forked from mtusi2026/mtusi2026lab4
Добавить приватное хранилище вложений и отдачу файла через API.
Байты лежат в SeaweedFS, метаданные в Postgres. Другая реплика скачивает тот же объект, потому что локальный диск API не является источником файла.
This commit is contained in:
+96
-3
@@ -4,14 +4,16 @@ import binascii
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import JSONResponse, Response
|
||||
|
||||
from app import cache, config, db, rediscli, sessions, store
|
||||
from app import attachments, cache, config, db, images, rediscli, s3, sessions, store
|
||||
from app.cursor_codec import decode_cursor, encode_cursor
|
||||
from app.errors import BASIC_CHALLENGE, BEARER_CHALLENGE, AppError, error_response
|
||||
from app.passwords import dummy_hash, hash_password, verify_password
|
||||
from app.validation import (
|
||||
parse_json_body,
|
||||
require_exact_keys,
|
||||
parse_attachment_ids,
|
||||
validate_display_name,
|
||||
validate_filename,
|
||||
validate_limit,
|
||||
validate_idempotency_key,
|
||||
validate_message_text,
|
||||
@@ -52,6 +54,7 @@ async def health_ready(request: Request) -> Response:
|
||||
return error_response(503, "service is shutting down", rid)
|
||||
await db.ping()
|
||||
await rediscli.ping()
|
||||
await s3.head_bucket()
|
||||
return _json({"status": "ok"}, rid)
|
||||
|
||||
|
||||
@@ -202,9 +205,13 @@ async def create_message(request: Request) -> Response:
|
||||
if err:
|
||||
return error_response(400, err, rid)
|
||||
assert body is not None
|
||||
if require_exact_keys(body, {"text"}, {"text"}):
|
||||
if require_exact_keys(body, {"text", "attachment_ids"}, {"text"}):
|
||||
return error_response(400, "invalid message payload", rid)
|
||||
if validate_message_text(body["text"]):
|
||||
attachment_ids, attachment_err = parse_attachment_ids(body.get("attachment_ids"))
|
||||
if attachment_err:
|
||||
return error_response(400, attachment_err, rid)
|
||||
assert attachment_ids is not None
|
||||
if validate_message_text(body["text"], allow_blank=bool(attachment_ids)):
|
||||
return error_response(400, "invalid message text", rid)
|
||||
if validate_idempotency_key(request.headers.get("Idempotency-Key")):
|
||||
return error_response(400, "invalid idempotency key", rid)
|
||||
@@ -214,11 +221,14 @@ async def create_message(request: Request) -> Response:
|
||||
body["text"],
|
||||
request.headers.get("Idempotency-Key") or "",
|
||||
request.url.path,
|
||||
attachment_ids,
|
||||
)
|
||||
if msg_err == "not_found":
|
||||
return error_response(404, "chat not found", rid)
|
||||
if msg_err == "conflict":
|
||||
return error_response(409, "idempotency key reused with a different body", rid)
|
||||
if msg_err == "not_ready":
|
||||
return error_response(409, "attachment is not ready", rid)
|
||||
assert message is not None
|
||||
return _json(message, rid, 201)
|
||||
|
||||
@@ -253,6 +263,89 @@ async def list_messages(request: Request) -> Response:
|
||||
return _json({"items": page, "next_cursor": next_cursor}, rid)
|
||||
|
||||
|
||||
def _media_type(value: str) -> str:
|
||||
return value.split(";", 1)[0].strip().lower()
|
||||
|
||||
|
||||
async def _read_limited(request: Request, limit: int) -> bytes:
|
||||
received = bytearray()
|
||||
async for chunk in request.stream():
|
||||
if len(received) + len(chunk) > limit:
|
||||
raise AppError(413, "file exceeds upload limit")
|
||||
received.extend(chunk)
|
||||
return bytes(received)
|
||||
|
||||
|
||||
async def upload_attachment(request: Request) -> Response:
|
||||
rid = request.state.request_id
|
||||
user = await _bearer_user(request)
|
||||
chat_id = request.path_params["chat_id"]
|
||||
if validate_uuid(chat_id):
|
||||
return error_response(400, "invalid chat id", rid)
|
||||
if validate_filename(request.query_params.get("filename")):
|
||||
return error_response(400, "invalid filename", rid)
|
||||
filename = request.query_params.get("filename") or ""
|
||||
declared = _media_type(request.headers.get("content-type", ""))
|
||||
if declared not in ("image/png", "image/jpeg"):
|
||||
return error_response(415, "unsupported media type", rid)
|
||||
content_length = request.headers.get("content-length")
|
||||
if content_length is not None:
|
||||
try:
|
||||
announced = int(content_length)
|
||||
except ValueError:
|
||||
return error_response(400, "invalid content length", rid)
|
||||
if announced > config.MAX_UPLOAD_BYTES:
|
||||
return error_response(413, "file exceeds upload limit", rid)
|
||||
if announced <= 0:
|
||||
return error_response(415, "unsupported or damaged image", rid)
|
||||
if await store.load_chat_for_member(chat_id, user["id"]) is None:
|
||||
return error_response(404, "chat not found", rid)
|
||||
data = await _read_limited(request, config.MAX_UPLOAD_BYTES)
|
||||
if not data:
|
||||
return error_response(415, "unsupported or damaged image", rid)
|
||||
try:
|
||||
content_type = images.inspect_image(data, declared)
|
||||
except images.ImageRejected as exc:
|
||||
return error_response(exc.status, exc.message, rid)
|
||||
created = await attachments.create_attachment(chat_id, user["id"], filename, content_type, data)
|
||||
return _json(created, rid, 201)
|
||||
|
||||
|
||||
async def get_attachment(request: Request) -> Response:
|
||||
rid = request.state.request_id
|
||||
user = await _bearer_user(request)
|
||||
attachment_id = request.path_params["attachment_id"]
|
||||
if validate_uuid(attachment_id):
|
||||
return error_response(400, "invalid attachment id", rid)
|
||||
row = await attachments.get_for_member(attachment_id, user["id"])
|
||||
if row is None:
|
||||
return error_response(404, "attachment not found", rid)
|
||||
return _json(attachments._public(row), rid)
|
||||
|
||||
|
||||
async def download_attachment(request: Request) -> Response:
|
||||
rid = request.state.request_id
|
||||
user = await _bearer_user(request)
|
||||
attachment_id = request.path_params["attachment_id"]
|
||||
if validate_uuid(attachment_id):
|
||||
return error_response(400, "invalid attachment id", rid)
|
||||
variant = request.query_params.get("variant")
|
||||
if variant not in (None, "original"):
|
||||
return error_response(400, "invalid variant", rid)
|
||||
row = await attachments.get_for_member(attachment_id, user["id"])
|
||||
if row is None:
|
||||
return error_response(404, "attachment not found", rid)
|
||||
payload = await s3.get_bytes(row["object_key"])
|
||||
return Response(payload, status_code=200, media_type=row["content_type"], headers={"X-Request-Id": rid})
|
||||
|
||||
|
||||
async def lab_sweep(request: Request) -> Response:
|
||||
if not config.lab_mode():
|
||||
return error_response(404, "not found", request.state.request_id)
|
||||
deleted = await attachments.sweep_orphans()
|
||||
return _json({"deleted": deleted}, request.state.request_id)
|
||||
|
||||
|
||||
async def lab_metrics(request: Request) -> Response:
|
||||
if not config.lab_mode():
|
||||
return error_response(404, "not found", request.state.request_id)
|
||||
|
||||
Reference in New Issue
Block a user