Выполнение лабораторной работы номер 7
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,592 @@
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import socket
|
||||
import uuid
|
||||
import time
|
||||
import telemetry as ot
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import psycopg
|
||||
from psycopg import errors
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerificationError
|
||||
from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request, Response
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
import cache
|
||||
import db
|
||||
from attachments import router as attachment_router, S3, BUCKET
|
||||
from schemas import (
|
||||
User, CreateUser, Session,
|
||||
Chat, CreateChat, ChatPage,
|
||||
Message, CreateMessage, MessagePage,
|
||||
)
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
log = logging.getLogger("messenger")
|
||||
|
||||
SESSION_TTL_SECONDS = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
||||
INSTANCE_ID = uuid.uuid4().hex
|
||||
|
||||
ph = PasswordHasher(memory_cost=19456,time_cost=2,parallelism=1)
|
||||
# Хеш-заглушка: проверяем пароль даже для несуществующего username,
|
||||
# чтобы по времени ответа нельзя было узнать, есть ли такой пользователь
|
||||
DUMMY_HASH = ph.hash("dummy-password-for-timing")
|
||||
|
||||
BASIC_CHALLENGE = {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
|
||||
BEARER_CHALLENGE = {"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||
|
||||
ERROR_CODES = {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
404: "not_found",
|
||||
409: "conflict",
|
||||
413: "payload_too_large",
|
||||
415: "unsupported_media_type",
|
||||
429: "rate_limited",
|
||||
503: "unavailable",
|
||||
}
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
db.pool.open(wait=True, timeout=30) # ждём, пока БД станет доступна
|
||||
cache.start() # фоновая проверка доступности Redis
|
||||
yield # тут приложение работает
|
||||
db.pool.close() # при остановке (SIGTERM) закрываем пул
|
||||
|
||||
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
|
||||
|
||||
# ---------- Вспомогательные функции ----------
|
||||
|
||||
def iso(dt: datetime) -> str:
|
||||
return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
def parse_uuid(value: str, what: str) -> str:
|
||||
try:
|
||||
return str(uuid.UUID(value))
|
||||
except ValueError:
|
||||
raise HTTPException(400, f"invalid {what}")
|
||||
|
||||
|
||||
def hash_token(token: str) -> str:
|
||||
return hashlib.sha256(token.encode()).hexdigest()
|
||||
|
||||
|
||||
def check_password(password_hash: str, password: str) -> bool:
|
||||
try:
|
||||
return ph.verify(password_hash, password)
|
||||
except (VerificationError, InvalidHashError):
|
||||
return False
|
||||
|
||||
|
||||
def user_from_row(row) -> User:
|
||||
return User(
|
||||
id=str(row["id"]),
|
||||
username=row["username"],
|
||||
display_name=row["display_name"],
|
||||
created_at=iso(row["created_at"]),
|
||||
)
|
||||
|
||||
|
||||
def chat_from_row(row) -> Chat:
|
||||
return Chat(
|
||||
id=str(row["id"]),
|
||||
title=row["title"],
|
||||
member_ids=[str(m) for m in row["member_ids"]],
|
||||
created_at=iso(row["created_at"]),
|
||||
)
|
||||
|
||||
|
||||
def message_from_row(row) -> Message:
|
||||
return Message(
|
||||
id=str(row["id"]),
|
||||
chat_id=str(row["chat_id"]),
|
||||
sender_id=str(row["sender_id"]),
|
||||
text=row["text"],
|
||||
attachment_ids=[str(v) for v in row["attachment_ids"]],
|
||||
created_at=iso(row["created_at"]),
|
||||
)
|
||||
|
||||
|
||||
# Курсор = base64(JSON) с последним (created_at, id) и "областью" (какой чат/список).
|
||||
# Курсор от другого чата не подойдёт -> 400.
|
||||
def encode_cursor(scope: str, created_at: datetime, item_id) -> str:
|
||||
raw = json.dumps({"s": scope, "t": iso(created_at), "i": str(item_id)})
|
||||
return base64.urlsafe_b64encode(raw.encode()).decode().rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(cursor: str, scope: str) -> tuple[datetime, str]:
|
||||
try:
|
||||
padded = cursor + "=" * (-len(cursor) % 4)
|
||||
data = json.loads(base64.urlsafe_b64decode(padded))
|
||||
if data["s"] != scope:
|
||||
raise ValueError("cursor from another resource")
|
||||
return datetime.fromisoformat(data["t"]), str(uuid.UUID(data["i"]))
|
||||
except (ValueError, KeyError, TypeError, binascii.Error):
|
||||
raise HTTPException(400, "invalid cursor")
|
||||
|
||||
|
||||
def is_member(conn, chat_id: str, user_id: str) -> bool:
|
||||
row = conn.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id, user_id),
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
|
||||
# ---------- Ошибки и X-Request-Id ----------
|
||||
|
||||
def error_response(status: int, message: str, request_id: str, headers=None) -> JSONResponse:
|
||||
if status in ERROR_CODES:
|
||||
code = ERROR_CODES[status]
|
||||
elif status < 500:
|
||||
code = "invalid_request"
|
||||
else:
|
||||
code = "internal_error"
|
||||
return JSONResponse(
|
||||
status_code=status,
|
||||
content={"error": {"code": code, "message": message, "request_id": request_id}},
|
||||
headers=headers or {},
|
||||
)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_id_middleware(request: Request, call_next):
|
||||
rid = request.headers.get("X-Request-Id")
|
||||
try:
|
||||
rid = str(uuid.UUID(rid or ""))
|
||||
except ValueError:
|
||||
rid = str(uuid.uuid4())
|
||||
request.state.request_id = rid
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except psycopg.OperationalError:
|
||||
# БД недоступна / пул исчерпан (PoolTimeout тоже OperationalError)
|
||||
log.exception("database unavailable")
|
||||
response = error_response(503, "service temporarily unavailable", rid)
|
||||
except Exception:
|
||||
log.exception("unhandled error")
|
||||
response = error_response(500, "internal error", rid)
|
||||
response.headers["X-Request-Id"] = rid
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return response
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def observe_http(request: Request, call_next):
|
||||
start=time.monotonic()
|
||||
with ot.tracer.start_as_current_span('HTTP '+request.method,kind=SpanKind.SERVER) as span:
|
||||
response=await call_next(request)
|
||||
route=getattr(request.scope.get('route'),'path','unmatched')
|
||||
status=response.status_code
|
||||
attrs={'method':request.method,'route':route,'status_class':str(status//100)+'xx'}
|
||||
span.update_name(request.method+' '+route)
|
||||
span.set_attribute('http.route',route)
|
||||
span.set_attribute('http.response.status_code',status)
|
||||
if status>=500:
|
||||
span.set_status(Status(StatusCode.ERROR))
|
||||
ot.http_count.add(1,attrs)
|
||||
ot.http_duration.record(time.monotonic()-start,attrs)
|
||||
ot.logger.info('http_request',extra={'route':route,'method':request.method,'status':status,
|
||||
'request_id':response.headers.get('X-Request-Id','')})
|
||||
response.headers['X-Trace-Id']=format(span.get_span_context().trace_id,'032x')
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_handler(request: Request, exc: RequestValidationError):
|
||||
return error_response(400, "invalid request", request.state.request_id)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
||||
return error_response(exc.status_code, str(exc.detail), request.state.request_id, exc.headers)
|
||||
|
||||
|
||||
# ---------- Аутентификация ----------
|
||||
|
||||
def parse_basic(authorization: str | None) -> tuple[str, str]:
|
||||
scheme, _, encoded = (authorization or "").partition(" ")
|
||||
if scheme.lower() != "basic" or not encoded.strip():
|
||||
raise HTTPException(401, "unauthorized", BASIC_CHALLENGE)
|
||||
try:
|
||||
decoded = base64.b64decode(encoded.strip(), validate=True).decode("utf-8")
|
||||
except (binascii.Error, UnicodeDecodeError):
|
||||
raise HTTPException(401, "unauthorized", BASIC_CHALLENGE)
|
||||
username, sep, password = decoded.partition(":") # двоеточие в пароле допустимо
|
||||
if not sep:
|
||||
raise HTTPException(401, "unauthorized", BASIC_CHALLENGE)
|
||||
return username, password
|
||||
|
||||
|
||||
def current_session(authorization: str | None = Header(default=None)) -> dict:
|
||||
# Принимаем только Bearer; X-User-Id и Basic здесь игнорируются -> 401
|
||||
scheme, _, token = (authorization or "").partition(" ")
|
||||
token = token.strip()
|
||||
if scheme.lower() != "bearer" or not token:
|
||||
raise HTTPException(401, "unauthorized", BEARER_CHALLENGE)
|
||||
token_hash = hash_token(token)
|
||||
|
||||
# 1. Кэш Redis (если доступен)
|
||||
cached = cache.get_session(token_hash)
|
||||
if cached == cache.REVOKED:
|
||||
raise HTTPException(401, "unauthorized", BEARER_CHALLENGE)
|
||||
# The source of truth is consulted even on cache hit, ensuring immediate revocation.
|
||||
|
||||
# 2. Промах или Redis недоступен -> источник истины PostgreSQL
|
||||
with db.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = %s
|
||||
AND s.revoked_at IS NULL
|
||||
AND s.expires_at > now()
|
||||
""",
|
||||
(token_hash,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise HTTPException(401, "unauthorized", BEARER_CHALLENGE)
|
||||
user = user_from_row(row)
|
||||
cache.put_session(token_hash, user.model_dump(), row["expires_at"])
|
||||
return {"user": user, "token_hash": token_hash}
|
||||
|
||||
|
||||
def current_user(session: dict = Depends(current_session)) -> User:
|
||||
return session["user"]
|
||||
|
||||
|
||||
app.include_router(attachment_router(current_user, is_member, parse_uuid, iso))
|
||||
|
||||
|
||||
# ---------- Health ----------
|
||||
|
||||
@app.get("/health/live")
|
||||
def liveness():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/health/ready")
|
||||
def readiness():
|
||||
try:
|
||||
with db.pool.connection(timeout=2) as conn:
|
||||
conn.execute("SELECT 1")
|
||||
S3.head_bucket(Bucket=BUCKET)
|
||||
except Exception:
|
||||
raise HTTPException(503, "database unavailable")
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
# ---------- Пользователи и сессии ----------
|
||||
|
||||
@app.post("/api/v1/users", status_code=201, response_model=User)
|
||||
def register_user(payload: CreateUser):
|
||||
password_hash = ph.hash(payload.password)
|
||||
try:
|
||||
with db.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO users (id, username, display_name, password_hash)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
RETURNING id, username, display_name, created_at
|
||||
""",
|
||||
(uuid.uuid4(), payload.username, payload.display_name, password_hash),
|
||||
).fetchone()
|
||||
except errors.UniqueViolation:
|
||||
# Гонку двух одинаковых регистраций разруливает UNIQUE в БД
|
||||
raise HTTPException(409, "username already taken")
|
||||
return user_from_row(row)
|
||||
|
||||
|
||||
@app.post("/api/v1/auth/sessions", status_code=201, response_model=Session)
|
||||
def create_session(authorization: str | None = Header(default=None)):
|
||||
username, password = parse_basic(authorization)
|
||||
|
||||
# A global DB-backed login budget is shared by all API replicas.
|
||||
# Commit increments before expensive password hashing, including invalid passwords.
|
||||
if len(username)>32 or len(password)>128:
|
||||
raise HTTPException(401, "invalid credentials", BASIC_CHALLENGE)
|
||||
with db.pool.connection() as conn:
|
||||
limit_row=conn.execute("""INSERT INTO login_attempts(scope,window_start,attempts)
|
||||
VALUES ('global',now(),1) ON CONFLICT(scope) DO UPDATE SET
|
||||
attempts=CASE WHEN login_attempts.window_start<now()-interval '1 minute' THEN 1 ELSE login_attempts.attempts+1 END,
|
||||
window_start=CASE WHEN login_attempts.window_start<now()-interval '1 minute' THEN now() ELSE login_attempts.window_start END
|
||||
RETURNING attempts""").fetchone()
|
||||
if limit_row['attempts']>120:
|
||||
raise HTTPException(429,"login rate limited",headers={'Retry-After':'60'})
|
||||
|
||||
with db.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users WHERE username = %s
|
||||
""",
|
||||
(username,),
|
||||
).fetchone()
|
||||
|
||||
# Проверка пароля вне соединения с БД: argon2 медленный, не держим соединение пула
|
||||
if row is None:
|
||||
check_password(DUMMY_HASH, password)
|
||||
raise HTTPException(401, "invalid credentials", BASIC_CHALLENGE)
|
||||
if not check_password(row["password_hash"], password):
|
||||
raise HTTPException(401, "invalid credentials", BASIC_CHALLENGE)
|
||||
|
||||
token = secrets.token_urlsafe(32) # 32 случайных байта = 256 бит
|
||||
with db.pool.connection() as conn:
|
||||
if ph.check_needs_rehash(row['password_hash']):
|
||||
conn.execute('UPDATE users SET password_hash=%s WHERE id=%s',(ph.hash(password),row['id']))
|
||||
session = conn.execute(
|
||||
"""
|
||||
INSERT INTO sessions (token_hash, user_id, expires_at)
|
||||
VALUES (%s, %s, now() + %s * interval '1 second')
|
||||
RETURNING expires_at
|
||||
""",
|
||||
(hash_token(token), row["id"], SESSION_TTL_SECONDS),
|
||||
).fetchone()
|
||||
|
||||
user = user_from_row(row)
|
||||
# Сессия уже сохранена в PostgreSQL (COMMIT); кэш — только ускорение
|
||||
cache.put_session(hash_token(token), user.model_dump(), session["expires_at"])
|
||||
return Session(
|
||||
token=token,
|
||||
token_type="Bearer",
|
||||
expires_at=iso(session["expires_at"]),
|
||||
user=user,
|
||||
)
|
||||
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
def delete_session(session: dict = Depends(current_session)):
|
||||
with db.pool.connection() as conn:
|
||||
conn.execute(
|
||||
"UPDATE sessions SET revoked_at = now() WHERE token_hash = %s AND revoked_at IS NULL",
|
||||
(session["token_hash"],),
|
||||
)
|
||||
# Сначала отзыв в источнике истины, потом "надгробие" в кэше
|
||||
cache.revoke_session(session["token_hash"])
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me", response_model=User)
|
||||
def get_me(me: User = Depends(current_user)):
|
||||
return me
|
||||
|
||||
|
||||
# ---------- Чаты ----------
|
||||
|
||||
@app.post("/api/v1/chats", status_code=201, response_model=Chat)
|
||||
def create_chat(payload: CreateChat, me: User = Depends(current_user)):
|
||||
member_ids = [parse_uuid(m, "member id") for m in payload.member_ids]
|
||||
if len(set(member_ids)) != len(member_ids):
|
||||
raise HTTPException(400, "member_ids must be unique")
|
||||
if me.id not in member_ids:
|
||||
raise HTTPException(400, "caller must be a member")
|
||||
|
||||
chat_id = uuid.uuid4()
|
||||
try:
|
||||
with db.pool.connection() as conn:
|
||||
# Атомарно: чат и все участники сохраняются вместе или не сохраняется ничего
|
||||
with conn.transaction():
|
||||
chat = conn.execute(
|
||||
"INSERT INTO chats (id, title) VALUES (%s, %s) RETURNING id, title, created_at",
|
||||
(chat_id, payload.title),
|
||||
).fetchone()
|
||||
with conn.cursor() as cur:
|
||||
cur.executemany(
|
||||
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
|
||||
[(chat_id, m) for m in member_ids],
|
||||
)
|
||||
except errors.ForeignKeyViolation:
|
||||
# Неизвестный участник: транзакция откатилась, чата в БД нет
|
||||
raise HTTPException(400, "unknown member")
|
||||
|
||||
return Chat(
|
||||
id=str(chat["id"]),
|
||||
title=chat["title"],
|
||||
member_ids=member_ids,
|
||||
created_at=iso(chat["created_at"]),
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats", response_model=ChatPage)
|
||||
def list_chats(
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: str | None = Query(default=None, min_length=1),
|
||||
me: User = Depends(current_user),
|
||||
):
|
||||
scope = "chats:" + me.id
|
||||
params: list = [me.id]
|
||||
after = ""
|
||||
if cursor is not None:
|
||||
created_at, last_id = decode_cursor(cursor, scope)
|
||||
after = "AND (c.created_at, c.id) > (%s, %s)"
|
||||
params += [created_at, last_id]
|
||||
params.append(limit + 1) # берём на 1 больше, чтобы понять, есть ли следующая страница
|
||||
|
||||
with db.pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
array_agg(m.user_id ORDER BY m.user_id) AS member_ids
|
||||
FROM chat_members my
|
||||
JOIN chats c ON c.id = my.chat_id
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE my.user_id = %s {after}
|
||||
GROUP BY c.id
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT %s
|
||||
""",
|
||||
params,
|
||||
).fetchall()
|
||||
|
||||
next_cursor = None
|
||||
if len(rows) > limit:
|
||||
rows = rows[:limit]
|
||||
next_cursor = encode_cursor(scope, rows[-1]["created_at"], rows[-1]["id"])
|
||||
return ChatPage(items=[chat_from_row(r) for r in rows], next_cursor=next_cursor)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}", response_model=Chat)
|
||||
def get_chat(chat_id: str, me: User = Depends(current_user)):
|
||||
cid = parse_uuid(chat_id, "chat id")
|
||||
with db.pool.connection() as conn:
|
||||
if not is_member(conn, cid, me.id):
|
||||
raise HTTPException(404, "chat not found") # чужой чат = как будто его нет
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
array_agg(m.user_id ORDER BY m.user_id) AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE c.id = %s
|
||||
GROUP BY c.id
|
||||
""",
|
||||
(cid,),
|
||||
).fetchone()
|
||||
return chat_from_row(row)
|
||||
|
||||
|
||||
# ---------- Сообщения ----------
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201, response_model=Message)
|
||||
def create_message(
|
||||
chat_id: str,
|
||||
payload: CreateMessage,
|
||||
me: User = Depends(current_user),
|
||||
idempotency_key: str | None = Header(default=None),
|
||||
):
|
||||
cid = parse_uuid(chat_id, "chat id")
|
||||
if not idempotency_key or not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", idempotency_key):
|
||||
raise HTTPException(400, "invalid Idempotency-Key")
|
||||
|
||||
path = f"/api/v1/chats/{cid}/messages"
|
||||
request_hash = hashlib.sha256(json.dumps(payload.model_dump(), sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest()
|
||||
message_id = uuid.uuid4()
|
||||
scope = (me.id, "POST", path, idempotency_key)
|
||||
|
||||
with db.pool.connection() as conn:
|
||||
if not is_member(conn, cid, me.id):
|
||||
raise HTTPException(404, "chat not found")
|
||||
|
||||
if payload.attachment_ids:
|
||||
available = conn.execute("SELECT id,status FROM attachments WHERE chat_id = %s AND status != 'pending' AND id = ANY(%s::uuid[])",
|
||||
(cid, payload.attachment_ids)).fetchall()
|
||||
if len(available) != len(payload.attachment_ids):
|
||||
raise HTTPException(404, "attachment not found")
|
||||
if any(a["status"] == "failed" for a in available):
|
||||
raise HTTPException(409, "attachment failed")
|
||||
|
||||
# Reserve the key atomically. A competing transaction waits at the unique index.
|
||||
# Only expired keys may be replaced. The foreign key is checked at COMMIT.
|
||||
claimed = conn.execute(
|
||||
"""
|
||||
INSERT INTO idempotency_keys
|
||||
(user_id, method, path, key, request_hash, message_id, expires_at)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, clock_timestamp() + interval '24 hours')
|
||||
ON CONFLICT (user_id, method, path, key) DO UPDATE
|
||||
SET request_hash = EXCLUDED.request_hash,
|
||||
message_id = EXCLUDED.message_id,
|
||||
expires_at = clock_timestamp() + interval '24 hours'
|
||||
WHERE idempotency_keys.expires_at <= clock_timestamp()
|
||||
RETURNING message_id
|
||||
""",
|
||||
(*scope, request_hash, message_id),
|
||||
).fetchone()
|
||||
|
||||
if claimed is None:
|
||||
# The existing unexpired key belongs to an already committed message.
|
||||
previous = conn.execute(
|
||||
"""
|
||||
SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at, m.attachment_ids
|
||||
FROM idempotency_keys k JOIN messages m ON m.id = k.message_id
|
||||
WHERE k.user_id = %s AND k.method = %s AND k.path = %s AND k.key = %s
|
||||
""",
|
||||
scope,
|
||||
).fetchone()
|
||||
if previous["request_hash"] != request_hash:
|
||||
raise HTTPException(409, "Idempotency-Key already used with another message")
|
||||
return message_from_row(previous)
|
||||
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, attachment_ids)
|
||||
VALUES (%s, %s, %s, %s, %s::uuid[])
|
||||
RETURNING id, chat_id, sender_id, text, created_at, attachment_ids
|
||||
""",
|
||||
(message_id, cid, me.id, payload.text, payload.attachment_ids),
|
||||
).fetchone()
|
||||
return message_from_row(row)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
def list_messages(
|
||||
chat_id: str,
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: str | None = Query(default=None, min_length=1),
|
||||
me: User = Depends(current_user),
|
||||
):
|
||||
cid = parse_uuid(chat_id, "chat id")
|
||||
scope = "messages:" + cid
|
||||
params: list = [cid]
|
||||
after = ""
|
||||
if cursor is not None:
|
||||
created_at, last_id = decode_cursor(cursor, scope)
|
||||
# keyset-пагинация: продолжаем строго после последнего (created_at, id)
|
||||
after = "AND (created_at, id) > (%s, %s)"
|
||||
params += [created_at, last_id]
|
||||
params.append(limit + 1)
|
||||
|
||||
with db.pool.connection() as conn:
|
||||
if not is_member(conn, cid, me.id):
|
||||
raise HTTPException(404, "chat not found")
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
SELECT id, chat_id, sender_id, text, created_at, attachment_ids
|
||||
FROM messages
|
||||
WHERE chat_id = %s {after}
|
||||
ORDER BY created_at, id
|
||||
LIMIT %s
|
||||
""",
|
||||
params,
|
||||
).fetchall()
|
||||
|
||||
next_cursor = None
|
||||
if len(rows) > limit:
|
||||
rows = rows[:limit]
|
||||
next_cursor = encode_cursor(scope, rows[-1]["created_at"], rows[-1]["id"])
|
||||
return MessagePage(items=[message_from_row(r) for r in rows], next_cursor=next_cursor)
|
||||
Reference in New Issue
Block a user