Files
privatestudio/privatestudio/studio/uploads.py
T
Shaun KrugerandClaude Opus 5.5 3bbb57760e Add resumable multipart uploads for large files
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>
2026-12-01 17:29:46 -07:00

235 lines
9.8 KiB
Python

"""Multipart uploads, shared by the S3 API and the browser uploader."""
import hashlib
import math
import uuid
from typing import Iterable, Optional
from django.conf import settings
from django.db import transaction
from django.utils import timezone
from privatestudio.studio.models import MultipartUpload, UploadedAsset, UploadPart, UploadStatus
from privatestudio.studio.request_body import RequestBody
from privatestudio.studio.storage import LockBusy, UploadGone, get_storage
MIB = 1024 * 1024
MAX_PARTS = 10_000
MAX_PART_SIZE = 5 * 1024 * MIB
class UploadError(Exception):
def __init__(self, status: int, code: str, message: str):
super().__init__(message)
self.status, self.code, self.message = status, code, message
def _no_such_upload() -> UploadError:
return UploadError(404, "NoSuchUpload", "The upload does not exist or is no longer active")
def _busy() -> UploadError:
return UploadError(503, "SlowDown", "The upload is being completed by another request")
def record_asset(studio, user, key: str, filename: str, size: int) -> UploadedAsset:
asset, _ = UploadedAsset.objects.update_or_create(
studio=studio,
s3_path=key,
defaults={
"uploaded_by": user,
"filename": filename,
"size": size,
"upload_timestamp": timezone.now(),
},
)
return asset
def choose_part_size(total_size: int) -> int:
"""The configured part size, or the whole MiB size that fits into MAX_PARTS."""
configured = settings.PRIVATESTUDIO_UPLOAD_PART_SIZE
if total_size <= configured * MAX_PARTS:
return configured
return math.ceil(total_size / MAX_PARTS / MIB) * MIB
def part_count(upload: MultipartUpload) -> int:
return max(1, math.ceil(upload.total_size / upload.part_size))
def expected_part_size(upload: MultipartUpload, number: int) -> int:
if number < part_count(upload):
return upload.part_size
return upload.total_size - (number - 1) * upload.part_size
def create(
studio, user, key: str, total_size: Optional[int] = None,
last_modified: Optional[int] = None, overwrite: bool = True,
) -> MultipartUpload:
"""Start an upload. ``total_size`` is known for browser uploads only."""
storage = get_storage()
storage.validate_key(studio.bucket_name, key)
part_size = None
if total_size is not None:
limit = settings.PRIVATESTUDIO_UPLOAD_MAX_SIZE
if (limit and total_size > limit) or total_size > MAX_PARTS * MAX_PART_SIZE:
raise UploadError(413, "EntityTooLarge", "The file is larger than the allowed size")
# The parts and the joined file exist together for a while.
if storage.free_space() < 2 * total_size:
raise UploadError(507, "InsufficientStorage", "There is not enough free disk space for this file")
part_size = choose_part_size(total_size)
if not overwrite and storage.object_exists(studio.bucket_name, key):
raise UploadError(409, "ObjectExists", "A file with this name already exists")
upload_id = uuid.uuid4()
storage.create_upload(upload_id)
try:
return MultipartUpload.objects.create(
upload_id=upload_id, studio=studio, created_by=user, key=key,
filename=key.rsplit("/", 1)[-1], total_size=total_size, part_size=part_size,
last_modified=last_modified, overwrite=overwrite,
)
except BaseException:
storage.remove_upload(upload_id)
raise
def put_part(upload: MultipartUpload, number: int, request) -> str:
"""Stream the request body into a part and return its ETag. Sending a part again replaces it."""
if not 1 <= number <= MAX_PARTS:
raise UploadError(400, "InvalidArgument", f"Part number must be between 1 and {MAX_PARTS}")
if upload.status != UploadStatus.ACTIVE:
raise _no_such_upload()
expected = None
if upload.total_size is not None:
if number > part_count(upload):
raise UploadError(400, "InvalidArgument", "Part number is past the end of the file")
expected = expected_part_size(upload, number)
storage = get_storage()
body = RequestBody(request, max_bytes=MAX_PART_SIZE if expected is None else expected)
try:
staged, result = storage.stage_part(upload.upload_id, body)
try:
body.verify_write(result)
if expected is not None and result.size != expected:
raise UploadError(400, "IncompleteBody", f"Part {number} must be {expected} bytes")
with storage.lock_upload(upload.upload_id):
upload.refresh_from_db()
if upload.status != UploadStatus.ACTIVE:
raise _no_such_upload()
storage.publish_part(upload.upload_id, number, result.md5, staged)
# A single upsert: update_or_create's read-then-write can hit SQLite
# lock errors when several parts arrive at once.
UploadPart.objects.bulk_create(
[UploadPart(upload=upload, part_number=number, size=result.size, etag=result.md5)],
update_conflicts=True,
unique_fields=["upload", "part_number"],
update_fields=["size", "etag", "uploaded_at"],
)
storage.remove_replaced_parts(upload.upload_id, number, result.md5)
finally:
staged.unlink(missing_ok=True)
except (UploadGone, MultipartUpload.DoesNotExist):
raise _no_such_upload() from None
except LockBusy:
raise _busy() from None
return result.md5
def _select_parts(upload: MultipartUpload, requested: Optional[Iterable[tuple[int, str]]]) -> list[UploadPart]:
stored = {p.part_number: p for p in upload.parts.all()}
if upload.total_size is not None:
missing = [n for n in range(1, part_count(upload) + 1) if n not in stored]
if missing:
raise UploadError(400, "InvalidPart", f"{len(missing)} parts are missing, first: {missing[0]}")
if requested is None:
return [stored[n] for n in sorted(stored)]
requested = list(requested)
if not requested:
raise UploadError(400, "MalformedXML", "No parts were listed")
selected, previous = [], 0
for number, etag in requested:
if number <= previous:
raise UploadError(400, "InvalidPartOrder", "Parts must be listed in ascending order")
previous = number
part = stored.get(number)
if part is None or part.etag != etag.strip().strip('"').lower():
raise UploadError(400, "InvalidPart", f"Part {number} is missing or its ETag does not match")
selected.append(part)
return selected
def complete(
upload: MultipartUpload, requested: Optional[Iterable[tuple[int, str]]] = None, overwrite: bool = False,
) -> MultipartUpload:
"""
Join the parts into the final object. Completing a completed upload returns it again.
``requested`` lists ``(part_number, etag)``. None means every stored part.
"""
if upload.status == UploadStatus.COMPLETED:
return upload
storage = get_storage()
studio = upload.studio
try:
# Long enough to wait out a part being published, but not another join.
with storage.lock_upload(upload.upload_id, timeout=2):
upload.refresh_from_db()
if upload.status == UploadStatus.COMPLETED:
return upload
if upload.status != UploadStatus.ACTIVE:
raise _no_such_upload()
parts = _select_parts(upload, requested)
size = sum(p.size for p in parts)
if upload.total_size is not None and size != upload.total_size:
raise UploadError(400, "InvalidPart", "The parts do not add up to the file size")
limit = settings.PRIVATESTUDIO_UPLOAD_MAX_SIZE
if limit and size > limit:
raise UploadError(413, "EntityTooLarge", "The file is larger than the allowed size")
if not (overwrite or upload.overwrite) and storage.object_exists(studio.bucket_name, upload.key):
raise UploadError(409, "ObjectExists", "A file with this name already exists")
storage.assemble(
upload.upload_id, [(p.part_number, p.etag, p.size) for p in parts],
studio.bucket_name, upload.key,
)
digests = b"".join(bytes.fromhex(p.etag) for p in parts)
etag = f"{hashlib.md5(digests, usedforsecurity=False).hexdigest()}-{len(parts)}"
with transaction.atomic():
upload.status = UploadStatus.COMPLETED
upload.etag = etag
upload.save(update_fields=["status", "etag"])
record_asset(studio, upload.created_by, upload.key, upload.filename, size)
storage.remove_upload(upload.upload_id)
except (UploadGone, MultipartUpload.DoesNotExist):
# Another request may have completed it between our two checks.
current = MultipartUpload.objects.filter(pk=upload.pk).first()
if current and current.status == UploadStatus.COMPLETED:
return current
raise _no_such_upload() from None
except LockBusy:
raise _busy() from None
return upload
def abort(upload: MultipartUpload) -> None:
if upload.status != UploadStatus.ACTIVE:
raise _no_such_upload()
storage = get_storage()
try:
with storage.lock_upload(upload.upload_id, timeout=5):
upload.refresh_from_db()
if upload.status != UploadStatus.ACTIVE:
raise _no_such_upload()
upload.status = UploadStatus.ABORTED
upload.save(update_fields=["status"])
upload.parts.all().delete()
storage.remove_upload(upload.upload_id)
except LockBusy:
raise _busy() from None
except UploadGone:
MultipartUpload.objects.filter(pk=upload.pk, status=UploadStatus.ACTIVE).update(status=UploadStatus.ABORTED)