Добавил наблюдаемость
This commit is contained in:
@@ -0,0 +1,164 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import tempfile
|
||||
import unicodedata
|
||||
import warnings
|
||||
from uuid import uuid4
|
||||
|
||||
import anyio
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.requests import ClientDisconnect
|
||||
|
||||
from .errors import ApiError, invalid, not_found
|
||||
from .storage import serialize
|
||||
from .broker import envelope, publish
|
||||
from .telemetry import event
|
||||
|
||||
|
||||
MAX_BYTES = 10485760
|
||||
MAX_PIXELS = 40000000
|
||||
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
|
||||
FIELDS = "id,chat_id,owner_id,filename,content_type,size_bytes,sha256,status,error_code,created_at,updated_at"
|
||||
|
||||
|
||||
def public(row):
|
||||
return {**serialize(row), "variants": []}
|
||||
|
||||
|
||||
def filename_value(value):
|
||||
if not 1 <= len(value) <= 255 or not value.strip():
|
||||
raise invalid("Неверное имя файла")
|
||||
if any(c in "/\\" or unicodedata.category(c) == "Cc" for c in value):
|
||||
raise invalid("Неверное имя файла")
|
||||
try:
|
||||
value.encode("utf-8")
|
||||
except UnicodeError:
|
||||
raise invalid("Неверное имя файла") from None
|
||||
return value
|
||||
|
||||
|
||||
def validate_image(source, media_type):
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
source.seek(0)
|
||||
with Image.open(source, formats=["PNG", "JPEG"]) as image:
|
||||
if image.width * image.height > MAX_PIXELS:
|
||||
raise ApiError(413, "payload_too_large", "Слишком много пикселей")
|
||||
actual = {"PNG": "image/png", "JPEG": "image/jpeg"}[image.format]
|
||||
if actual != media_type:
|
||||
raise ApiError(415, "unsupported_media_type", "Формат не совпадает с Content-Type")
|
||||
image.verify()
|
||||
source.seek(0)
|
||||
with Image.open(source, formats=["PNG", "JPEG"]) as image:
|
||||
image.load()
|
||||
except (Image.DecompressionBombWarning, Image.DecompressionBombError):
|
||||
raise ApiError(413, "payload_too_large", "Слишком много пикселей") from None
|
||||
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
|
||||
raise ApiError(415, "unsupported_media_type", "Повреждённое изображение") from None
|
||||
|
||||
|
||||
class Attachments:
|
||||
def __init__(self, store, objects):
|
||||
self.store = store
|
||||
self.objects = objects
|
||||
self.slots = asyncio.Semaphore(2)
|
||||
|
||||
async def receive(self, request, chat_id, filename):
|
||||
user_id = request.state.user_id
|
||||
await run_in_threadpool(self.store.chat, user_id, chat_id)
|
||||
filename = filename_value(filename)
|
||||
media_type = request.headers.get("Content-Type", "").split(";", 1)[0].strip().lower()
|
||||
if media_type not in ("image/png", "image/jpeg"):
|
||||
raise ApiError(415, "unsupported_media_type", "Нужен PNG или JPEG")
|
||||
declared = request.headers.get("Content-Length")
|
||||
if declared is not None:
|
||||
if not declared.isascii() or not declared.isdecimal() or len(declared) > 18:
|
||||
raise invalid("Неверный Content-Length")
|
||||
if int(declared) > MAX_BYTES:
|
||||
raise ApiError(413, "payload_too_large", "Файл больше 10 MiB")
|
||||
try:
|
||||
await asyncio.wait_for(self.slots.acquire(), timeout=15)
|
||||
except TimeoutError:
|
||||
raise ApiError(429, "rate_limited", "Загрузки заняты", {"Retry-After": "1"}) from None
|
||||
try:
|
||||
with tempfile.TemporaryFile(mode="w+b") as source:
|
||||
size, checksum = 0, hashlib.sha256()
|
||||
try:
|
||||
with anyio.fail_after(15):
|
||||
async for chunk in request.stream():
|
||||
size += len(chunk)
|
||||
if size > MAX_BYTES:
|
||||
raise ApiError(413, "payload_too_large", "Файл больше 10 MiB")
|
||||
checksum.update(chunk)
|
||||
await run_in_threadpool(source.write, chunk)
|
||||
except (TimeoutError, ClientDisconnect):
|
||||
raise invalid("Загрузка прервана или слишком медленная") from None
|
||||
await run_in_threadpool(validate_image, source, media_type)
|
||||
return await run_in_threadpool(
|
||||
self.publish, user_id, chat_id, filename, media_type, size, checksum.hexdigest(), source,
|
||||
)
|
||||
finally:
|
||||
self.slots.release()
|
||||
|
||||
def publish(self, user_id, chat_id, filename, media_type, size, checksum, source):
|
||||
attachment_id, job_id = uuid4(), uuid4()
|
||||
stage = "staging/" + attachment_id.hex
|
||||
key = "originals/" + str(attachment_id)
|
||||
with self.store.connection() as connection:
|
||||
self.store.require_chat(connection, user_id, chat_id)
|
||||
connection.execute(
|
||||
"INSERT INTO upload_intents(id,chat_id,owner_id,object_key) VALUES (%s,%s,%s,%s)",
|
||||
(attachment_id, chat_id, user_id, stage),
|
||||
)
|
||||
with self.store.connection() as connection:
|
||||
connection.execute("SELECT id FROM upload_intents WHERE id=%s FOR UPDATE", (attachment_id,))
|
||||
self.objects.put(stage, source, size, media_type)
|
||||
row = connection.execute(
|
||||
"INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,object_key,status) "
|
||||
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,'queued') RETURNING " + FIELDS,
|
||||
(attachment_id, chat_id, user_id, filename, media_type, size, checksum, key),
|
||||
).fetchone()
|
||||
job = connection.execute(
|
||||
"INSERT INTO attachment_jobs(id,attachment_id,staging_key) VALUES (%s,%s,%s) RETURNING *",
|
||||
(job_id, attachment_id, stage),
|
||||
).fetchone()
|
||||
connection.execute("DELETE FROM upload_intents WHERE id=%s", (attachment_id,))
|
||||
publish(envelope(job))
|
||||
with self.store.connection() as connection:
|
||||
connection.execute("UPDATE attachment_jobs SET published_at=clock_timestamp() WHERE id=%s", (job_id,))
|
||||
event("job.accepted", job_id=str(job_id))
|
||||
return public(row)
|
||||
|
||||
def get(self, user_id, attachment_id, internal=False):
|
||||
with self.store.connection() as connection:
|
||||
row = connection.execute(
|
||||
"SELECT " + FIELDS + (",object_key" if internal else "") + " FROM attachments a "
|
||||
"WHERE a.id=%s AND EXISTS (SELECT 1 FROM chat_members m "
|
||||
"WHERE m.chat_id=a.chat_id AND m.user_id=%s)", (attachment_id, user_id),
|
||||
).fetchone()
|
||||
if not row:
|
||||
raise not_found()
|
||||
variants = connection.execute(
|
||||
"SELECT name,content_type,width,height,size_bytes,sha256 FROM attachment_variants "
|
||||
"WHERE attachment_id=%s ORDER BY name", (attachment_id,),
|
||||
).fetchall() if row['status'] == 'ready' else []
|
||||
if internal:
|
||||
return row
|
||||
return {**public(row), "variants": serialize(variants)}
|
||||
|
||||
def content(self, user_id, attachment_id, variant):
|
||||
row = self.get(user_id, attachment_id, internal=True)
|
||||
if row['status'] != 'ready':
|
||||
raise ApiError(409, 'conflict', 'Файл ещё не готов')
|
||||
if variant == 'original':
|
||||
return row
|
||||
with self.store.connection() as connection:
|
||||
found = connection.execute(
|
||||
"SELECT object_key,content_type,size_bytes FROM attachment_variants "
|
||||
"WHERE attachment_id=%s AND name=%s", (attachment_id, variant),
|
||||
).fetchone()
|
||||
if not found:
|
||||
raise not_found()
|
||||
return {**row, **found}
|
||||
Reference in New Issue
Block a user