NarratifAI / src /companion.py
Consulawtech's picture
Accept resumable Companion uploads with atomic job deduplication
01864c7
Raw History Blame Contribute Delete
2.24 kB
"""Owner-bound, bounded assembly of resumable Companion uploads."""
import uuid
from fastapi import HTTPException
CHUNK_SIZE = 512 * 1024
MAX_BYTES = 240 * 1024 * 1024
def load_upload(uid, recording_id, request):
try:
recording_id = str(uuid.UUID(recording_id))
except (ValueError, TypeError, AttributeError):
raise HTTPException(400, 'Invalid recording')
rows = request('GET', '/rest/v1/companion_uploads', params={'id': f'eq.{recording_id}', 'firebase_uid': f'eq.{uid}', 'limit': '1'})
if rows is None:
raise HTTPException(503, 'Upload storage unavailable. Retry to resume.')
if not rows:
raise HTTPException(404, 'Upload not found for this account')
return rows[0]
def assemble_upload(upload, request):
size = upload.get('bytes')
if not isinstance(size, int) or not 0 < size <= MAX_BYTES:
raise HTTPException(400, 'Invalid upload size')
count = (size + CHUNK_SIZE - 1) // CHUNK_SIZE
content = bytearray()
# Bound each database response; never request a 480 MiB JSON response.
for offset in range(0, count, 4):
rows = request('GET', '/rest/v1/companion_chunks', params={
'upload_id': f'eq.{upload["id"]}', 'select': 'index,data', 'order': 'index.asc',
'offset': str(offset), 'limit': str(min(4, count-offset))})
if rows is None:
raise HTTPException(503, 'Upload storage unavailable. Retry to resume.')
if len(rows) != min(4, count-offset):
raise HTTPException(409, 'Upload incomplete. Resume uploading first.')
for i, row in enumerate(rows, offset):
if row['index'] != i:
raise HTTPException(409, 'Upload incomplete')
try:
raw = row['data']
if not isinstance(raw, str) or not raw.startswith('\\x'):
raise ValueError()
part = bytes.fromhex(raw[2:])
except (ValueError, TypeError):
raise HTTPException(503, 'Stored upload is invalid')
if len(part) != min(CHUNK_SIZE, size - i * CHUNK_SIZE):
raise HTTPException(409, 'Upload chunk size mismatch')
content.extend(part)
return bytes(content)