381 lines
19 KiB
Python
381 lines
19 KiB
Python
"""
|
||
Доступ к данным в PostgreSQL. Только параметризованные запросы (%s):
|
||
значения передаются отдельно от текста SQL, инъекция невозможна.
|
||
"""
|
||
from __future__ import annotations
|
||
import base64
|
||
import hashlib
|
||
import json
|
||
import uuid
|
||
from datetime import datetime, timezone
|
||
|
||
from psycopg.errors import UniqueViolation
|
||
|
||
|
||
def iso(dt: datetime) -> str:
|
||
"""RFC 3339 UTC с Z — формат контракта."""
|
||
return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
|
||
|
||
|
||
def now() -> datetime:
|
||
return datetime.now(timezone.utc)
|
||
|
||
|
||
# ---------------------------------------------------------------- курсор
|
||
def encode_cursor(scope: str, created_at: datetime, id_) -> str:
|
||
raw = json.dumps({"s": scope, "c": iso(created_at), "i": str(id_)}).encode()
|
||
return base64.urlsafe_b64encode(raw).decode()
|
||
|
||
|
||
def decode_cursor(cursor: str, scope: str) -> tuple[datetime, uuid.UUID]:
|
||
"""(created_at, id) последнего показанного элемента или ValueError → 400."""
|
||
try:
|
||
data = json.loads(base64.urlsafe_b64decode(cursor.encode()))
|
||
if data.get("s") != scope:
|
||
raise ValueError("cursor scope mismatch")
|
||
return datetime.fromisoformat(data["c"].replace("Z", "+00:00")), uuid.UUID(data["i"])
|
||
except (ValueError, KeyError, TypeError, AttributeError) as exc:
|
||
raise ValueError("bad cursor") from exc
|
||
|
||
|
||
def _page(rows: list, limit: int, scope: str, key):
|
||
"""rows получены с LIMIT limit+1: лишняя строка = есть следующая страница."""
|
||
has_more = len(rows) > limit
|
||
page = rows[:limit]
|
||
next_cursor = encode_cursor(scope, *key(page[-1])) if has_more and page else None
|
||
return page, next_cursor
|
||
|
||
|
||
# ---------------------------------------------------------------- users
|
||
USER_COLS = "id, username, display_name, created_at"
|
||
|
||
|
||
def user_out(row) -> dict:
|
||
return {"id": str(row[0]), "username": row[1], "display_name": row[2], "created_at": iso(row[3])}
|
||
|
||
|
||
class UsernameTaken(Exception):
|
||
pass
|
||
|
||
|
||
async def create_user(conn, username: str, display_name: str, password_hash: str) -> dict:
|
||
try:
|
||
cur = await conn.execute(
|
||
f"INSERT INTO users (id, username, display_name, password_hash, created_at) "
|
||
f"VALUES (%s, %s, %s, %s, %s) RETURNING {USER_COLS}",
|
||
(uuid.uuid4(), username, display_name, password_hash, now()))
|
||
except UniqueViolation as exc:
|
||
# Уникальность username гарантирует БД, а не проверка «есть ли такой»
|
||
# перед вставкой: две одновременные регистрации не пройдут обе.
|
||
raise UsernameTaken() from exc
|
||
return user_out(await cur.fetchone())
|
||
|
||
|
||
async def get_user(conn, user_id) -> dict | None:
|
||
cur = await conn.execute(f"SELECT {USER_COLS} FROM users WHERE id = %s", (user_id,))
|
||
row = await cur.fetchone()
|
||
return user_out(row) if row else None
|
||
|
||
|
||
async def get_credentials(conn, username: str):
|
||
cur = await conn.execute(
|
||
f"SELECT {USER_COLS}, password_hash FROM users WHERE username = %s", (username,))
|
||
return await cur.fetchone()
|
||
|
||
|
||
async def update_password_hash(conn, user_id, password_hash: str) -> None:
|
||
await conn.execute("UPDATE users SET password_hash = %s WHERE id = %s", (password_hash, user_id))
|
||
|
||
|
||
# ---------------------------------------------------------------- chats
|
||
CHAT_SELECT = (
|
||
"SELECT c.id, c.title, c.created_at, "
|
||
" (SELECT array_agg(m.user_id ORDER BY m.position) FROM chat_members m WHERE m.chat_id = c.id) "
|
||
"FROM chats c ")
|
||
|
||
|
||
def chat_out(row) -> dict:
|
||
return {"id": str(row[0]), "title": row[1],
|
||
"member_ids": [str(x) for x in row[3]], "created_at": iso(row[2])}
|
||
|
||
|
||
async def count_existing_users(conn, ids: list[uuid.UUID]) -> int:
|
||
cur = await conn.execute("SELECT count(*) FROM users WHERE id = ANY(%s)", (ids,))
|
||
return (await cur.fetchone())[0]
|
||
|
||
|
||
async def insert_chat(conn, title: str, member_ids: list[uuid.UUID], creator) -> dict:
|
||
"""Чат + все участники. Вызывать внутри транзакции: либо всё, либо ничего."""
|
||
chat_id, created = uuid.uuid4(), now()
|
||
await conn.execute(
|
||
"INSERT INTO chats (id, title, created_by, created_at) VALUES (%s, %s, %s, %s)",
|
||
(chat_id, title, creator, created))
|
||
async with conn.cursor() as cur:
|
||
await cur.executemany(
|
||
"INSERT INTO chat_members (chat_id, user_id, position) VALUES (%s, %s, %s)",
|
||
[(chat_id, uid, pos) for pos, uid in enumerate(member_ids)])
|
||
return {"id": str(chat_id), "title": title,
|
||
"member_ids": [str(x) for x in member_ids], "created_at": iso(created)}
|
||
|
||
|
||
async def get_chat_for_member(conn, chat_id, user_id) -> dict | None:
|
||
"""Чат, если он существует И пользователь в нём состоит; иначе None (→ 404)."""
|
||
cur = await conn.execute(
|
||
CHAT_SELECT + "WHERE c.id = %s AND EXISTS "
|
||
"(SELECT 1 FROM chat_members x WHERE x.chat_id = c.id AND x.user_id = %s)",
|
||
(chat_id, user_id))
|
||
row = await cur.fetchone()
|
||
return chat_out(row) if row else None
|
||
|
||
|
||
async def list_chats(conn, user_id, limit: int, cursor: str | None):
|
||
scope = f"chats:{user_id}"
|
||
params: list = [user_id]
|
||
where = ""
|
||
if cursor:
|
||
c_at, c_id = decode_cursor(cursor, scope)
|
||
where = "WHERE (c.created_at, c.id) > (%s, %s) "
|
||
params += [c_at, c_id]
|
||
cur = await conn.execute(
|
||
CHAT_SELECT + "JOIN chat_members me ON me.chat_id = c.id AND me.user_id = %s "
|
||
+ where + "ORDER BY c.created_at, c.id LIMIT %s", (*params, limit + 1))
|
||
rows = await cur.fetchall()
|
||
page, nxt = _page(rows, limit, scope, key=lambda r: (r[2], r[0]))
|
||
return [chat_out(r) for r in page], nxt
|
||
|
||
|
||
# ---------------------------------------------------------------- messages
|
||
MSG_COLS = "id, chat_id, sender_id, text, created_at"
|
||
# lab4: id вложений сообщения в порядке из запроса (пустой массив, если их нет).
|
||
MSG_ATTACHMENTS = (
|
||
"COALESCE((SELECT array_agg(ma.attachment_id ORDER BY ma.position) "
|
||
"FROM message_attachments ma WHERE ma.message_id = m.id), '{}'::uuid[])")
|
||
MSG_SELECT = f"SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at, {MSG_ATTACHMENTS} FROM messages m "
|
||
|
||
|
||
def message_out(row) -> dict:
|
||
return {"id": str(row[0]), "chat_id": str(row[1]), "sender_id": str(row[2]),
|
||
"text": row[3], "created_at": iso(row[4]),
|
||
"attachment_ids": [str(x) for x in row[5]]}
|
||
|
||
|
||
# ---------------------------------------------------------------- идемпотентность
|
||
class IdempotencyConflict(Exception):
|
||
"""Тот же Idempotency-Key, но другое тело запроса → 409."""
|
||
|
||
|
||
class AttachmentNotFound(Exception):
|
||
"""Вложения нет или оно из другого чата → 404."""
|
||
|
||
|
||
class AttachmentNotReady(Exception):
|
||
"""Вложение в состоянии failed → 409 (в lab4 статус всегда ready)."""
|
||
|
||
|
||
def request_hash(text: str, attachment_ids: list | None = None) -> bytes:
|
||
"""Хэш канонического тела: порядок ключей JSON не влияет на результат.
|
||
Отсутствующий attachment_ids и [] — одно и то же (контракт), поэтому пустой
|
||
список в хэш не входит: ключи, сохранённые lab3 для текстовых сообщений,
|
||
после обновления дают тот же хэш."""
|
||
body: dict = {"text": text}
|
||
if attachment_ids:
|
||
body["attachment_ids"] = [str(x) for x in attachment_ids]
|
||
canonical = json.dumps(body, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
|
||
return hashlib.sha256(canonical.encode("utf-8")).digest()
|
||
|
||
|
||
async def check_attachments(conn, chat_id, attachment_ids: list[uuid.UUID]) -> None:
|
||
"""Все вложения существуют и принадлежат ЭТОМУ чату; иначе 404 (не раскрываем,
|
||
что чужое вложение существует). FOR SHARE: строку нельзя удалить до COMMIT."""
|
||
if not attachment_ids:
|
||
return
|
||
cur = await conn.execute(
|
||
"SELECT id, chat_id, status FROM attachments WHERE id = ANY(%s) FOR SHARE",
|
||
(attachment_ids,))
|
||
found = {row[0]: row for row in await cur.fetchall()}
|
||
for aid in attachment_ids:
|
||
row = found.get(aid)
|
||
if row is None or str(row[1]) != str(chat_id):
|
||
raise AttachmentNotFound()
|
||
if any(row[2] == "failed" for row in found.values()):
|
||
raise AttachmentNotReady()
|
||
|
||
|
||
async def get_message(conn, message_id) -> dict:
|
||
cur = await conn.execute(MSG_SELECT + "WHERE m.id = %s", (message_id,))
|
||
return message_out(await cur.fetchone())
|
||
|
||
|
||
async def send_message_idempotent(conn, chat_id, sender_id, key: str, text: str,
|
||
ttl_seconds: int,
|
||
attachment_ids: list[uuid.UUID] | None = None) -> dict:
|
||
"""Записать сообщение ровно один раз для (пользователь, чат, ключ).
|
||
Вызывать внутри транзакции: ключ, сообщение и его связи с вложениями
|
||
фиксируются вместе или никак, поэтому ошибка (5xx) не оставляет «записанного результата».
|
||
|
||
Конкурентные повторы через разные реплики: второй INSERT того же PK ждёт
|
||
COMMIT первого (блокировка уникального индекса в PostgreSQL), затем получает
|
||
конфликт и читает уже сохранённый результат."""
|
||
attachment_ids = attachment_ids or []
|
||
rhash = request_hash(text, attachment_ids)
|
||
msg_id, created = uuid.uuid4(), now()
|
||
cur = await conn.execute(
|
||
"INSERT INTO idempotency_keys (user_id, chat_id, idem_key, request_hash, message_id, created_at) "
|
||
"VALUES (%s, %s, %s, %s, %s, %s) "
|
||
"ON CONFLICT (user_id, chat_id, idem_key) DO NOTHING RETURNING 1",
|
||
(sender_id, chat_id, key, rhash, msg_id, created))
|
||
if await cur.fetchone() is None:
|
||
cur = await conn.execute(
|
||
"SELECT request_hash, message_id, created_at < now() - make_interval(secs => %s) "
|
||
"FROM idempotency_keys WHERE user_id = %s AND chat_id = %s AND idem_key = %s FOR UPDATE",
|
||
(ttl_seconds, sender_id, chat_id, key))
|
||
stored_hash, stored_msg, expired = await cur.fetchone()
|
||
if not expired:
|
||
if bytes(stored_hash) != rhash:
|
||
raise IdempotencyConflict()
|
||
return await get_message(conn, stored_msg) # тот же Message, что и в первый раз
|
||
# Ключ старше TTL: используем его заново как новый.
|
||
await conn.execute(
|
||
"UPDATE idempotency_keys SET request_hash = %s, message_id = %s, created_at = %s "
|
||
"WHERE user_id = %s AND chat_id = %s AND idem_key = %s",
|
||
(rhash, msg_id, created, sender_id, chat_id, key))
|
||
# Вложения проверяются в той же транзакции, что и запись сообщения.
|
||
await check_attachments(conn, chat_id, attachment_ids)
|
||
await conn.execute(
|
||
f"INSERT INTO messages ({MSG_COLS}) VALUES (%s, %s, %s, %s, %s)",
|
||
(msg_id, chat_id, sender_id, text, created))
|
||
if attachment_ids:
|
||
async with conn.cursor() as c:
|
||
await c.executemany(
|
||
"INSERT INTO message_attachments (message_id, attachment_id, position) VALUES (%s, %s, %s)",
|
||
[(msg_id, aid, pos) for pos, aid in enumerate(attachment_ids)])
|
||
return {"id": str(msg_id), "chat_id": str(chat_id), "sender_id": str(sender_id),
|
||
"text": text, "created_at": iso(created),
|
||
"attachment_ids": [str(x) for x in attachment_ids]}
|
||
|
||
|
||
async def list_messages(conn, chat_id, limit: int, cursor: str | None):
|
||
"""Keyset-пагинация по индексу (chat_id, created_at, id): без OFFSET и без скана истории."""
|
||
scope = f"messages:{chat_id}"
|
||
params: list = [chat_id]
|
||
where = ""
|
||
if cursor:
|
||
c_at, c_id = decode_cursor(cursor, scope)
|
||
where = "AND (m.created_at, m.id) > (%s, %s) "
|
||
params += [c_at, c_id]
|
||
cur = await conn.execute(
|
||
MSG_SELECT + "WHERE m.chat_id = %s " + where
|
||
+ "ORDER BY m.created_at, m.id LIMIT %s", (*params, limit + 1))
|
||
rows = await cur.fetchall()
|
||
page, nxt = _page(rows, limit, scope, key=lambda r: (r[4], r[0]))
|
||
return [message_out(r) for r in page], nxt
|
||
|
||
|
||
# ---------------------------------------------------------------- вложения (lab4–5)
|
||
ATT_COLS = ("id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, "
|
||
"error_code, created_at, updated_at, object_key")
|
||
VARIANT_ORDER = ("thumbnail", "crop", "optimized")
|
||
|
||
|
||
def attachment_out(row, variants: list | None = None) -> dict:
|
||
"""Публичное представление: без object_key, staging, bucket и внутренних адресов.
|
||
size_bytes/sha256/content_type всегда описывают ОРИГИНАЛ; у вариантов — свои поля.
|
||
Варианты показываются только у ready (статус ставится после записи всех вариантов)."""
|
||
return {"id": str(row[0]), "chat_id": str(row[1]), "owner_id": str(row[2]),
|
||
"filename": row[3], "content_type": row[4], "size_bytes": row[5],
|
||
"sha256": row[6], "status": row[7],
|
||
"variants": (variants or []) if row[7] == "ready" else [],
|
||
"error_code": row[8] if row[7] == "failed" else None,
|
||
"created_at": iso(row[9]), "updated_at": iso(row[10])}
|
||
|
||
|
||
async def add_upload_intent(conn, object_key: str, attachment_id) -> None:
|
||
"""Журнал намерения: запись ДО PUT в S3 (staging). Если процесс упадёт между PUT и
|
||
COMMIT метаданных, по этой строке janitor найдёт и удалит объект-сироту."""
|
||
await conn.execute(
|
||
"INSERT INTO upload_intents (object_key, attachment_id, created_at) VALUES (%s, %s, now())",
|
||
(object_key, attachment_id))
|
||
|
||
|
||
class IntentLost(Exception):
|
||
"""Журнал загрузки уже забрал janitor (загрузка шла дольше grace period)."""
|
||
|
||
|
||
async def commit_attachment(conn, *, attachment_id, chat_id, owner_id, filename: str,
|
||
content_type: str, size_bytes: int, sha256: str,
|
||
width: int, height: int, object_key: str, staging_key: str,
|
||
pipeline_version: int, max_attempts: int) -> tuple[dict, int, dict]:
|
||
"""lab5. Вызывать внутри ОДНОЙ транзакции. Атомарно фиксирует:
|
||
- снятие журнала загрузки (staging-объект теперь «принадлежит» вложению),
|
||
- вложение status=queued,
|
||
- job (queued, attempt=1),
|
||
- строку outbox с сообщением для брокера (transactional outbox).
|
||
После COMMIT работа не теряется: оригинал в staging, намерение — в БД.
|
||
Возвращает (Attachment, id строки outbox, payload сообщения)."""
|
||
from .broker import make_payload # локальный импорт: repo не зависит от redis
|
||
cur = await conn.execute(
|
||
"DELETE FROM upload_intents WHERE object_key = %s RETURNING 1", (staging_key,))
|
||
if await cur.fetchone() is None:
|
||
raise IntentLost()
|
||
ts = now()
|
||
cur = await conn.execute(
|
||
f"INSERT INTO attachments ({ATT_COLS}, width, height, staging_key) "
|
||
"VALUES (%s, %s, %s, %s, %s, %s, %s, 'queued', NULL, %s, %s, %s, %s, %s, %s) "
|
||
f"RETURNING {ATT_COLS}",
|
||
(attachment_id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||
ts, ts, object_key, width, height, staging_key))
|
||
att = attachment_out(await cur.fetchone())
|
||
job_id = uuid.uuid4()
|
||
await conn.execute(
|
||
"INSERT INTO attachment_jobs (job_id, attachment_id, pipeline_version, status, attempt, "
|
||
"max_attempts, created_at, updated_at) VALUES (%s, %s, %s, 'queued', 1, %s, %s, %s)",
|
||
(job_id, attachment_id, pipeline_version, max_attempts, ts, ts))
|
||
payload = make_payload(job_id, attachment_id, pipeline_version, 1, ts)
|
||
cur = await conn.execute(
|
||
"INSERT INTO job_outbox (job_id, attempt, payload, available_at, created_at) "
|
||
"VALUES (%s, 1, %s, %s, %s) RETURNING id",
|
||
(job_id, json.dumps(payload), ts, ts))
|
||
outbox_id = (await cur.fetchone())[0]
|
||
await conn.execute(
|
||
"INSERT INTO job_events (job_id, event, attempt, actor) VALUES (%s, 'accepted', 1, 'api')",
|
||
(job_id,))
|
||
return att, outbox_id, payload
|
||
|
||
|
||
async def mark_published(conn, outbox_id: int, stream_id: str) -> None:
|
||
await conn.execute(
|
||
"UPDATE job_outbox SET published_at = now(), stream_id = %s, "
|
||
"publish_attempts = publish_attempts + 1 WHERE id = %s AND published_at IS NULL",
|
||
(stream_id, outbox_id))
|
||
|
||
|
||
async def get_variants(conn, attachment_id, pipeline_version: int) -> list[dict]:
|
||
cur = await conn.execute(
|
||
"SELECT variant, content_type, size_bytes, width, height, sha256 FROM attachment_variants "
|
||
"WHERE attachment_id = %s AND pipeline_version = %s", (attachment_id, pipeline_version))
|
||
rows = {r[0]: r for r in await cur.fetchall()}
|
||
return [{"name": r[0], "content_type": r[1], "size_bytes": r[2], "width": r[3],
|
||
"height": r[4], "sha256": r[5]} for name in VARIANT_ORDER if (r := rows.get(name))]
|
||
|
||
|
||
async def get_variant(conn, attachment_id, pipeline_version: int, name: str):
|
||
"""(object_key, content_type, size_bytes, sha256) или None."""
|
||
cur = await conn.execute(
|
||
"SELECT object_key, content_type, size_bytes, sha256 FROM attachment_variants "
|
||
"WHERE attachment_id = %s AND pipeline_version = %s AND variant = %s",
|
||
(attachment_id, pipeline_version, name))
|
||
return await cur.fetchone()
|
||
|
||
|
||
async def drop_upload_intent(conn, object_key: str) -> None:
|
||
await conn.execute("DELETE FROM upload_intents WHERE object_key = %s", (object_key,))
|
||
|
||
|
||
async def get_attachment_for_member(conn, attachment_id, user_id):
|
||
"""Строка вложения, если пользователь состоит в его чате; иначе None (→ 404)."""
|
||
cur = await conn.execute(
|
||
f"SELECT {ATT_COLS} FROM attachments a WHERE a.id = %s AND EXISTS "
|
||
"(SELECT 1 FROM chat_members x WHERE x.chat_id = a.chat_id AND x.user_id = %s)",
|
||
(attachment_id, user_id))
|
||
return await cur.fetchone()
|