forked from mtusi2026/mtusi2026lab3
140 lines
6.9 KiB
Python
140 lines
6.9 KiB
Python
"""Параметризованный SQL. Одна функция записи — одна транзакция."""
|
|
from uuid import UUID, uuid4
|
|
|
|
from psycopg.errors import ForeignKeyViolation, UniqueViolation
|
|
|
|
from src import db, pagination
|
|
from src.errors import ApiError
|
|
from src.config import IDEMPOTENCY_TTL
|
|
|
|
|
|
def utc(value):
|
|
return value.isoformat(timespec="microseconds").replace("+00:00", "Z")
|
|
|
|
|
|
def public_user(row):
|
|
return {"id": str(row["id"]), "username": row["username"],
|
|
"display_name": row["display_name"], "created_at": utc(row["created_at"])}
|
|
|
|
|
|
def public_chat(row):
|
|
return {"id": str(row["id"]), "title": row["title"],
|
|
"member_ids": [str(value) for value in row["member_ids"]], "created_at": utc(row["created_at"])}
|
|
|
|
|
|
def public_message(row):
|
|
return {"id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]),
|
|
"text": row["text"], "created_at": utc(row["created_at"])}
|
|
|
|
|
|
def create_user(username, display_name, password_hash):
|
|
try:
|
|
with db.connection() as conn:
|
|
row = conn.execute("""INSERT INTO users(id, username, display_name, password_hash)
|
|
VALUES (%s, %s, %s, %s) RETURNING *""", (uuid4(), username, display_name, password_hash)).fetchone()
|
|
result = public_user(row)
|
|
return result
|
|
except UniqueViolation:
|
|
raise ApiError(409, "conflict", "Имя пользователя уже занято") from None
|
|
|
|
|
|
def find_login(username):
|
|
with db.connection() as conn:
|
|
return conn.execute("SELECT * FROM users WHERE username=%s", (username,)).fetchone()
|
|
|
|
|
|
def find_user(user_id):
|
|
with db.connection() as conn:
|
|
row = conn.execute("SELECT * FROM users WHERE id=%s", (UUID(user_id),)).fetchone()
|
|
return public_user(row) if row else None
|
|
|
|
|
|
def create_chat(user_id, title, member_ids):
|
|
if user_id not in member_ids:
|
|
raise ApiError(400, "invalid_request", "Создатель должен входить в member_ids")
|
|
try:
|
|
with db.connection() as conn:
|
|
row = conn.execute("INSERT INTO chats(id, title) VALUES (%s, %s) RETURNING *", (uuid4(), title)).fetchone()
|
|
with conn.cursor() as cur:
|
|
cur.executemany("INSERT INTO chat_members(chat_id, user_id) VALUES (%s, %s)",
|
|
[(row["id"], UUID(member)) for member in member_ids])
|
|
row["member_ids"] = member_ids
|
|
result = public_chat(row)
|
|
return result
|
|
except ForeignKeyViolation:
|
|
raise ApiError(400, "invalid_request", "Все участники должны существовать") from None
|
|
|
|
|
|
def require_member(conn, user_id, chat_id):
|
|
row = conn.execute("SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s", (UUID(chat_id), UUID(user_id))).fetchone()
|
|
if row is None:
|
|
raise ApiError(404, "not_found", "Чат не найден")
|
|
|
|
|
|
def get_chat(user_id, chat_id):
|
|
with db.connection() as conn:
|
|
require_member(conn, user_id, chat_id)
|
|
row = conn.execute("""SELECT c.*, ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id) AS member_ids
|
|
FROM chats c WHERE c.id=%s""", (UUID(chat_id),)).fetchone()
|
|
return public_chat(row)
|
|
|
|
|
|
def list_chats(user_id, limit, cursor):
|
|
scope = "chats:" + user_id
|
|
size, anchor = pagination.parameters(limit, cursor, scope)
|
|
with db.connection() as conn:
|
|
if anchor:
|
|
found = conn.execute("""SELECT 1 FROM chats c JOIN chat_members m ON m.chat_id=c.id
|
|
WHERE m.user_id=%s AND (c.created_at, c.id)=(%s, %s)""", (UUID(user_id), *anchor)).fetchone()
|
|
if not found:
|
|
raise ApiError(400, "invalid_request", "Неверный cursor")
|
|
condition = "AND (c.created_at, c.id) > (%s, %s)" if anchor else ""
|
|
params = (UUID(user_id), *(anchor or ()), size + 1)
|
|
rows = conn.execute("""WITH selected AS (
|
|
SELECT c.* FROM chats c JOIN chat_members own ON own.chat_id=c.id
|
|
WHERE own.user_id=%s """ + condition + """ ORDER BY c.created_at, c.id LIMIT %s
|
|
) SELECT c.*, ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id) AS member_ids
|
|
FROM selected c ORDER BY c.created_at, c.id""", params).fetchall()
|
|
return pagination.page([public_chat(row) for row in rows], size, scope)
|
|
|
|
|
|
def create_message(user_id, chat_id, text, key):
|
|
with db.connection() as conn:
|
|
require_member(conn, user_id, chat_id)
|
|
# Одна блокировка на область ключа во всех API-процессах.
|
|
# Побочный эффект и результат повтора фиксируются одной транзакцией.
|
|
scope = user_id + ":POST:/api/v1/chats/" + chat_id + "/messages:" + key
|
|
conn.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", (scope,))
|
|
previous = conn.execute("""SELECT m.*, i.request_text FROM message_idempotency i
|
|
JOIN messages m ON m.id=i.message_id
|
|
WHERE i.user_id=%s AND i.chat_id=%s AND i.key=%s AND i.expires_at>clock_timestamp()""",
|
|
(UUID(user_id), UUID(chat_id), key)).fetchone()
|
|
if previous:
|
|
if previous["request_text"] != text:
|
|
raise ApiError(409, "conflict", "Этот ключ уже использован с другим сообщением")
|
|
return public_message(previous)
|
|
conn.execute("DELETE FROM message_idempotency WHERE user_id=%s AND chat_id=%s AND key=%s",
|
|
(UUID(user_id), UUID(chat_id), key))
|
|
row = conn.execute("""INSERT INTO messages(id, chat_id, sender_id, text) VALUES (%s, %s, %s, %s)
|
|
RETURNING *""", (uuid4(), UUID(chat_id), UUID(user_id), text)).fetchone()
|
|
conn.execute("""INSERT INTO message_idempotency(user_id, chat_id, key, request_text, message_id, expires_at)
|
|
VALUES (%s, %s, %s, %s, %s, clock_timestamp() + %s * interval '1 second')""",
|
|
(UUID(user_id), UUID(chat_id), key, text, row["id"], IDEMPOTENCY_TTL))
|
|
result = public_message(row)
|
|
return result
|
|
|
|
|
|
def list_messages(user_id, chat_id, limit, cursor):
|
|
scope = "messages:" + chat_id
|
|
size, anchor = pagination.parameters(limit, cursor, scope)
|
|
with db.connection() as conn:
|
|
require_member(conn, user_id, chat_id)
|
|
if anchor:
|
|
found = conn.execute("SELECT 1 FROM messages WHERE chat_id=%s AND (created_at, id)=(%s, %s)", (UUID(chat_id), *anchor)).fetchone()
|
|
if not found:
|
|
raise ApiError(400, "invalid_request", "Неверный cursor")
|
|
condition = "AND (created_at, id) > (%s, %s)" if anchor else ""
|
|
rows = conn.execute("SELECT * FROM messages WHERE chat_id=%s " + condition +
|
|
" ORDER BY created_at, id LIMIT %s", (UUID(chat_id), *(anchor or ()), size + 1)).fetchall()
|
|
return pagination.page([public_message(row) for row in rows], size, scope)
|