This commit is contained in:
caramelteawithmint
2026-11-20 11:19:14 +03:00
parent 276dbdad8a
commit 2b68813b33
24 changed files with 1516 additions and 0 deletions
+171
View File
@@ -0,0 +1,171 @@
import re
import uuid
from datetime import datetime
from typing import Optional
from fastapi import APIRouter, Depends, Header, Query
from pydantic import BaseModel, ConfigDict, Field
from psycopg.rows import dict_row
from ..db import connection
from ..errors import ApiError
from ..idempotency import run_idempotent
from ..serializers import row_to_message
from .sessions import require_actor
router = APIRouter(prefix="/api/v1")
KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
class CreateMessage(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(max_length=4000)
attachment_ids: list[str] = Field(default_factory=list, max_length=10)
def _check_chat_member(conn, chat_id: str, user_id: str) -> None:
with conn.cursor() as cur:
cur.execute(
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
(chat_id, user_id),
)
if cur.fetchone() is None:
raise ApiError(404, "not_found", "Чат не найден")
def _encode_cursor(created_at: datetime, id_) -> str:
import base64
raw = f"{created_at.isoformat()}|{id_}"
return base64.urlsafe_b64encode(raw.encode("utf-8")).decode("ascii").rstrip("=")
def _decode_cursor(cursor: str):
import base64
pad = "=" * (-len(cursor) % 4)
raw = base64.urlsafe_b64decode(cursor + pad).decode("utf-8")
ts, id_ = raw.split("|", 1)
return datetime.fromisoformat(ts), id_
@router.post("/chats/{chat_id}/messages", status_code=201)
def create_message(
chat_id: str,
body: CreateMessage,
idempotency_key: str = Header(..., alias="Idempotency-Key"),
actor: dict = Depends(require_actor),
):
try:
uuid.UUID(chat_id)
except ValueError:
raise ApiError(400, "invalid_request", "Неверный chat_id")
if not KEY_RE.fullmatch(idempotency_key or ""):
raise ApiError(400, "invalid_request", "Неверный Idempotency-Key")
if not body.text.strip() and not body.attachment_ids:
raise ApiError(400, "invalid_request", "Нужен текст или вложение")
scope = f"POST /api/v1/chats/{chat_id}/messages"
def action(conn):
_check_chat_member(conn, chat_id, actor["user_id"])
with conn.cursor(row_factory=dict_row) as cur:
cur.execute(
"""
INSERT INTO messages (chat_id, sender_id, text)
VALUES (%s, %s, %s)
RETURNING id, chat_id, sender_id, text, created_at
""",
(chat_id, actor["user_id"], body.text),
)
row = cur.fetchone()
if body.attachment_ids:
for att_id in body.attachment_ids:
cur.execute(
"SELECT 1 FROM attachments WHERE id = %s AND chat_id = %s",
(att_id, chat_id),
)
if cur.fetchone() is None:
raise ApiError(404, "not_found", "Вложение не найдено")
cur.executemany(
"INSERT INTO message_attachments (message_id, attachment_id) VALUES (%s, %s)",
[(row["id"], att_id) for att_id in body.attachment_ids]
)
row["attachment_ids"] = body.attachment_ids
return 201, row_to_message(row)
_, payload = run_idempotent(
user_id=actor["user_id"],
scope=scope,
key=idempotency_key,
body=body.model_dump(),
action=action,
)
return payload
@router.get("/chats/{chat_id}/messages")
def list_messages(
chat_id: str,
limit: int = Query(default=50, ge=1, le=100),
cursor: Optional[str] = Query(default=None),
actor: dict = Depends(require_actor),
):
try:
uuid.UUID(chat_id)
except ValueError:
raise ApiError(400, "invalid_request", "Неверный chat_id")
with connection() as conn:
with conn.cursor() as cur:
cur.execute(
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
(chat_id, actor["user_id"]),
)
if cur.fetchone() is None:
raise ApiError(404, "not_found", "Чат не найден")
params: list = [chat_id]
where = ["m.chat_id = %s"]
if cursor:
try:
c_ts, c_id = _decode_cursor(cursor)
except Exception:
raise ApiError(400, "invalid_request", "Неверный cursor")
where.append("(m.created_at, m.id) > (%s, %s)")
params.extend([c_ts, c_id])
sql = f"""
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
COALESCE(
ARRAY(
SELECT ma.attachment_id::text
FROM message_attachments ma
WHERE ma.message_id = m.id
), ARRAY[]::text[]
) AS attachment_ids
FROM messages m
WHERE {' AND '.join(where)}
ORDER BY m.created_at, m.id
LIMIT %s
"""
params.append(limit + 1)
with connection() as conn:
with conn.cursor(row_factory=dict_row) as cur:
cur.execute(sql, params)
rows = cur.fetchall()
next_cursor = None
if len(rows) > limit:
last = rows[limit - 1]
next_cursor = _encode_cursor(last["created_at"], str(last["id"]))
rows = rows[:limit]
return {"items": [row_to_message(r) for r in rows], "next_cursor": next_cursor}