feat: implement attachment endpoints and linking to messages

This commit is contained in:
2026-11-11 20:23:41 +03:00
parent 8ab7245f9c
commit b815cef838
+119 -36
View File
@@ -1,40 +1,42 @@
import os
import uuid
import socket
import uuid
import hashlib
import json
from contextvars import ContextVar
from datetime import datetime, timedelta, timezone
from typing import Optional
from uuid import UUID
from sqlalchemy.exc import IntegrityError
import hashlib
import json
INSTANCE_ID = os.environ.get("HOSTNAME", f"api-{socket.gethostname()}")
from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request
from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from sqlalchemy import select, text
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.middleware.base import BaseHTTPMiddleware
from .auth import (
SESSION_TTL,
create_session,
generate_token,
get_current_user,
hash_password,
hash_token,
revoke_current_session,
verify_password,
)
from .db.models import IdempotencyRecord, SessionRow, User
from .db.models import IdempotencyRecord, SessionRow, User, Attachment, MessageAttachment
from .db.session import get_db
from .models import CreateChat, CreateMessage, CreateUser
from .repositories import chats as chats_repo
from .repositories import messages as messages_repo
from .repositories import users as users_repo
from .s3_client import s3, BUCKET, ensure_bucket
from .image_utils import validate_image
# уникальный id инстанса (берется из имени контейнера в docker)
INSTANCE_ID = os.environ.get("HOSTNAME", f"api-{socket.gethostname()}")
request_id_var: ContextVar[str] = ContextVar("request_id", default="")
@@ -50,7 +52,6 @@ _HTTP_CODES = {
500: "internal_error",
}
def err_json(status: int, code: str, message: str) -> JSONResponse:
resp = JSONResponse(
status_code=status,
@@ -62,30 +63,33 @@ def err_json(status: int, code: str, message: str) -> JSONResponse:
}
},
)
# добавляем заголовок инстанса даже в ошибки
resp.headers["X-Instance-Id"] = INSTANCE_ID
return resp
class RequestIdMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
rid = request.headers.get("X-Request-Id") or uuid.uuid4().hex
request_id_var.set(rid)
response = await call_next(request)
response.headers["X-Request-Id"] = rid
# добавляем заголовок инстанса во все успешные ответы
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
app = FastAPI(title="MTUSI Messenger — lab2")
app = FastAPI(title="MTUSI Messenger — lab4")
app.add_middleware(RequestIdMiddleware)
security = HTTPBasic(auto_error=False)
# при старте приложения проверяем, что бакет в minio создан
@app.on_event("startup")
def startup_event():
ensure_bucket()
@app.exception_handler(RequestValidationError)
async def _validation(request: Request, exc: RequestValidationError):
return err_json(400, "invalid_request", "Validation error")
@app.exception_handler(HTTPException)
async def _http(request: Request, exc: HTTPException):
code = _HTTP_CODES.get(exc.status_code, "internal_error")
@@ -96,16 +100,13 @@ async def _http(request: Request, exc: HTTPException):
resp.headers[k] = v
return resp
@app.exception_handler(Exception)
async def _generic(request: Request, exc: Exception):
return err_json(500, "internal_error", "Internal server error")
def _iso_z(dt: datetime) -> str:
return dt.isoformat().replace("+00:00", "Z")
def _user_json(u: User) -> dict:
return {
"id": str(u.id),
@@ -114,7 +115,6 @@ def _user_json(u: User) -> dict:
"created_at": _iso_z(u.created_at),
}
def _chat_json(chat, member_ids: list[str]) -> dict:
return {
"id": str(chat.id),
@@ -123,7 +123,6 @@ def _chat_json(chat, member_ids: list[str]) -> dict:
"created_at": _iso_z(chat.created_at),
}
def _msg_json(m) -> dict:
return {
"id": str(m.id),
@@ -133,13 +132,26 @@ def _msg_json(m) -> dict:
"created_at": _iso_z(m.created_at),
}
# хелпер для формирования json метаданных вложения
def _attachment_json(att: Attachment) -> dict:
return {
"id": str(att.id),
"chat_id": str(att.chat_id),
"owner_id": str(att.owner_id),
"filename": att.filename,
"content_type": att.content_type,
"size_bytes": att.size_bytes,
"sha256": att.sha256,
"status": att.status,
"error_code": att.error_code,
"created_at": _iso_z(att.created_at),
}
# ---------- health ----------
@app.get("/health/live")
def live():
return {"status": "ok"}
@app.get("/health/ready")
async def ready(db: AsyncSession = Depends(get_db)):
try:
@@ -148,7 +160,6 @@ async def ready(db: AsyncSession = Depends(get_db)):
return err_json(503, "unavailable", "Database unavailable")
return {"status": "ok"}
# ---------- users ----------
@app.post("/api/v1/users", status_code=201)
async def register(body: CreateUser, db: AsyncSession = Depends(get_db)):
@@ -163,7 +174,6 @@ async def register(body: CreateUser, db: AsyncSession = Depends(get_db)):
raise HTTPException(409, "Username already exists")
return _user_json(user)
# ---------- sessions ----------
@app.post("/api/v1/auth/sessions", status_code=201)
async def login(
@@ -190,17 +200,14 @@ async def login(
"user": _user_json(user),
}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
async def logout(authorization: str = Header(...), db: AsyncSession = Depends(get_db)):
await revoke_current_session(authorization, db)
@app.get("/api/v1/users/me")
async def me(user: User = Depends(get_current_user)):
return _user_json(user)
# ---------- chats ----------
@app.post("/api/v1/chats", status_code=201)
async def create_chat(
@@ -216,7 +223,6 @@ async def create_chat(
raise HTTPException(404, "Member not found")
return _chat_json(chat, [str(x) for x in body.member_ids])
@app.get("/api/v1/chats")
async def list_chats(
user: User = Depends(get_current_user),
@@ -239,7 +245,6 @@ async def list_chats(
nxt = f"{next_cursor[0].isoformat()}|{next_cursor[1]}" if next_cursor else None
return {"items": items, "next_cursor": nxt}
@app.get("/api/v1/chats/{chat_id}")
async def get_chat(
chat_id: UUID,
@@ -252,7 +257,6 @@ async def get_chat(
members = await chats_repo.list_member_ids(db, chat.id)
return _chat_json(chat, [str(m) for m in members])
# ---------- messages ----------
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
async def post_message(
@@ -268,7 +272,7 @@ async def post_message(
req_hash = hashlib.sha256(body.model_dump_json().encode("utf-8")).hexdigest()
# 1. Проверяем, есть ли уже такой ключ
# проверяем, есть ли уже такой ключ идемпотентности
stmt = select(IdempotencyRecord).where(
IdempotencyRecord.user_id == user.id,
IdempotencyRecord.key == idempotency_key,
@@ -278,14 +282,25 @@ async def post_message(
if record:
if record.request_hash != req_hash:
raise HTTPException(409, "Idempotency key conflict")
# Возвращаем сохраненный ответ (201 и тот же JSON)
# возвращаем сохраненный ответ (201 и тот же JSON)
return JSONResponse(status_code=201, content=json.loads(record.response_body))
# 2. Создаём сообщение
# создаем сообщение
msg = await messages_repo.create_and_invalidate(db, chat_id, user.id, body.text)
resp_body = json.dumps(_msg_json(msg))
# привязываем вложения, если они были переданы
if body.attachment_ids:
for att_id in body.attachment_ids:
att = await db.get(Attachment, att_id)
if not att or att.chat_id != chat_id:
raise HTTPException(404, f"Attachment {att_id} not found in this chat")
db.add(MessageAttachment(message_id=msg.id, attachment_id=att_id))
resp_dict = _msg_json(msg)
resp_dict["attachment_ids"] = [str(a) for a in (body.attachment_ids or [])]
resp_body = json.dumps(resp_dict)
# 3. Сохраняем ключ
# сохраняем ключ идемпотентности
db.add(IdempotencyRecord(
user_id=user.id,
key=idempotency_key,
@@ -295,7 +310,7 @@ async def post_message(
try:
await db.commit()
except IntegrityError:
# Гонка: другая реплика уже вставила этот ключ
# гонка: другая реплика уже вставила этот ключ
await db.rollback()
record = (await db.execute(stmt)).scalar_one_or_none()
if record and record.request_hash == req_hash:
@@ -304,7 +319,6 @@ async def post_message(
return JSONResponse(status_code=201, content=json.loads(resp_body))
@app.get("/api/v1/chats/{chat_id}/messages")
async def list_messages(
chat_id: UUID,
@@ -330,7 +344,76 @@ async def list_messages(
nxt = f"{next_cursor[0].isoformat()}|{next_cursor[1]}" if next_cursor else None
return {"items": [_msg_json(m) for m in rows], "next_cursor": nxt}
# ---------- attachments ----------
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=201)
async def upload_attachment(
chat_id: UUID,
filename: str = Query(..., min_length=1, max_length=255),
request: Request = None,
user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
# проверяем, что чат существует и юзер в нем состоит
chat = await chats_repo.get_if_member(db, chat_id, user.id)
if not chat:
raise HTTPException(404, "Chat not found")
# читаем сырые байты из тела запроса
content = await request.body()
# валидируем картинку (размер и формат)
mime = validate_image(content)
sha256 = hashlib.sha256(content).hexdigest()
ext = ".png" if mime == "image/png" else ".jpg"
s3_key = f"{chat_id}/{uuid.uuid4()}{ext}"
# загружаем в minio
s3.put_object(Bucket=BUCKET, Key=s3_key, Body=content, ContentType=mime)
# сохраняем метаданные в базу
att = Attachment(
chat_id=chat_id, owner_id=user.id, filename=filename,
content_type=mime, size_bytes=len(content), sha256=sha256,
status="ready", s3_key=s3_key,
)
db.add(att)
await db.commit()
await db.refresh(att)
return _attachment_json(att)
@app.get("/api/v1/attachments/{attachment_id}")
async def get_attachment(
attachment_id: UUID,
user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
att = await db.get(Attachment, attachment_id)
if not att:
raise HTTPException(404, "Attachment not found")
chat = await chats_repo.get_if_member(db, att.chat_id, user.id)
if not chat:
raise HTTPException(404, "Attachment not found")
return _attachment_json(att)
@app.get("/api/v1/attachments/{attachment_id}/content")
async def download_attachment(
attachment_id: UUID,
user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
att = await db.get(Attachment, attachment_id)
if not att:
raise HTTPException(404, "Attachment not found")
chat = await chats_repo.get_if_member(db, att.chat_id, user.id)
if not chat:
raise HTTPException(404, "Attachment not found")
# вытаскиваем файл из minio и отдаем его клиенту
obj = s3.get_object(Bucket=BUCKET, Key=att.s3_key)
content = obj["Body"].read()
return Response(content=content, media_type=att.content_type)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("APP_PORT", "8080")))