Lab 4 for Grade 4

This commit is contained in:
paflove
2026-11-14 15:09:57 +03:00
parent ec540a1a72
commit 46251b361f
20 changed files with 1813 additions and 15 deletions
+828
View File
@@ -0,0 +1,828 @@
import os
import re
import io
import uuid
import base64
import secrets
import hashlib
import json
import asyncio
from datetime import datetime, timezone, timedelta
from typing import List, Optional
import asyncpg
import redis.asyncio as aioredis
import boto3
from botocore.client import Config
from PIL import Image
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
from fastapi import FastAPI, Request, Header, HTTPException, Depends, Query
from fastapi.responses import JSONResponse, Response
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
from pydantic import BaseModel, Field, constr, field_validator, ConfigDict
# --- КОНФИГУРАЦИЯ ---
def get_secret_or_env(file_var: str, default: str) -> str:
path = os.getenv(file_var)
if path and os.path.exists(path):
with open(path, "r", encoding="utf-8") as f:
return f.read().strip()
return default
DATABASE_URL = get_secret_or_env("DATABASE_URL_FILE", "postgresql://appuser:apppassword@postgres:5432/messenger_db")
CACHE_URL = get_secret_or_env("CACHE_URL_FILE", "redis://redis:6379/0")
S3_ENDPOINT = os.getenv("S3_ENDPOINT", "http://s3:9000")
S3_REGION = os.getenv("S3_REGION", "us-east-1")
S3_BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
S3_ACCESS_KEY = get_secret_or_env("S3_ACCESS_KEY_ID_FILE", "miniouser")
S3_SECRET_KEY = get_secret_or_env("S3_SECRET_ACCESS_KEY_FILE", "miniopassword123")
MAX_UPLOAD_BYTES = int(os.getenv("MAX_UPLOAD_BYTES", "10485760"))
MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000"))
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
IDEMPOTENCY_TTL_SECONDS = int(os.getenv("IDEMPOTENCY_TTL_SECONDS", "86400"))
INSTANCE_ID = str(uuid.uuid4())
IDEMPOTENCY_REGEX = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
ph = PasswordHasher()
db_pool: Optional[asyncpg.Pool] = None
redis_client: Optional[aioredis.Redis] = None
s3_client = None
def to_rfc3339(dt: datetime) -> str:
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
# --- PYDANTIC МОДЕЛИ ---
class CreateUserRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
username: constr(pattern=r"^[a-z0-9_]{3,32}$")
display_name: str = Field(min_length=1, max_length=100)
password: str = Field(min_length=12, max_length=128)
@field_validator("display_name")
@classmethod
def validate_name(cls, v: str) -> str:
if not v.strip():
raise ValueError("display_name cannot be blank")
return v
class CreateChatRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str = Field(min_length=1, max_length=100)
member_ids: List[str] = Field(min_length=1, max_length=100)
@field_validator("title")
@classmethod
def validate_title(cls, v: str) -> str:
if not v.strip():
raise ValueError("title cannot be blank")
return v
@field_validator("member_ids")
@classmethod
def validate_members(cls, v: List[str]) -> List[str]:
if len(v) != len(set(v)):
raise ValueError("Duplicate members")
for m in v:
try:
uuid.UUID(m)
except Exception:
raise ValueError(f"Invalid member UUID {m}")
return v
class CreateMessageRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
text: Optional[str] = Field(default="", max_length=4000)
attachment_ids: List[str] = Field(default_factory=list, max_length=10)
@field_validator("attachment_ids")
@classmethod
def validate_attachments(cls, v: List[str]) -> List[str]:
if len(v) != len(set(v)):
raise ValueError("Duplicate attachment IDs")
for a in v:
try:
uuid.UUID(a)
except Exception:
raise ValueError(f"Invalid attachment UUID {a}")
return v
app = FastAPI(title="MTUSI Messenger Lab 4")
# --- ЖИЗНЕННЫЙ ЦИКЛ ---
@app.on_event("startup")
async def on_startup():
global db_pool, redis_client, s3_client
db_pool = await asyncpg.create_pool(DATABASE_URL, min_size=2, max_size=20, command_timeout=10.0)
redis_client = aioredis.from_url(CACHE_URL, decode_responses=True)
s3_client = boto3.client(
"s3",
endpoint_url=S3_ENDPOINT,
region_name=S3_REGION,
aws_access_key_id=S3_ACCESS_KEY,
aws_secret_access_key=S3_SECRET_KEY,
config=Config(signature_version="s3v4")
)
@app.on_event("shutdown")
async def on_shutdown():
if db_pool:
await db_pool.close()
if redis_client:
await redis_client.close()
# --- MIDDLEWARE ---
@app.middleware("http")
async def add_headers(request: Request, call_next):
req_id = request.headers.get("X-Request-Id") or str(uuid.uuid4())
request.state.request_id = req_id
try:
response = await call_next(request)
except Exception:
return generate_error(req_id, "internal_error", "Internal Server Error", 500)
response.headers["X-Request-Id"] = req_id
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
def generate_error(req_id: str, code: str, message: str, status_code: int, headers: dict = None):
h = headers or {}
h["X-Request-Id"] = req_id
h["X-Instance-Id"] = INSTANCE_ID
return JSONResponse(
status_code=status_code,
content={"error": {"code": code, "message": message, "request_id": req_id}},
headers=h
)
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
code_map = {
400: "invalid_request",
401: "unauthorized",
403: "forbidden",
404: "not_found",
409: "conflict",
413: "payload_too_large",
415: "unsupported_media_type",
503: "unavailable"
}
code = code_map.get(exc.status_code, "internal_error")
req_id = getattr(request.state, "request_id", str(uuid.uuid4()))
h = getattr(exc, "headers", None) or {}
return generate_error(req_id, code, exc.detail or "Error", exc.status_code, h)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
req_id = getattr(request.state, "request_id", str(uuid.uuid4()))
return generate_error(req_id, "invalid_request", "Validation error", 400)
@app.exception_handler(Exception)
async def generic_exception_handler(request: Request, exc: Exception):
req_id = getattr(request.state, "request_id", str(uuid.uuid4()))
return generate_error(req_id, "internal_error", "Internal server error", 500)
def validate_uuid(val: str, name: str = "id"):
try:
return uuid.UUID(val)
except Exception:
raise HTTPException(status_code=400, detail=f"Invalid {name} UUID format")
# --- AUTH (BEARER) ---
async def get_current_user(authorization: Optional[str] = Header(None)) -> dict:
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Missing Bearer token", headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
token = authorization.split(" ", 1)[1].strip()
if not token or not redis_client or not db_pool:
raise HTTPException(status_code=401, detail="Unauthorized", headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
try:
user_id = await redis_client.get(f"session:{token}")
except Exception:
raise HTTPException(status_code=503, detail="Session store unavailable")
if not user_id:
raise HTTPException(status_code=401, detail="Session expired or invalid", headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
async with db_pool.acquire() as conn:
row = await conn.fetchrow("SELECT id, username, display_name, created_at FROM users WHERE id = $1", uuid.UUID(user_id))
if not row:
raise HTTPException(status_code=401, detail="User not found", headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": to_rfc3339(row["created_at"])
}
# --- HEALTH ---
@app.get("/health/live")
async def health_live():
return {"status": "ok"}
@app.get("/health/ready")
async def health_ready():
try:
if not db_pool or not redis_client or not s3_client:
raise Exception("Components not ready")
async with db_pool.acquire() as conn:
await conn.fetchval("SELECT 1")
await redis_client.ping()
await asyncio.to_thread(s3_client.head_bucket, Bucket=S3_BUCKET)
return {"status": "ok"}
except Exception:
raise HTTPException(status_code=503, detail="Database, cache or S3 not ready")
# --- AUTH SESSIONS ---
async def create_session_handler(authorization: Optional[str] = Header(None)):
if not authorization or not authorization.startswith("Basic "):
raise HTTPException(status_code=401, detail="Basic auth required", headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
try:
raw_b64 = authorization.split(" ", 1)[1]
decoded = base64.b64decode(raw_b64).decode("utf-8")
username, password = decoded.split(":", 1)
except Exception:
raise HTTPException(status_code=401, detail="Invalid Basic header", headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
async with db_pool.acquire() as conn:
row = await conn.fetchrow("SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1", username)
if not row:
raise HTTPException(status_code=401, detail="Invalid credentials", headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
try:
ph.verify(row["password_hash"], password)
except VerifyMismatchError:
raise HTTPException(status_code=401, detail="Invalid credentials", headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
token = secrets.token_urlsafe(32)
expires_at = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL_SECONDS)
await redis_client.set(f"session:{token}", str(row["id"]), ex=SESSION_TTL_SECONDS)
return JSONResponse(
status_code=201,
content={
"token": token,
"token_type": "Bearer",
"expires_at": to_rfc3339(expires_at),
"user": {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": to_rfc3339(row["created_at"])
}
}
)
@app.post("/auth/sessions", status_code=201)
@app.post("/api/v1/auth/sessions", status_code=201)
async def create_session(authorization: Optional[str] = Header(None)):
return await create_session_handler(authorization)
async def delete_session_handler(authorization: Optional[str] = Header(None)):
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Bearer token required", headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
token = authorization.split(" ", 1)[1].strip()
exists = await redis_client.delete(f"session:{token}")
if not exists:
raise HTTPException(status_code=401, detail="Token already invalid", headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
return Response(status_code=204)
@app.delete("/auth/sessions/current", status_code=204)
@app.delete("/api/v1/auth/sessions/current", status_code=204)
async def delete_session(authorization: Optional[str] = Header(None)):
return await delete_session_handler(authorization)
# --- USERS ---
async def create_user_handler(req: CreateUserRequest):
user_id = uuid.uuid4()
now = datetime.now(timezone.utc)
hashed_pw = ph.hash(req.password)
try:
async with db_pool.acquire() as conn:
await conn.execute(
"INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES ($1, $2, $3, $4, $5)",
user_id, req.username, req.display_name, hashed_pw, now
)
except asyncpg.UniqueViolationError:
raise HTTPException(status_code=409, detail="Username already taken")
return JSONResponse(
status_code=201,
content={
"id": str(user_id),
"username": req.username,
"display_name": req.display_name,
"created_at": to_rfc3339(now)
}
)
@app.post("/users", status_code=201)
@app.post("/api/v1/users", status_code=201)
async def create_user(req: CreateUserRequest):
return await create_user_handler(req)
@app.get("/users/me")
@app.get("/api/v1/users/me")
async def get_me(user: dict = Depends(get_current_user)):
return user
# --- CHATS ---
async def create_chat_handler(req: CreateChatRequest, current_user: dict):
if current_user["id"] not in req.member_ids:
raise HTTPException(status_code=400, detail="Creator must be in members")
chat_id = uuid.uuid4()
now = datetime.now(timezone.utc)
member_uuids = [uuid.UUID(m) for m in req.member_ids]
async with db_pool.acquire() as conn:
async with conn.transaction():
count = await conn.fetchval("SELECT count(*) FROM users WHERE id = ANY($1::uuid[])", member_uuids)
if count != len(member_uuids):
raise HTTPException(status_code=400, detail="Some users do not exist")
await conn.execute("INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)", chat_id, req.title, now)
await conn.executemany("INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)", [(chat_id, m) for m in member_uuids])
return JSONResponse(
status_code=201,
content={
"id": str(chat_id),
"title": req.title,
"member_ids": req.member_ids,
"created_at": to_rfc3339(now)
}
)
@app.post("/chats", status_code=201)
@app.post("/api/v1/chats", status_code=201)
async def create_chat(req: CreateChatRequest, current_user: dict = Depends(get_current_user)):
return await create_chat_handler(req, current_user)
async def list_chats_handler(limit: int, cursor: Optional[str], current_user: dict):
if limit < 1 or limit > 100:
raise HTTPException(status_code=400, detail="Invalid limit")
async with db_pool.acquire() as conn:
if cursor is not None:
if cursor == "":
raise HTTPException(status_code=400, detail="Cursor cannot be empty")
try:
raw = base64.b64decode(cursor).decode("utf-8")
parts = raw.split("|")
c_time_str, c_id_str = parts[-2], parts[-1]
cursor_time = datetime.fromisoformat(c_time_str.replace("Z", "+00:00"))
cursor_id = uuid.UUID(c_id_str)
except Exception:
raise HTTPException(status_code=400, detail="Invalid cursor format")
query = """
SELECT c.id, c.title, c.created_at, array_agg(cm_all.user_id::text) as member_ids
FROM chats c
JOIN chat_members cm ON cm.chat_id = c.id
JOIN chat_members cm_all ON cm_all.chat_id = c.id
WHERE cm.user_id = $1 AND (c.created_at, c.id) > ($2, $3)
GROUP BY c.id, c.title, c.created_at
ORDER BY c.created_at ASC, c.id ASC
LIMIT $4
"""
rows = await conn.fetch(query, uuid.UUID(current_user["id"]), cursor_time, cursor_id, limit + 1)
else:
query = """
SELECT c.id, c.title, c.created_at, array_agg(cm_all.user_id::text) as member_ids
FROM chats c
JOIN chat_members cm ON cm.chat_id = c.id
JOIN chat_members cm_all ON cm_all.chat_id = c.id
WHERE cm.user_id = $1
GROUP BY c.id, c.title, c.created_at
ORDER BY c.created_at ASC, c.id ASC
LIMIT $2
"""
rows = await conn.fetch(query, uuid.UUID(current_user["id"]), limit + 1)
items = []
for r in rows[:limit]:
items.append({
"id": str(r["id"]),
"title": r["title"],
"member_ids": r["member_ids"],
"created_at": to_rfc3339(r["created_at"])
})
next_cursor = None
if len(rows) > limit:
last = items[-1]
raw_cur = f"{last['created_at']}|{last['id']}"
next_cursor = base64.b64encode(raw_cur.encode("utf-8")).decode("utf-8")
return {"items": items, "next_cursor": next_cursor}
@app.get("/chats")
@app.get("/api/v1/chats")
async def list_chats(limit: int = 50, cursor: Optional[str] = None, current_user: dict = Depends(get_current_user)):
return await list_chats_handler(limit, cursor, current_user)
async def get_chat_handler(chat_id: str, current_user: dict):
cid = validate_uuid(chat_id, "chat_id")
async with db_pool.acquire() as conn:
row = await conn.fetchrow(
"""
SELECT c.id, c.title, c.created_at, array_agg(cm.user_id::text) as member_ids
FROM chats c
JOIN chat_members cm ON cm.chat_id = c.id
WHERE c.id = $1
GROUP BY c.id, c.title, c.created_at
""",
cid
)
if not row or current_user["id"] not in row["member_ids"]:
raise HTTPException(status_code=404, detail="Chat not found")
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": row["member_ids"],
"created_at": to_rfc3339(row["created_at"])
}
@app.get("/chats/{chat_id}")
@app.get("/api/v1/chats/{chat_id}")
async def get_chat(chat_id: str, current_user: dict = Depends(get_current_user)):
return await get_chat_handler(chat_id, current_user)
# --- S3 ВЛОЖЕНИЯ (ATTACHMENTS) ---
def validate_filename(filename: str):
if not filename or len(filename) < 1 or len(filename) > 255:
raise HTTPException(status_code=400, detail="Invalid filename length")
if "/" in filename or "\\" in filename or "\0" in filename:
raise HTTPException(status_code=400, detail="Filename contains dangerous path separators")
for ch in filename:
code = ord(ch)
if code < 32 or code == 127:
raise HTTPException(status_code=400, detail="Filename contains control characters")
async def upload_attachment_handler(chat_id: str, request: Request, filename: str, current_user: dict):
cid = validate_uuid(chat_id, "chat_id")
validate_filename(filename)
async with db_pool.acquire() as conn:
is_member = await conn.fetchval(
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
cid, uuid.UUID(current_user["id"])
)
if not is_member:
raise HTTPException(status_code=404, detail="Chat not found")
content_type = request.headers.get("Content-Type", "")
if content_type not in ["image/png", "image/jpeg"]:
raise HTTPException(status_code=415, detail="Unsupported media type (PNG or JPEG required)")
# Предварительная проверка Content-Length до чтения тела
content_length = request.headers.get("Content-Length")
if content_length:
try:
if int(content_length) > MAX_UPLOAD_BYTES:
raise HTTPException(status_code=413, detail="Payload too large (max 10 MiB)")
except ValueError:
raise HTTPException(status_code=400, detail="Invalid Content-Length")
# Потоковое чтение по кускам с мгновенной остановкой при превышении лимита
chunks = []
size_bytes = 0
async for chunk in request.stream():
size_bytes += len(chunk)
if size_bytes > MAX_UPLOAD_BYTES:
raise HTTPException(status_code=413, detail="Payload too large (max 10 MiB)")
chunks.append(chunk)
body = b"".join(chunks)
if size_bytes == 0:
raise HTTPException(status_code=415, detail="Empty attachment body")
# Проверка магических байтов
if content_type == "image/png" and not body.startswith(b"\x89PNG\r\n\x1a\n"):
raise HTTPException(status_code=415, detail="MIME signature mismatch for PNG")
if content_type == "image/jpeg" and not body.startswith(b"\xff\xd8\xff"):
raise HTTPException(status_code=415, detail="MIME signature mismatch for JPEG")
# Проверка разрешения и целостности без полной распаковки пикселей
try:
Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS
with Image.open(io.BytesIO(body)) as img:
if (content_type == "image/png" and img.format != "PNG") or (content_type == "image/jpeg" and img.format != "JPEG"):
raise HTTPException(status_code=415, detail="Image format does not match Content-Type")
w, h = img.size
if w * h > MAX_IMAGE_PIXELS:
raise HTTPException(status_code=413, detail="Image exceeds max pixel limit (40M)")
img.verify()
except Image.DecompressionBombError:
raise HTTPException(status_code=413, detail="Image exceeds max pixel limit (40M)")
except HTTPException:
raise
except Exception:
raise HTTPException(status_code=415, detail="Corrupt image content")
sha256 = hashlib.sha256(body).hexdigest().lower()
att_id = uuid.uuid4()
now = datetime.now(timezone.utc)
object_key = f"attachments/{cid}/{att_id}"
try:
await asyncio.to_thread(
s3_client.put_object,
Bucket=S3_BUCKET,
Key=object_key,
Body=body,
ContentType=content_type
)
except Exception:
raise HTTPException(status_code=503, detail="S3 storage unavailable")
async with db_pool.acquire() as conn:
await conn.execute(
"""
INSERT INTO attachments (id, chat_id, user_id, filename, size_bytes, sha256, content_type, status, object_key, created_at, updated_at, error_code)
VALUES ($1, $2, $3, $4, $5, $6, $7, 'ready', $8, $9, $9, NULL)
""",
att_id, cid, uuid.UUID(current_user["id"]), filename, size_bytes, sha256, content_type, object_key, now
)
return JSONResponse(
status_code=201,
content={
"id": str(att_id),
"chat_id": str(cid),
"owner_id": current_user["id"],
"status": "ready",
"filename": filename,
"size_bytes": size_bytes,
"sha256": sha256,
"content_type": content_type,
"created_at": to_rfc3339(now),
"updated_at": to_rfc3339(now),
"variants": [],
"error_code": None
}
)
@app.post("/chats/{chat_id}/attachments", status_code=201)
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=201)
async def upload_attachment(
chat_id: str,
request: Request,
filename: str = Query(...),
current_user: dict = Depends(get_current_user)
):
return await upload_attachment_handler(chat_id, request, filename, current_user)
async def get_attachment_meta_handler(attachment_id: str, current_user: dict):
aid = validate_uuid(attachment_id, "attachment_id")
async with db_pool.acquire() as conn:
row = await conn.fetchrow(
"""
SELECT a.id, a.chat_id, a.user_id as owner_id, a.filename, a.size_bytes, a.sha256, a.content_type, a.status, a.created_at, a.updated_at, a.error_code
FROM attachments a
JOIN chat_members cm ON cm.chat_id = a.chat_id
WHERE a.id = $1 AND cm.user_id = $2
""",
aid, uuid.UUID(current_user["id"])
)
if not row:
raise HTTPException(status_code=404, detail="Attachment not found")
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"owner_id": str(row["owner_id"]),
"status": row["status"],
"filename": row["filename"],
"size_bytes": row["size_bytes"],
"sha256": row["sha256"],
"content_type": row["content_type"],
"created_at": to_rfc3339(row["created_at"]),
"updated_at": to_rfc3339(row["updated_at"]),
"variants": [],
"error_code": row["error_code"]
}
@app.get("/attachments/{attachment_id}")
@app.get("/api/v1/attachments/{attachment_id}")
async def get_attachment_meta(attachment_id: str, current_user: dict = Depends(get_current_user)):
return await get_attachment_meta_handler(attachment_id, current_user)
async def download_attachment_content_handler(attachment_id: str, current_user: dict):
aid = validate_uuid(attachment_id, "attachment_id")
async with db_pool.acquire() as conn:
row = await conn.fetchrow(
"""
SELECT a.id, a.chat_id, a.object_key, a.content_type, a.filename
FROM attachments a
JOIN chat_members cm ON cm.chat_id = a.chat_id
WHERE a.id = $1 AND cm.user_id = $2
""",
aid, uuid.UUID(current_user["id"])
)
if not row:
raise HTTPException(status_code=404, detail="Attachment not found")
try:
s3_obj = await asyncio.to_thread(
s3_client.get_object,
Bucket=S3_BUCKET,
Key=row["object_key"]
)
data = await asyncio.to_thread(s3_obj["Body"].read)
except Exception:
raise HTTPException(status_code=503, detail="S3 storage unavailable")
return Response(
content=data,
media_type=row["content_type"],
headers={"Content-Disposition": f'inline; filename="{row["filename"]}"'}
)
@app.get("/attachments/{attachment_id}/content")
@app.get("/api/v1/attachments/{attachment_id}/content")
async def download_attachment_content(attachment_id: str, current_user: dict = Depends(get_current_user)):
return await download_attachment_content_handler(attachment_id, current_user)
# --- MESSAGES ---
async def create_message_handler(chat_id: str, req: CreateMessageRequest, current_user: dict, idempotency_key: Optional[str]):
if not idempotency_key or not IDEMPOTENCY_REGEX.match(idempotency_key):
raise HTTPException(status_code=400, detail="Missing or invalid Idempotency-Key")
cid = validate_uuid(chat_id, "chat_id")
uid = uuid.UUID(current_user["id"])
if not req.attachment_ids and not (req.text and req.text.strip()):
raise HTTPException(status_code=400, detail="Message text cannot be blank without attachments")
att_uuids = [uuid.UUID(a) for a in req.attachment_ids]
body_dict = {"text": req.text, "attachment_ids": sorted(req.attachment_ids)}
req_hash = hashlib.sha256(json.dumps(body_dict, sort_keys=True).encode("utf-8")).hexdigest()
async with db_pool.acquire() as conn:
is_member = await conn.fetchval(
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
cid, uid
)
if not is_member:
raise HTTPException(status_code=404, detail="Chat not found")
if att_uuids:
att_rows = await conn.fetch(
"SELECT id, chat_id, status FROM attachments WHERE id = ANY($1::uuid[])",
att_uuids
)
if len(att_rows) != len(att_uuids):
raise HTTPException(status_code=404, detail="Some attachments not found")
for ar in att_rows:
if ar["chat_id"] != cid:
raise HTTPException(status_code=404, detail="Attachment belongs to another chat")
if ar["status"] != "ready":
raise HTTPException(status_code=409, detail="Attachment not ready")
async with conn.transaction():
existing = await conn.fetchrow(
"""
SELECT request_hash, response_code, response_body
FROM idempotency_keys
WHERE user_id = $1 AND chat_id = $2 AND key = $3
FOR UPDATE
""",
uid, cid, idempotency_key
)
if existing:
if existing["request_hash"] != req_hash:
raise HTTPException(status_code=409, detail="Idempotency key collision with different body")
saved_body = json.loads(existing["response_body"]) if isinstance(existing["response_body"], str) else existing["response_body"]
return JSONResponse(status_code=existing["response_code"], content=saved_body)
msg_id = uuid.uuid4()
now = datetime.now(timezone.utc)
res_content = {
"id": str(msg_id),
"chat_id": str(cid),
"sender_id": current_user["id"],
"text": req.text,
"attachment_ids": req.attachment_ids,
"created_at": to_rfc3339(now)
}
await conn.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, text, attachment_ids, created_at)
VALUES ($1, $2, $3, $4, $5, $6)
""",
msg_id, cid, uid, req.text, att_uuids, now
)
await conn.execute(
"""
INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, response_code, response_body, created_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)
""",
uid, cid, idempotency_key, req_hash, 201, json.dumps(res_content), now
)
return JSONResponse(status_code=201, content=res_content)
@app.post("/chats/{chat_id}/messages", status_code=201)
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
async def create_message(
chat_id: str,
req: CreateMessageRequest,
current_user: dict = Depends(get_current_user),
idempotency_key: Optional[str] = Header(None, alias="Idempotency-Key")
):
return await create_message_handler(chat_id, req, current_user, idempotency_key)
async def list_messages_handler(chat_id: str, limit: int, cursor: Optional[str], current_user: dict):
cid = validate_uuid(chat_id, "chat_id")
if limit < 1 or limit > 100:
raise HTTPException(status_code=400, detail="Invalid limit")
async with db_pool.acquire() as conn:
is_member = await conn.fetchval(
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
cid, uuid.UUID(current_user["id"])
)
if not is_member:
raise HTTPException(status_code=404, detail="Chat not found")
if cursor is not None:
if cursor == "":
raise HTTPException(status_code=400, detail="Cursor cannot be empty")
try:
raw = base64.b64decode(cursor).decode("utf-8")
parts = raw.split("|")
if len(parts) == 3:
cur_chat_id, c_time_str, c_id_str = parts
if cur_chat_id != str(cid):
raise HTTPException(status_code=400, detail="Cursor belongs to another chat")
elif len(parts) == 2:
c_time_str, c_id_str = parts
else:
raise ValueError()
cursor_time = datetime.fromisoformat(c_time_str.replace("Z", "+00:00"))
cursor_id = uuid.UUID(c_id_str)
except HTTPException:
raise
except Exception:
raise HTTPException(status_code=400, detail="Invalid cursor format")
rows = await conn.fetch(
"""
SELECT id, chat_id, sender_id, text, attachment_ids, created_at
FROM messages
WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
ORDER BY created_at ASC, id ASC
LIMIT $4
""",
cid, cursor_time, cursor_id, limit + 1
)
else:
rows = await conn.fetch(
"""
SELECT id, chat_id, sender_id, text, attachment_ids, created_at
FROM messages
WHERE chat_id = $1
ORDER BY created_at ASC, id ASC
LIMIT $2
""",
cid, limit + 1
)
items = []
for r in rows[:limit]:
raw_atts = r["attachment_ids"] or []
items.append({
"id": str(r["id"]),
"chat_id": str(r["chat_id"]),
"sender_id": str(r["sender_id"]),
"text": r["text"],
"attachment_ids": [str(x) for x in raw_atts],
"created_at": to_rfc3339(r["created_at"])
})
next_cursor = None
if len(rows) > limit:
last = items[-1]
raw_cur = f"{cid}|{last['created_at']}|{last['id']}"
next_cursor = base64.b64encode(raw_cur.encode("utf-8")).decode("utf-8")
return {"items": items, "next_cursor": next_cursor}
@app.get("/chats/{chat_id}/messages")
@app.get("/api/v1/chats/{chat_id}/messages")
async def list_messages(chat_id: str, limit: int = 50, cursor: Optional[str] = None, current_user: dict = Depends(get_current_user)):
return await list_messages_handler(chat_id, limit, cursor, current_user)
+42
View File
@@ -0,0 +1,42 @@
import os
import asyncio
import asyncpg
import boto3
from botocore.client import Config
DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://appuser:apppassword@postgres:5432/messenger_db")
S3_ENDPOINT = os.getenv("S3_ENDPOINT", "http://s3:9000")
S3_BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
S3_ACCESS_KEY = os.getenv("S3_ACCESS_KEY", "miniouser")
S3_SECRET_KEY = os.getenv("S3_SECRET_KEY", "miniopassword123")
async def main():
print("1. Применение миграций базы данных PostgreSQL...")
conn = await asyncpg.connect(DATABASE_URL)
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "migrations")
sql_files = sorted([f for f in os.listdir(migrations_dir) if f.endswith(".sql")])
for sql_file in sql_files:
print(f" Выполнение: {sql_file}")
with open(os.path.join(migrations_dir, sql_file), "r", encoding="utf-8") as f:
await conn.execute(f.read())
await conn.close()
print("Миграции PostgreSQL успешно применены!")
print("\n2. Инициализация S3-бакета...")
s3 = boto3.client(
"s3",
endpoint_url=S3_ENDPOINT,
region_name="us-east-1",
aws_access_key_id=S3_ACCESS_KEY,
aws_secret_access_key=S3_SECRET_KEY,
config=Config(signature_version="s3v4")
)
try:
s3.head_bucket(Bucket=S3_BUCKET)
print(f" Бакет '{S3_BUCKET}' уже существует.")
except Exception:
s3.create_bucket(Bucket=S3_BUCKET)
print(f" Приватный бакет '{S3_BUCKET}' успешно создан!")
if __name__ == "__main__":
asyncio.run(main())