This commit is contained in:
2026-11-10 19:24:33 +03:00
parent c594b88a46
commit b55b230533
23 changed files with 1200 additions and 73 deletions
+61 -24
View File
@@ -1,8 +1,9 @@
import hashlib
import json
import re
import tempfile
import uuid
from typing import Optional, Sequence, Type, TypeVar
from typing import BinaryIO, Optional, Sequence, Tuple, Type, TypeVar
from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse
@@ -12,11 +13,15 @@ from starlette.responses import Response
from .auth import BASIC_CHALLENGE, BEARER_CHALLENGE, parse_basic, parse_bearer
from .drain import draining
from .errors import invalid_request, not_found, payload_too_large, unauthorized, unavailable, unsupported_media_type
from .images import MAX_UPLOAD_BYTES, inspect_image
from .images import INSPECT_PREFIX, MAX_UPLOAD_BYTES, inspect_image, inspect_prefix
from .pagination import encode_cursor, parse_page
from .schemas import CreateChat, CreateMessage, CreateUser
from .store import Chat, Store, User
# Bytes kept in RAM before SpooledTemporaryFile rolls over to an ephemeral file.
# The original is never persisted on the API volume; the spool dies with the request.
_SPOOL_RAM = 64 * 1024
router = APIRouter()
Body = TypeVar('Body', bound=BaseModel)
@@ -77,21 +82,50 @@ def _declared_image_type(value: Optional[str]) -> str:
return media
async def _read_upload(request: Request) -> bytes:
declared = request.headers.get('content-length')
if declared is not None:
async def _spool_upload(request: Request, declared: str) -> Tuple[BinaryIO, int, str, str]:
"""Stream the body into a size-capped spool, hash it, and inspect the header.
Returns (spool, size, sha256, sniffed_type). The caller must close the spool.
One request never holds more than INSPECT_PREFIX plus _SPOOL_RAM in Python heap;
the rest, if any, is an ephemeral tempfile deleted in finally.
"""
length = request.headers.get('content-length')
if length is not None:
try:
size = int(declared)
size = int(length)
except ValueError:
raise invalid_request('Некорректный Content-Length') from None
if size > MAX_UPLOAD_BYTES:
raise payload_too_large('Файл больше 10 МиБ')
buf = bytearray()
async for chunk in request.stream():
if len(buf) + len(chunk) > MAX_UPLOAD_BYTES:
raise payload_too_large('Файл больше 10 МиБ')
buf.extend(chunk)
return bytes(buf)
spool = tempfile.SpooledTemporaryFile(max_size=_SPOOL_RAM)
hasher = hashlib.sha256()
head = bytearray()
total = 0
sniffed: Optional[str] = None
try:
async for chunk in request.stream():
if not chunk:
continue
if total + len(chunk) > MAX_UPLOAD_BYTES:
raise payload_too_large('Файл больше 10 МиБ')
hasher.update(chunk)
spool.write(chunk)
total += len(chunk)
if len(head) < INSPECT_PREFIX:
head.extend(chunk[: INSPECT_PREFIX - len(head)])
if sniffed is None and len(head) >= 24:
sniffed = inspect_prefix(bytes(head), complete=False)
if sniffed is not None and sniffed != declared:
raise unsupported_media_type('Содержимое не соответствует Content-Type')
if sniffed is None:
sniffed = inspect_image(bytes(head))
if sniffed != declared:
raise unsupported_media_type('Содержимое не соответствует Content-Type')
spool.seek(0)
return spool, total, hasher.hexdigest(), sniffed
except BaseException:
spool.close()
raise
async def _member_chat(store: Store, chat_id: str, actor: User) -> Chat:
@@ -231,18 +265,21 @@ async def upload_attachment(
chat = await _member_chat(store, chat_id, actor)
filename = _filename(request.query_params.get('filename'))
declared = _declared_image_type(request.headers.get('content-type'))
data = await _read_upload(request)
actual = inspect_image(data)
if actual != declared:
raise unsupported_media_type('Содержимое не соответствует Content-Type')
attachment = await store.create_attachment(
chat.id,
actor.id,
filename,
actual,
data,
hashlib.sha256(data).hexdigest(),
)
spool = None
try:
spool, size, digest, actual = await _spool_upload(request, declared)
attachment = await store.create_attachment(
chat.id,
actor.id,
filename,
actual,
spool,
size,
digest,
)
finally:
if spool is not None:
spool.close()
return JSONResponse(attachment.to_dict(), status_code=201)