Реализовала требования лабы 4 на оценку 4
This commit is contained in:
@@ -0,0 +1,238 @@
|
||||
"""Вложения (lab4): синхронный binary upload PNG/JPEG, авторизованный download."""
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import unicodedata
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from fastapi.responses import Response
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
from ..models.schemas import Attachment, User
|
||||
from ..storage import s3
|
||||
from ..storage.postgres import storage
|
||||
from .security import current_user
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/v1", tags=["attachments"])
|
||||
|
||||
MAX_UPLOAD_BYTES = int(os.environ.get("MAX_UPLOAD_BYTES", "10485760"))
|
||||
MAX_IMAGE_PIXELS = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000"))
|
||||
|
||||
|
||||
def _require_member(chat_id: UUID, user_id: UUID):
|
||||
chat = storage.get_chat(chat_id)
|
||||
if chat is None or user_id not in chat.member_ids:
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
return chat
|
||||
|
||||
|
||||
def _validate_filename(name: str) -> str:
|
||||
if not name or len(name) > 255:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
if name.strip() != name or name.strip() == "":
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
for ch in name:
|
||||
if ch in ("/", "\\", "\x00") or unicodedata.category(ch).startswith("C"):
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
return name
|
||||
|
||||
|
||||
def _detect_content_type(data: bytes) -> Optional[str]:
|
||||
"""MIME по содержимому, не по заголовку."""
|
||||
if data.startswith(b"\x89PNG\r\n\x1a\n"):
|
||||
return "image/png"
|
||||
if data.startswith(b"\xff\xd8\xff"):
|
||||
return "image/jpeg"
|
||||
return None
|
||||
|
||||
|
||||
def _read_limited_body(request: Request) -> bytes:
|
||||
"""Читает тело запроса с жёстким лимитом MAX_UPLOAD_BYTES.
|
||||
|
||||
Content-Length проверяется до чтения. Потоково читаем и режем на лимите,
|
||||
чтобы клиент не мог прислать больше.
|
||||
"""
|
||||
cl = request.headers.get("content-length")
|
||||
if cl is not None:
|
||||
try:
|
||||
if int(cl) > MAX_UPLOAD_BYTES:
|
||||
raise HTTPException(status_code=413, detail="payload_too_large")
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
chunks = []
|
||||
total = 0
|
||||
# Синхронное чтение — FastAPI уже выполнил sync-endpoint в threadpool.
|
||||
iterator = request.stream()
|
||||
import asyncio
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
chunk = loop.run_until_complete(iterator.__anext__())
|
||||
except StopAsyncIteration:
|
||||
break
|
||||
if not chunk:
|
||||
continue
|
||||
total += len(chunk)
|
||||
if total > MAX_UPLOAD_BYTES:
|
||||
raise HTTPException(status_code=413, detail="payload_too_large")
|
||||
chunks.append(chunk)
|
||||
finally:
|
||||
loop.close()
|
||||
return b"".join(chunks)
|
||||
|
||||
|
||||
def _validate_image(data: bytes) -> str:
|
||||
"""Проверяет формат по содержимому и лимит пикселей до полной распаковки."""
|
||||
ctype = _detect_content_type(data)
|
||||
if ctype is None:
|
||||
raise HTTPException(status_code=415, detail="unsupported_media_type")
|
||||
# Pillow позволяет узнать размеры без полной распаковки.
|
||||
try:
|
||||
img = Image.open(io.BytesIO(data))
|
||||
width, height = img.size
|
||||
except (UnidentifiedImageError, OSError):
|
||||
raise HTTPException(status_code=415, detail="unsupported_media_type")
|
||||
if width <= 0 or height <= 0:
|
||||
raise HTTPException(status_code=415, detail="unsupported_media_type")
|
||||
if width * height > MAX_IMAGE_PIXELS:
|
||||
raise HTTPException(status_code=413, detail="payload_too_large")
|
||||
# Реальное декодирование пикселей для проверки целостности (bomb-защита
|
||||
# уже отработала по лимиту выше).
|
||||
try:
|
||||
img.load()
|
||||
except Exception:
|
||||
raise HTTPException(status_code=415, detail="unsupported_media_type")
|
||||
return ctype
|
||||
|
||||
|
||||
def _attachment_response(att: Attachment) -> Attachment:
|
||||
return att
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/chats/{chat_id}/attachments",
|
||||
summary="Принять один PNG/JPEG, до 10 MiB",
|
||||
response_model=Attachment,
|
||||
status_code=201,
|
||||
)
|
||||
async def upload_attachment(
|
||||
chat_id: UUID,
|
||||
request: Request,
|
||||
user: User = Depends(current_user),
|
||||
filename: str = Query(...),
|
||||
) -> Attachment:
|
||||
_require_member(chat_id, user.id)
|
||||
safe_name = _validate_filename(filename)
|
||||
|
||||
# Читаем потоково с ограничением, не доверяя Content-Length.
|
||||
chunks: list[bytes] = []
|
||||
total = 0
|
||||
async for chunk in request.stream():
|
||||
if not chunk:
|
||||
continue
|
||||
total += len(chunk)
|
||||
if total > MAX_UPLOAD_BYTES:
|
||||
raise HTTPException(status_code=413, detail="payload_too_large")
|
||||
chunks.append(chunk)
|
||||
body = b"".join(chunks)
|
||||
|
||||
if len(body) == 0:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
if len(body) > MAX_UPLOAD_BYTES:
|
||||
raise HTTPException(status_code=413, detail="payload_too_large")
|
||||
|
||||
content_type = _validate_image(body)
|
||||
sha256 = hashlib.sha256(body).hexdigest()
|
||||
|
||||
attachment_id = uuid4()
|
||||
object_key = s3.original_key(chat_id, attachment_id)
|
||||
|
||||
# 1) Сначала сохраняем в S3. Если следующий шаг упадёт — компенсируем.
|
||||
try:
|
||||
s3.put_bytes(object_key, body, content_type)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise HTTPException(status_code=503, detail="unavailable") from exc
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
att = Attachment(
|
||||
id=attachment_id,
|
||||
chat_id=chat_id,
|
||||
owner_id=user.id,
|
||||
filename=safe_name,
|
||||
content_type=content_type,
|
||||
size_bytes=len(body),
|
||||
sha256=sha256,
|
||||
status="ready",
|
||||
variants=[],
|
||||
error_code=None,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
|
||||
# 2) INSERT метаданных. При сбое — удаляем объект из S3 (компенсация).
|
||||
try:
|
||||
storage.create_attachment(att, object_key)
|
||||
except Exception:
|
||||
try:
|
||||
s3.delete_object(object_key)
|
||||
except Exception:
|
||||
pass
|
||||
raise HTTPException(status_code=503, detail="unavailable")
|
||||
|
||||
return att
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/attachments/{attachment_id}",
|
||||
summary="Метаданные вложения, доступ участникам чата",
|
||||
response_model=Attachment,
|
||||
)
|
||||
def get_attachment(
|
||||
attachment_id: UUID,
|
||||
user: User = Depends(current_user),
|
||||
) -> Attachment:
|
||||
pair = storage.get_attachment_with_key(attachment_id)
|
||||
if pair is None:
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
att, _key = pair
|
||||
_require_member(att.chat_id, user.id)
|
||||
return att
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/attachments/{attachment_id}/content",
|
||||
summary="Скачать байты через авторизованный API",
|
||||
)
|
||||
def download_attachment(
|
||||
attachment_id: UUID,
|
||||
user: User = Depends(current_user),
|
||||
variant: str = Query("original"),
|
||||
):
|
||||
if variant != "original":
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
pair = storage.get_attachment_with_key(attachment_id)
|
||||
if pair is None:
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
att, object_key = pair
|
||||
_require_member(att.chat_id, user.id)
|
||||
if att.status != "ready":
|
||||
raise HTTPException(status_code=409, detail="conflict")
|
||||
|
||||
try:
|
||||
data, ctype = s3.get_object(object_key)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
# Объект отсутствует при готовых метаданных: 404.
|
||||
if exc.__class__.__name__ == "NoSuchKey":
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
raise HTTPException(status_code=503, detail="unavailable") from exc
|
||||
|
||||
return Response(
|
||||
content=data,
|
||||
media_type=ctype,
|
||||
headers={"Content-Length": str(len(data))},
|
||||
)
|
||||
@@ -1,6 +1,7 @@
|
||||
from fastapi import APIRouter
|
||||
from ..models.schemas import Health
|
||||
from ..storage import db as _db
|
||||
from ..storage import s3 as _s3
|
||||
from ..storage.sessions import _redis_client, _store
|
||||
|
||||
|
||||
@@ -31,8 +32,15 @@ def readiness() -> Health:
|
||||
with _db.connection() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT 1")
|
||||
cur.fetchone()
|
||||
# Redis (в режиме redis)
|
||||
if _store() == "redis":
|
||||
# _redis_client() сам поднимает RuntimeError("redis_unavailable")
|
||||
# при ошибке; main.runtime_error_handler → 503 Error.
|
||||
_redis_client().ping()
|
||||
# S3: критичен для пути загрузки вложений.
|
||||
try:
|
||||
if _s3.head_object("attachments/__health_probe__") is None:
|
||||
pass # 404 — S3 доступен
|
||||
except Exception as exc:
|
||||
raise RuntimeError("s3_unavailable: %s" % type(exc).__name__) from exc
|
||||
return Health(status="ok")
|
||||
+22
-3
@@ -23,7 +23,8 @@ def _require_member(chat_id: UUID, user_id: UUID):
|
||||
|
||||
|
||||
def _encode_cursor(chat_id: UUID, message: Message) -> str:
|
||||
data = {"chat_id": str(chat_id), "id": str(message.id), "created_at": message.created_at.isoformat()}
|
||||
data = {"chat_id": str(chat_id), "id": str(message.id),
|
||||
"created_at": message.created_at.isoformat()}
|
||||
return base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
|
||||
|
||||
|
||||
@@ -44,7 +45,7 @@ def _canonical_body_hash(payload: CreateMessage) -> str:
|
||||
поэтому payload {"text":"x"} и {"text":"x","attachment_ids":[]} дают
|
||||
одинаковый model_dump и одинаковый хэш — как требует контракт.
|
||||
"""
|
||||
data = payload.model_dump()
|
||||
data = payload.model_dump(mode="json")
|
||||
canonical = json.dumps(data, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
|
||||
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||
|
||||
@@ -69,6 +70,23 @@ def create_message(
|
||||
|
||||
_require_member(chat_id, user.id)
|
||||
|
||||
text = payload.text or ""
|
||||
attachment_ids = list(payload.attachment_ids)
|
||||
|
||||
# Контракт: text (непустой) ИЛИ attachment_ids (>=1).
|
||||
if text.strip() == "" and not attachment_ids:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
# Все вложения должны принадлежать этому чату.
|
||||
if attachment_ids:
|
||||
found = storage.list_attachments_by_ids(attachment_ids, chat_id)
|
||||
if len(found) != len(attachment_ids):
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
for aid in attachment_ids:
|
||||
att, _key = found[aid]
|
||||
if att.status == "failed":
|
||||
raise HTTPException(status_code=409, detail="conflict")
|
||||
|
||||
method = "POST"
|
||||
path = "/api/v1/chats/%s/messages" % chat_id
|
||||
body_hash = _canonical_body_hash(payload)
|
||||
@@ -78,7 +96,8 @@ def create_message(
|
||||
state, message, info = storage.add_message_idempotent(
|
||||
chat_id=chat_id,
|
||||
sender_id=user.id,
|
||||
text=payload.text,
|
||||
text=text,
|
||||
attachment_ids=attachment_ids,
|
||||
user_id=user.id,
|
||||
method=method,
|
||||
path=path,
|
||||
|
||||
+14
-24
@@ -12,7 +12,7 @@ from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
import psycopg
|
||||
import uvicorn
|
||||
from .api import auth, chats, health, messages, users
|
||||
from .api import attachments, auth, chats, health, messages, users
|
||||
from .storage.db import init_pool, close_pool
|
||||
|
||||
|
||||
@@ -31,8 +31,7 @@ INSTANCE_ID = os.environ.get("INSTANCE_ID") or uuid.uuid4().hex[:12]
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
init_pool() # пул соединений PostgreSQL с таймаутами (уровень 4)
|
||||
# Схему готовит отдельный сервис migrate (service_completed_successfully)
|
||||
init_pool() # пул соединений PostgreSQL с таймаутами
|
||||
logger.info(
|
||||
"event=startup app_env=%s session_store=%s instance_id=%s",
|
||||
os.environ.get("APP_ENV", "lab"),
|
||||
@@ -45,8 +44,8 @@ async def lifespan(app: FastAPI):
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUCI Messenger — lab3",
|
||||
version="1.3.0",
|
||||
title="MTUCI Messenger — lab4",
|
||||
version="1.4.0",
|
||||
lifespan=lifespan,
|
||||
swagger_ui_parameters={"persistAuthorization": True},
|
||||
)
|
||||
@@ -76,12 +75,8 @@ async def observability_middleware(request: Request, call_next):
|
||||
path = request.url.path
|
||||
logger.info(
|
||||
"event=http method=%s path=%s status=%s duration_ms=%s request_id=%s instance_id=%s",
|
||||
request.method,
|
||||
path,
|
||||
response.status_code,
|
||||
duration_ms,
|
||||
request_id,
|
||||
INSTANCE_ID,
|
||||
request.method, path, response.status_code,
|
||||
duration_ms, request_id, INSTANCE_ID,
|
||||
)
|
||||
return response
|
||||
|
||||
@@ -143,34 +138,28 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
|
||||
async def db_unavailable_handler(request: Request, exc: psycopg.OperationalError):
|
||||
"""PostgreSQL недоступен → 503 unavailable, без внутренних деталей."""
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
logger.error(
|
||||
"event=db_unavailable type=%s request_id=%s",
|
||||
type(exc).__name__,
|
||||
request_id,
|
||||
)
|
||||
logger.error("event=db_unavailable type=%s request_id=%s",
|
||||
type(exc).__name__, request_id)
|
||||
return _error_response(503, "Зависимость недоступна", request_id, request.url.path)
|
||||
|
||||
|
||||
@app.exception_handler(RuntimeError)
|
||||
async def runtime_error_handler(request: Request, exc: RuntimeError):
|
||||
"""Redis недоступен или конфигурация битая."""
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
text = str(exc)
|
||||
if "redis_unavailable" in text:
|
||||
logger.error("event=redis_unavailable request_id=%s", request_id)
|
||||
return _error_response(503, "Зависимость недоступна", request_id, request.url.path)
|
||||
logger.error(
|
||||
"event=runtime_error type=%s request_id=%s",
|
||||
type(exc).__name__,
|
||||
request_id,
|
||||
)
|
||||
logger.error("event=runtime_error type=%s request_id=%s",
|
||||
type(exc).__name__, request_id)
|
||||
return _error_response(500, "Внутренняя ошибка", request_id, request.url.path)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_exception_handler(request: Request, exc: Exception):
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
logger.error("event=unhandled_exception type=%s request_id=%s", type(exc).__name__, request_id)
|
||||
logger.error("event=unhandled_exception type=%s request_id=%s",
|
||||
type(exc).__name__, request_id)
|
||||
return _error_response(500, "Внутренняя ошибка", request_id, request.url.path)
|
||||
|
||||
|
||||
@@ -179,6 +168,7 @@ app.include_router(auth.router)
|
||||
app.include_router(users.router)
|
||||
app.include_router(chats.router)
|
||||
app.include_router(messages.router)
|
||||
app.include_router(attachments.router)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -186,7 +176,7 @@ if __name__ == "__main__":
|
||||
"app.main:app",
|
||||
host="0.0.0.0",
|
||||
port=8080,
|
||||
log_level="info",
|
||||
log_level="info"
|
||||
)
|
||||
server = uvicorn.Server(config)
|
||||
|
||||
|
||||
+39
-15
@@ -78,18 +78,17 @@ class Chat(BaseModel):
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
"""Контракт: отсутствующий attachment_ids семантически равен [].
|
||||
Поэтому поле опциональное с default_factory=list — модель принимает
|
||||
оба варианта, а _canonical_body_hash видит одинаковый dict.
|
||||
"""
|
||||
"""text может быть пустым, если есть хотя бы одно вложение (lab4)."""
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
text: str = Field(min_length=1, max_length=4000)
|
||||
attachment_ids: List[UUID] = Field(default_factory=list)
|
||||
text: str = Field(default="", max_length=4000)
|
||||
attachment_ids: List[UUID] = Field(default_factory=list, max_length=10)
|
||||
|
||||
@field_validator("text")
|
||||
@field_validator("attachment_ids")
|
||||
@classmethod
|
||||
def _text_not_blank(cls, v: str) -> str:
|
||||
return _not_blank(v)
|
||||
def _unique_attachments(cls, v: List[UUID]) -> List[UUID]:
|
||||
if len(set(v)) != len(v):
|
||||
raise ValueError("duplicate attachment_ids")
|
||||
return v
|
||||
|
||||
|
||||
class Message(BaseModel):
|
||||
@@ -99,6 +98,7 @@ class Message(BaseModel):
|
||||
sender_id: UUID
|
||||
text: str
|
||||
created_at: datetime
|
||||
attachment_ids: List[UUID] = Field(default_factory=list)
|
||||
|
||||
@field_serializer("created_at")
|
||||
def _ser_created_at(self, dt: datetime) -> str:
|
||||
@@ -129,11 +129,35 @@ class Session(BaseModel):
|
||||
return _to_z(dt)
|
||||
|
||||
|
||||
class ErrorBody(BaseModel):
|
||||
code: str
|
||||
message: str
|
||||
request_id: str
|
||||
class Variant(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
name: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
width: int
|
||||
height: int
|
||||
sha256: str
|
||||
|
||||
|
||||
class ErrorResponse(BaseModel):
|
||||
error: ErrorBody
|
||||
class Attachment(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
owner_id: UUID
|
||||
filename: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
status: str # "ready"
|
||||
variants: List[Variant] = Field(default_factory=list)
|
||||
error_code: Optional[str] = None
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
@field_serializer("created_at")
|
||||
def _ser_created_at(self, dt: datetime) -> str:
|
||||
return _to_z(dt)
|
||||
|
||||
@field_serializer("updated_at")
|
||||
def _ser_updated_at(self, dt: datetime) -> str:
|
||||
return _to_z(dt)
|
||||
@@ -104,6 +104,34 @@ CREATE TABLE IF NOT EXISTS idempotency_keys (
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_idempotency_created
|
||||
ON idempotency_keys (created_at);
|
||||
|
||||
-- lab4: вложения
|
||||
CREATE TABLE IF NOT EXISTS attachments (
|
||||
id UUID PRIMARY KEY,
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
owner_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
filename TEXT NOT NULL,
|
||||
content_type TEXT NOT NULL,
|
||||
size_bytes BIGINT NOT NULL,
|
||||
sha256 TEXT NOT NULL,
|
||||
object_key TEXT NOT NULL UNIQUE,
|
||||
status TEXT NOT NULL, -- ready (lab4), queued/processing/failed (lab5)
|
||||
error_code TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_attachments_chat
|
||||
ON attachments (chat_id);
|
||||
|
||||
-- связь сообщение↔вложение (порядок сохраняем)
|
||||
CREATE TABLE IF NOT EXISTS message_attachments (
|
||||
message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
|
||||
position INT NOT NULL,
|
||||
PRIMARY KEY (message_id, attachment_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_msg_att_message
|
||||
ON message_attachments (message_id, position);
|
||||
"""
|
||||
|
||||
|
||||
|
||||
+130
-28
@@ -6,7 +6,7 @@ from datetime import datetime, timezone
|
||||
from typing import List, Optional
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from ..models.schemas import Chat, Message, User
|
||||
from ..models.schemas import Attachment, Chat, Message, User, Variant
|
||||
from .db import connection
|
||||
from .sessions import (
|
||||
create_session as _sess_create,
|
||||
@@ -62,10 +62,22 @@ def _row_to_chat(row, member_ids: List[UUID]) -> Chat:
|
||||
return Chat(id=row[0], title=row[1], member_ids=member_ids, created_at=row[2])
|
||||
|
||||
|
||||
def _row_to_message(row) -> Message:
|
||||
def _row_to_message(row, attachment_ids: List[UUID]) -> Message:
|
||||
return Message(
|
||||
id=row[0], chat_id=row[1], sender_id=row[2],
|
||||
text=row[3], created_at=row[4],
|
||||
attachment_ids=attachment_ids,
|
||||
)
|
||||
|
||||
|
||||
def _row_to_attachment(row) -> Attachment:
|
||||
# row: id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
# status, error_code, created_at, updated_at
|
||||
return Attachment(
|
||||
id=row[0], chat_id=row[1], owner_id=row[2],
|
||||
filename=row[3], content_type=row[4], size_bytes=row[5],
|
||||
sha256=row[6], status=row[7], variants=[], error_code=row[8],
|
||||
created_at=row[9], updated_at=row[10],
|
||||
)
|
||||
|
||||
|
||||
@@ -209,30 +221,21 @@ class PostgresStorage:
|
||||
return chats
|
||||
|
||||
# ---------- Сообщения ----------
|
||||
def add_message(self, chat_id: UUID, sender_id: UUID, text: str) -> Message:
|
||||
with self._lock, connection() as conn:
|
||||
message = Message(
|
||||
id=uuid4(), chat_id=chat_id, sender_id=sender_id,
|
||||
text=text, created_at=now_utc(),
|
||||
)
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text, created_at)"
|
||||
" VALUES (%s, %s, %s, %s, %s)",
|
||||
(message.id, message.chat_id, message.sender_id,
|
||||
message.text, message.created_at),
|
||||
)
|
||||
conn.commit()
|
||||
return message
|
||||
|
||||
def list_messages(self, chat_id: UUID) -> List[Message]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, sender_id, text, created_at FROM messages"
|
||||
" WHERE chat_id = %s ORDER BY created_at, id",
|
||||
(chat_id,),
|
||||
)
|
||||
return [_row_to_message(r) for r in cur.fetchall()]
|
||||
def _load_message_attachments(
|
||||
self, cur, message_ids: List[UUID]
|
||||
) -> dict[UUID, List[UUID]]:
|
||||
"""Одним запросом достаём attachment_ids для набора сообщений."""
|
||||
if not message_ids:
|
||||
return {}
|
||||
cur.execute(
|
||||
"SELECT message_id, attachment_id, position FROM message_attachments"
|
||||
" WHERE message_id = ANY(%s) ORDER BY message_id, position",
|
||||
(list(message_ids),),
|
||||
)
|
||||
result: dict[UUID, List[UUID]] = {}
|
||||
for mid, aid, _pos in cur.fetchall():
|
||||
result.setdefault(mid, []).append(aid)
|
||||
return result
|
||||
|
||||
def list_messages_page(
|
||||
self,
|
||||
@@ -261,7 +264,10 @@ class PostgresStorage:
|
||||
" ORDER BY created_at, id LIMIT %s",
|
||||
(chat_id, after_ts, after_id, limit),
|
||||
)
|
||||
return [_row_to_message(r) for r in cur.fetchall()]
|
||||
rows = cur.fetchall()
|
||||
ids = [r[0] for r in rows]
|
||||
att_map = self._load_message_attachments(cur, ids)
|
||||
return [_row_to_message(r, att_map.get(r[0], [])) for r in rows]
|
||||
|
||||
# ---------- Идемпотентность (lab3) ----------
|
||||
def add_message_idempotent(
|
||||
@@ -269,6 +275,7 @@ class PostgresStorage:
|
||||
chat_id: UUID,
|
||||
sender_id: UUID,
|
||||
text: str,
|
||||
attachment_ids: List[UUID],
|
||||
user_id: UUID,
|
||||
method: str,
|
||||
path: str,
|
||||
@@ -309,6 +316,7 @@ class PostgresStorage:
|
||||
message = Message(
|
||||
id=uuid4(), chat_id=chat_id, sender_id=sender_id,
|
||||
text=text, created_at=now_utc(),
|
||||
attachment_ids=list(attachment_ids),
|
||||
)
|
||||
cur.execute(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text, created_at)"
|
||||
@@ -316,7 +324,15 @@ class PostgresStorage:
|
||||
(message.id, message.chat_id, message.sender_id,
|
||||
message.text, message.created_at),
|
||||
)
|
||||
# 3) Сразу пишем финальный ответ в ту же строку ключа.
|
||||
if attachment_ids:
|
||||
cur.executemany(
|
||||
"INSERT INTO message_attachments"
|
||||
" (message_id, attachment_id, position)"
|
||||
" VALUES (%s, %s, %s)",
|
||||
[(message.id, aid, idx)
|
||||
for idx, aid in enumerate(attachment_ids)],
|
||||
)
|
||||
# 3) Пишем финальный ответ в ту же строку ключа.
|
||||
body_json = _json.loads(message.model_dump_json())
|
||||
cur.execute(
|
||||
"UPDATE idempotency_keys"
|
||||
@@ -352,5 +368,91 @@ class PostgresStorage:
|
||||
},
|
||||
)
|
||||
|
||||
# ---------- Вложения ----------
|
||||
def create_attachment(
|
||||
self,
|
||||
attachment: Attachment,
|
||||
object_key: str,
|
||||
) -> Attachment:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO attachments"
|
||||
" (id, chat_id, owner_id, filename, content_type, size_bytes,"
|
||||
" sha256, object_key, status, error_code, created_at, updated_at)"
|
||||
" VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||
(
|
||||
attachment.id, attachment.chat_id, attachment.owner_id,
|
||||
attachment.filename, attachment.content_type,
|
||||
attachment.size_bytes, attachment.sha256, object_key,
|
||||
attachment.status, attachment.error_code,
|
||||
attachment.created_at, attachment.updated_at,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
return attachment
|
||||
|
||||
def get_attachment(self, attachment_id: UUID) -> Optional[Attachment]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, owner_id, filename, content_type, size_bytes,"
|
||||
" sha256, status, error_code, created_at, updated_at"
|
||||
" FROM attachments WHERE id = %s",
|
||||
(attachment_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
cur.execute(
|
||||
"SELECT object_key FROM attachments WHERE id = %s", (attachment_id,),
|
||||
)
|
||||
obj_row = cur.fetchone()
|
||||
att = _row_to_attachment(row)
|
||||
att_variants: List[Variant] = [] # lab4: вариантов нет
|
||||
att.variants = att_variants
|
||||
# object_key нужен вызывающему для чтения из S3; отдаём через
|
||||
# отдельный метод get_attachment_with_key.
|
||||
return att
|
||||
|
||||
def get_attachment_with_key(
|
||||
self, attachment_id: UUID
|
||||
) -> Optional[tuple[Attachment, str]]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, owner_id, filename, content_type, size_bytes,"
|
||||
" sha256, status, error_code, created_at, updated_at, object_key"
|
||||
" FROM attachments WHERE id = %s",
|
||||
(attachment_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
att = _row_to_attachment(row[:11])
|
||||
return att, row[11]
|
||||
|
||||
def list_attachments_by_ids(
|
||||
self, ids: List[UUID], chat_id: UUID
|
||||
) -> dict[UUID, tuple[Attachment, str]]:
|
||||
"""Достаём вложения этого чата. Возвращает {id: (Attachment, object_key)}."""
|
||||
if not ids:
|
||||
return {}
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, owner_id, filename, content_type, size_bytes,"
|
||||
" sha256, status, error_code, created_at, updated_at, object_key"
|
||||
" FROM attachments WHERE chat_id = %s AND id = ANY(%s)",
|
||||
(chat_id, list(ids)),
|
||||
)
|
||||
result: dict[UUID, tuple[Attachment, str]] = {}
|
||||
for row in cur.fetchall():
|
||||
att = _row_to_attachment(row[:11])
|
||||
att.variants = []
|
||||
result[row[0]] = (att, row[11])
|
||||
return result
|
||||
|
||||
def delete_attachment(self, attachment_id: UUID) -> None:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute("DELETE FROM attachments WHERE id = %s", (attachment_id,))
|
||||
conn.commit()
|
||||
|
||||
|
||||
storage = PostgresStorage() # единственный экземпляр на процесс
|
||||
@@ -0,0 +1,76 @@
|
||||
"""S3-клиент (MinIO) для lab4.
|
||||
|
||||
Object key генерирует сервер: attachments/<chat_id>/<attachment_id>/original.
|
||||
filename используется только для отображения, не в ключе.
|
||||
"""
|
||||
import os
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
|
||||
import boto3
|
||||
from botocore.client import Config
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
|
||||
def _endpoint() -> str:
|
||||
return os.environ["S3_ENDPOINT"]
|
||||
|
||||
|
||||
def _bucket() -> str:
|
||||
return os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
|
||||
|
||||
def client():
|
||||
"""Клиент с прикладными credentials (не admin)."""
|
||||
return boto3.client(
|
||||
"s3",
|
||||
endpoint_url=_endpoint(),
|
||||
region_name=os.environ.get("S3_REGION", "us-east-1"),
|
||||
aws_access_key_id=os.environ["S3_APP_KEY_ID"],
|
||||
aws_secret_access_key=os.environ["S3_APP_SECRET_KEY"],
|
||||
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
|
||||
)
|
||||
|
||||
|
||||
def original_key(chat_id: UUID, attachment_id: UUID) -> str:
|
||||
"""Единственный ключ оригинала. Не зависит от filename."""
|
||||
return "attachments/%s/%s/original" % (chat_id, attachment_id)
|
||||
|
||||
|
||||
def put_bytes(key: str, data: bytes, content_type: str) -> None:
|
||||
client().put_object(
|
||||
Bucket=_bucket(),
|
||||
Key=key,
|
||||
Body=data,
|
||||
ContentType=content_type,
|
||||
ContentLength=len(data),
|
||||
)
|
||||
|
||||
|
||||
def get_object(key: str):
|
||||
"""Возвращает (bytes, content_type). Бросает ClientError при отсутствии."""
|
||||
resp = client().get_object(Bucket=_bucket(), Key=key)
|
||||
body = resp["Body"].read()
|
||||
ctype = resp.get("ContentType") or "application/octet-stream"
|
||||
return body, ctype
|
||||
|
||||
|
||||
def delete_object(key: str) -> None:
|
||||
client().delete_object(Bucket=_bucket(), Key=key)
|
||||
|
||||
|
||||
def head_object(key: str) -> Optional[dict]:
|
||||
try:
|
||||
return client().head_object(Bucket=_bucket(), Key=key)
|
||||
except ClientError as exc:
|
||||
if exc.response.get("Error", {}).get("Code") in ("404", "NoSuchKey", "NotFound"):
|
||||
return None
|
||||
raise
|
||||
|
||||
|
||||
def list_objects(prefix: str = "attachments/"):
|
||||
"""Итератор по объектам bucket. Используется cleanup-сервисом."""
|
||||
paginator = client().get_paginator("list_objects_v2")
|
||||
for page in paginator.paginate(Bucket=_bucket(), Prefix=prefix):
|
||||
for obj in page.get("Contents", []):
|
||||
yield obj
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Фоновая сверка S3 и PostgreSQL (уровень 4).
|
||||
|
||||
- Orphan: объект в S3 есть, а метаданных в attachments нет.
|
||||
Удаляем только если объект старше ORPHAN_GRACE_SECONDS.
|
||||
- Missing: метаданные есть, объекта в S3 нет.
|
||||
Пишем warning в лог (не удаляем метаданные — учебная политика).
|
||||
- Object key кодирует chat_id и attachment_id, поэтому сверка по метаданным
|
||||
attachments.
|
||||
- Каждый цикл независим; падение логируется и не роняет процесс.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from uuid import UUID
|
||||
|
||||
from . import s3
|
||||
from .db import connection, init_pool, close_pool
|
||||
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
stream=sys.stdout,
|
||||
)
|
||||
log = logging.getLogger("s3_cleanup")
|
||||
|
||||
|
||||
def _interval() -> int:
|
||||
try:
|
||||
return max(30, int(os.environ.get("CLEANUP_INTERVAL_SECONDS", "300")))
|
||||
except ValueError:
|
||||
return 300
|
||||
|
||||
|
||||
def _grace() -> int:
|
||||
try:
|
||||
return max(0, int(os.environ.get("ORPHAN_GRACE_SECONDS", "3600")))
|
||||
except ValueError:
|
||||
return 3600
|
||||
|
||||
|
||||
def _known_keys() -> set[str]:
|
||||
"""Все ожидаемые object key из таблицы attachments."""
|
||||
keys: set[str] = set()
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT id, chat_id FROM attachments")
|
||||
for aid, cid in cur.fetchall():
|
||||
keys.add(s3.original_key(cid, aid))
|
||||
return keys
|
||||
|
||||
|
||||
def _run_once() -> dict:
|
||||
now = datetime.now(timezone.utc)
|
||||
grace_cutoff = now - timedelta(seconds=_grace())
|
||||
|
||||
known = _known_keys()
|
||||
orphan_deleted = 0
|
||||
missing = 0
|
||||
scanned = 0
|
||||
|
||||
for obj in s3.list_objects("attachments/"):
|
||||
scanned += 1
|
||||
key = obj["Key"]
|
||||
if key in known:
|
||||
continue
|
||||
# Orphan: в S3 есть, в БД нет. Удаляем только старше grace period.
|
||||
lm = obj.get("LastModified")
|
||||
if lm is None:
|
||||
continue
|
||||
if lm.tzinfo is None:
|
||||
lm = lm.replace(tzinfo=timezone.utc)
|
||||
if lm > grace_cutoff:
|
||||
# Свежий объект — возможно in-flight upload; не трогаем.
|
||||
continue
|
||||
try:
|
||||
s3.delete_object(key)
|
||||
orphan_deleted += 1
|
||||
log.info("event=orphan_deleted key=%s", key)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.error("event=orphan_delete_failed key=%s type=%s", key, type(exc).__name__)
|
||||
|
||||
# Проверяем обратную сторону: метаданные без объекта.
|
||||
for key in known:
|
||||
if s3.head_object(key) is None:
|
||||
missing += 1
|
||||
log.warning("event=missing_object key=%s", key)
|
||||
|
||||
return {
|
||||
"scanned": scanned,
|
||||
"orphan_deleted": orphan_deleted,
|
||||
"missing": missing,
|
||||
"known": len(known),
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
init_pool()
|
||||
interval = _interval()
|
||||
log.info("event=cleanup_start interval_s=%s grace_s=%s", interval, _grace())
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
stats = _run_once()
|
||||
log.info(
|
||||
"event=cleanup_pass scanned=%s known=%s orphan_deleted=%s missing=%s",
|
||||
stats["scanned"], stats["known"],
|
||||
stats["orphan_deleted"], stats["missing"],
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.error("event=cleanup_failed type=%s", type(exc).__name__)
|
||||
time.sleep(interval)
|
||||
finally:
|
||||
close_pool()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user