Перенесла полный код из предыдущей лабораторной работы
This commit is contained in:
@@ -0,0 +1,203 @@
|
||||
import os
|
||||
from contextlib import contextmanager
|
||||
from typing import Iterator
|
||||
|
||||
import psycopg
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
|
||||
_pool: ConnectionPool | None = None
|
||||
|
||||
|
||||
def _dsn() -> str:
|
||||
dsn = os.environ.get("DATABASE_URL")
|
||||
if not dsn:
|
||||
raise RuntimeError("DATABASE_URL is not set")
|
||||
return dsn
|
||||
|
||||
|
||||
def init_pool() -> None:
|
||||
"""Ограниченный пул соединений с таймаутами. Вызывается один раз на старте."""
|
||||
global _pool
|
||||
if _pool is not None:
|
||||
return
|
||||
_pool = ConnectionPool(
|
||||
conninfo=_dsn(),
|
||||
min_size=2,
|
||||
max_size=10,
|
||||
timeout=5.0,
|
||||
max_idle=300.0,
|
||||
kwargs={"options": "-c statement_timeout=5000"},
|
||||
open=True,
|
||||
)
|
||||
|
||||
|
||||
def close_pool() -> None:
|
||||
global _pool
|
||||
if _pool is not None:
|
||||
_pool.close()
|
||||
_pool = None
|
||||
|
||||
|
||||
@contextmanager
|
||||
def connection() -> Iterator[psycopg.Connection]:
|
||||
"""Соединение из пула; autocommit=False для явных транзакций."""
|
||||
if _pool is None:
|
||||
init_pool()
|
||||
assert _pool is not None
|
||||
with _pool.connection() as conn:
|
||||
yield conn
|
||||
|
||||
|
||||
SCHEMA_SQL = """
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id UUID PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
display_name TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS chats (
|
||||
id UUID PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS chat_members (
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id UUID PRIMARY KEY,
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
text TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_chat_created
|
||||
ON messages (chat_id, created_at, id);
|
||||
|
||||
-- sessions остаются как fallback, если SESSION_STORE=postgres.
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token TEXT PRIMARY KEY,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
expires_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
|
||||
-- lab3: общая идемпотентность POST /messages.
|
||||
-- scope: user_id + method + path + key (см. contracts/README.md).
|
||||
-- body_hash — sha256 канонизированного JSON без attachment_ids=[], чтобы
|
||||
-- отличать повтор «того же» body (201, тот же Message) от «другого» (409).
|
||||
CREATE TABLE IF NOT EXISTS idempotency_keys (
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
method TEXT NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
body_hash TEXT NOT NULL,
|
||||
response_status INT NOT NULL,
|
||||
response_body JSONB NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (user_id, method, path, key)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_idempotency_created
|
||||
ON idempotency_keys (created_at);
|
||||
|
||||
-- lab4: вложения
|
||||
CREATE TABLE IF NOT EXISTS attachments (
|
||||
id UUID PRIMARY KEY,
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
owner_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
filename TEXT NOT NULL,
|
||||
content_type TEXT NOT NULL,
|
||||
size_bytes BIGINT NOT NULL,
|
||||
sha256 TEXT NOT NULL,
|
||||
object_key TEXT NOT NULL UNIQUE,
|
||||
status TEXT NOT NULL, -- queued/processing/ready/failed
|
||||
error_code TEXT,
|
||||
processing_until TIMESTAMPTZ, -- lease для worker (lab5)
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_attachments_chat
|
||||
ON attachments (chat_id);
|
||||
|
||||
-- связь сообщение↔вложение (порядок сохраняем)
|
||||
CREATE TABLE IF NOT EXISTS message_attachments (
|
||||
message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
|
||||
position INT NOT NULL,
|
||||
PRIMARY KEY (message_id, attachment_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_msg_att_message
|
||||
ON message_attachments (message_id, position);
|
||||
|
||||
-- lab5: варианты обработки (идемпотентность по (attachment_id, pipeline_version, variant))
|
||||
CREATE TABLE IF NOT EXISTS attachment_variants (
|
||||
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
|
||||
pipeline_version INT NOT NULL,
|
||||
variant TEXT NOT NULL,
|
||||
object_key TEXT NOT NULL,
|
||||
content_type TEXT NOT NULL,
|
||||
size_bytes BIGINT NOT NULL,
|
||||
width INT NOT NULL,
|
||||
height INT NOT NULL,
|
||||
sha256 TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (attachment_id, pipeline_version, variant)
|
||||
);
|
||||
|
||||
-- lab5 level 4: transactional outbox (разрыв COMMIT → publish)
|
||||
CREATE TABLE IF NOT EXISTS outbox (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
job_id UUID NOT NULL UNIQUE,
|
||||
payload JSONB NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
published_at TIMESTAMPTZ
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_outbox_unpublished
|
||||
ON outbox (id) WHERE published_at IS NULL;
|
||||
"""
|
||||
|
||||
|
||||
def init_schema() -> None:
|
||||
"""Идемпотентная миграция: безопасно вызывать многократно.
|
||||
|
||||
Вызывается ОДИН РАЗ отдельным one-shot сервисом migrate
|
||||
(см. compose.yaml). Реплики API миграции больше не выполняют:
|
||||
они ждут service_completed_successfully.
|
||||
"""
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(SCHEMA_SQL)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def run_migrations() -> None:
|
||||
"""Точка входа для one-shot migrate-контейнера.
|
||||
|
||||
Поднимает пул, применяет схему, закрывает пул. Завершается с кодом 0
|
||||
при успехе — этого достаточно для service_completed_successfully.
|
||||
"""
|
||||
init_pool()
|
||||
try:
|
||||
init_schema()
|
||||
finally:
|
||||
close_pool()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Запуск: python -m app.storage.db
|
||||
# (в compose.yaml — command: ["python", "-m", "app.storage.db"])
|
||||
import logging
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
)
|
||||
log = logging.getLogger("migrate")
|
||||
log.info("event=migrations_start")
|
||||
run_migrations()
|
||||
log.info("event=migrations_done")
|
||||
@@ -0,0 +1,177 @@
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
import threading
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Dict, List, Optional
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from ..models.schemas import Chat, Message, User
|
||||
|
||||
|
||||
def now_utc() -> datetime:
|
||||
"""Время сервера в UTC с суффиксом Z на выходе."""
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
# --- Password KDF (stdlib scrypt) ---
|
||||
_SCRYPT_N = 2 ** 14
|
||||
_SCRYPT_R = 8
|
||||
_SCRYPT_P = 1
|
||||
_SCRYPT_DKLEN = 32
|
||||
|
||||
|
||||
def _hash_password(password: str) -> str:
|
||||
salt = secrets.token_bytes(16)
|
||||
dk = hashlib.scrypt(
|
||||
password.encode("utf-8"),
|
||||
salt=salt,
|
||||
n=_SCRYPT_N,
|
||||
r=_SCRYPT_R,
|
||||
p=_SCRYPT_P,
|
||||
dklen=_SCRYPT_DKLEN,
|
||||
)
|
||||
return "scrypt$%d$%d$%d$%s$%s" % (
|
||||
_SCRYPT_N, _SCRYPT_R, _SCRYPT_P,
|
||||
salt.hex(), dk.hex(),
|
||||
)
|
||||
|
||||
|
||||
def _verify_password(password: str, stored: str) -> bool:
|
||||
try:
|
||||
scheme, n, r, p, salt_hex, dk_hex = stored.split("$")
|
||||
if scheme != "scrypt":
|
||||
return False
|
||||
dk = hashlib.scrypt(
|
||||
password.encode("utf-8"),
|
||||
salt=bytes.fromhex(salt_hex),
|
||||
n=int(n), r=int(r), p=int(p),
|
||||
dklen=len(bytes.fromhex(dk_hex)),
|
||||
)
|
||||
return hmac.compare_digest(dk.hex(), dk_hex)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
class MemoryStorage:
|
||||
"""Потокобезопасное In-memory хранилище пользователей, чатов, сообщений и сессий. Все данные исчезают при перезапуске процесса"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.RLock()
|
||||
self._users: Dict[UUID, User] = {}
|
||||
self._usernames: Dict[str, UUID] = {}
|
||||
self._passwords: Dict[UUID, str] = {}
|
||||
self._chats: Dict[UUID, Chat] = {}
|
||||
self._messages: Dict[UUID, List[Message]] = {}
|
||||
# token -> (user_id, expires_at)
|
||||
self._sessions: Dict[str, tuple] = {}
|
||||
|
||||
# ---------- Пользователи ----------
|
||||
def create_user(self, username: str, display_name: str, password: str) -> User:
|
||||
with self._lock:
|
||||
if username in self._usernames:
|
||||
raise ValueError("username_taken")
|
||||
user = User(
|
||||
id=uuid4(),
|
||||
username=username,
|
||||
display_name=display_name,
|
||||
created_at=now_utc(),
|
||||
)
|
||||
self._users[user.id] = user
|
||||
self._usernames[username] = user.id
|
||||
self._passwords[user.id] = _hash_password(password)
|
||||
return user
|
||||
|
||||
def get_user(self, user_id: UUID) -> Optional[User]:
|
||||
with self._lock:
|
||||
return self._users.get(user_id)
|
||||
|
||||
def get_user_by_username(self, username: str) -> Optional[User]:
|
||||
with self._lock:
|
||||
uid = self._usernames.get(username)
|
||||
return self._users.get(uid) if uid else None
|
||||
|
||||
def verify_credentials(self, username: str, password: str) -> Optional[User]:
|
||||
with self._lock:
|
||||
uid = self._usernames.get(username)
|
||||
if uid is None:
|
||||
return None
|
||||
stored = self._passwords.get(uid)
|
||||
if not stored or not _verify_password(password, stored):
|
||||
return None
|
||||
return self._users.get(uid)
|
||||
|
||||
# ---------- Сессии ----------
|
||||
def create_session(self, user_id: UUID, ttl_seconds: int) -> tuple:
|
||||
with self._lock:
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires_at = now_utc() + timedelta(seconds=ttl_seconds)
|
||||
self._sessions[token] = (user_id, expires_at)
|
||||
return token, expires_at
|
||||
|
||||
def get_session_user(self, token: str) -> Optional[User]:
|
||||
with self._lock:
|
||||
entry = self._sessions.get(token)
|
||||
if entry is None:
|
||||
return None
|
||||
user_id, expires_at = entry
|
||||
if expires_at <= now_utc():
|
||||
self._sessions.pop(token, None)
|
||||
return None
|
||||
return self._users.get(user_id)
|
||||
|
||||
def revoke_session(self, token: str) -> None:
|
||||
with self._lock:
|
||||
self._sessions.pop(token, None)
|
||||
|
||||
# ---------- Чаты ----------
|
||||
def create_chat(self, title: str, member_ids: List[UUID]) -> Chat:
|
||||
with self._lock:
|
||||
for uid in member_ids:
|
||||
if uid not in self._users:
|
||||
raise ValueError("unknown_member")
|
||||
chat = Chat(
|
||||
id=uuid4(),
|
||||
title=title,
|
||||
member_ids=list(member_ids),
|
||||
created_at=now_utc(),
|
||||
)
|
||||
self._chats[chat.id] = chat
|
||||
self._messages[chat.id] = []
|
||||
return chat
|
||||
|
||||
def get_chat(self, chat_id: UUID) -> Optional[Chat]:
|
||||
with self._lock:
|
||||
return self._chats.get(chat_id)
|
||||
|
||||
def list_chats_for_user(self, user_id: UUID) -> List[Chat]:
|
||||
with self._lock:
|
||||
chats = [c for c in self._chats.values() if user_id in c.member_ids]
|
||||
chats.sort(key=lambda c: (c.created_at, str(c.id)))
|
||||
return chats
|
||||
|
||||
# ---------- Сообщения ----------
|
||||
def add_message(self, chat_id: UUID, sender_id: UUID, text: str) -> Message:
|
||||
"""Улучшение Трека 1: список сообщений хранится уже отсортированным.
|
||||
created_at монотонен в пределах одного процесса, поэтому append
|
||||
сохраняет порядок (created_at, id) по возрастанию — сортировка на
|
||||
чтении не нужна. При конкурентных вставках под RLock порядок
|
||||
сохраняется, но монотонность часов не гарантируется контрактом."""
|
||||
with self._lock:
|
||||
message = Message(
|
||||
id=uuid4(),
|
||||
chat_id=chat_id,
|
||||
sender_id=sender_id,
|
||||
text=text,
|
||||
created_at=now_utc(),
|
||||
)
|
||||
self._messages.setdefault(chat_id, []).append(message)
|
||||
return message
|
||||
|
||||
def list_messages(self, chat_id: UUID) -> List[Message]:
|
||||
with self._lock:
|
||||
# Без пересортировки: список уже в порядке (created_at, id).
|
||||
return list(self._messages.get(chat_id, []))
|
||||
|
||||
|
||||
storage = MemoryStorage() # единственный экземпляр хранилища на процесс
|
||||
@@ -0,0 +1,614 @@
|
||||
import hashlib
|
||||
import hmac
|
||||
import json as _json
|
||||
import secrets
|
||||
import threading
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import List, Optional
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from ..models.schemas import Attachment, Chat, Message, User, Variant
|
||||
from .db import connection
|
||||
from .sessions import (
|
||||
create_session as _sess_create,
|
||||
get_session_user as _sess_get,
|
||||
revoke_session as _sess_revoke,
|
||||
)
|
||||
|
||||
|
||||
def now_utc() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
# --- Password KDF (stdlib scrypt) ---
|
||||
_SCRYPT_N = 2 ** 14
|
||||
_SCRYPT_R = 8
|
||||
_SCRYPT_P = 1
|
||||
_SCRYPT_DKLEN = 32
|
||||
|
||||
|
||||
def _hash_password(password: str) -> str:
|
||||
salt = secrets.token_bytes(16)
|
||||
dk = hashlib.scrypt(
|
||||
password.encode("utf-8"),
|
||||
salt=salt,
|
||||
n=_SCRYPT_N, r=_SCRYPT_R, p=_SCRYPT_P, dklen=_SCRYPT_DKLEN,
|
||||
)
|
||||
return "scrypt$%d$%d$%d$%s$%s" % (
|
||||
_SCRYPT_N, _SCRYPT_R, _SCRYPT_P, salt.hex(), dk.hex(),
|
||||
)
|
||||
|
||||
|
||||
def _verify_password(password: str, stored: str) -> bool:
|
||||
try:
|
||||
scheme, n, r, p, salt_hex, dk_hex = stored.split("$")
|
||||
if scheme != "scrypt":
|
||||
return False
|
||||
dk = hashlib.scrypt(
|
||||
password.encode("utf-8"),
|
||||
salt=bytes.fromhex(salt_hex),
|
||||
n=int(n), r=int(r), p=int(p),
|
||||
dklen=len(bytes.fromhex(dk_hex)),
|
||||
)
|
||||
return hmac.compare_digest(dk.hex(), dk_hex)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _row_to_user(row) -> User:
|
||||
return User(id=row[0], username=row[1], display_name=row[2], created_at=row[3])
|
||||
|
||||
|
||||
def _row_to_chat(row, member_ids: List[UUID]) -> Chat:
|
||||
return Chat(id=row[0], title=row[1], member_ids=member_ids, created_at=row[2])
|
||||
|
||||
|
||||
def _row_to_message(row, attachment_ids: List[UUID]) -> Message:
|
||||
return Message(
|
||||
id=row[0], chat_id=row[1], sender_id=row[2],
|
||||
text=row[3], created_at=row[4],
|
||||
attachment_ids=attachment_ids,
|
||||
)
|
||||
|
||||
|
||||
def _row_to_attachment(row, variants: Optional[list] = None) -> Attachment:
|
||||
# row: id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
# status, error_code, created_at, updated_at
|
||||
return Attachment(
|
||||
id=row[0], chat_id=row[1], owner_id=row[2],
|
||||
filename=row[3], content_type=row[4], size_bytes=row[5],
|
||||
sha256=row[6], status=row[7], variants=variants or [],
|
||||
error_code=row[8],
|
||||
created_at=row[9], updated_at=row[10],
|
||||
)
|
||||
|
||||
|
||||
class PostgresStorage:
|
||||
"""Потокобезопасная обёртка; параллелизм обеспечивает PostgreSQL."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.RLock()
|
||||
|
||||
# ---------- Пользователи ----------
|
||||
def create_user(self, username: str, display_name: str, password: str) -> User:
|
||||
with self._lock, connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT 1 FROM users WHERE username = %s", (username,))
|
||||
if cur.fetchone() is not None:
|
||||
raise ValueError("username_taken")
|
||||
user = User(
|
||||
id=uuid4(), username=username,
|
||||
display_name=display_name, created_at=now_utc(),
|
||||
)
|
||||
try:
|
||||
cur.execute(
|
||||
"INSERT INTO users (id, username, display_name, password_hash, created_at)"
|
||||
" VALUES (%s, %s, %s, %s, %s)",
|
||||
(user.id, user.username, user.display_name,
|
||||
_hash_password(password), user.created_at),
|
||||
)
|
||||
except Exception as exc:
|
||||
if exc.__class__.__name__ == "UniqueViolation":
|
||||
raise ValueError("username_taken")
|
||||
raise
|
||||
conn.commit()
|
||||
return user
|
||||
|
||||
def get_user(self, user_id: UUID) -> Optional[User]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
|
||||
(user_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _row_to_user(row) if row else None
|
||||
|
||||
def get_user_by_username(self, username: str) -> Optional[User]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, username, display_name, created_at FROM users WHERE username = %s",
|
||||
(username,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _row_to_user(row) if row else None
|
||||
|
||||
def verify_credentials(self, username: str, password: str) -> Optional[User]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, username, display_name, created_at, password_hash"
|
||||
" FROM users WHERE username = %s",
|
||||
(username,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
if not _verify_password(password, row[4]):
|
||||
return None
|
||||
return _row_to_user(row[:4])
|
||||
|
||||
# ---------- Сессии ----------
|
||||
def create_session(self, user_id: UUID, ttl_seconds: int) -> tuple:
|
||||
return _sess_create(user_id, ttl_seconds)
|
||||
|
||||
def get_session_user(self, token: str) -> Optional[User]:
|
||||
return _sess_get(token)
|
||||
|
||||
def revoke_session(self, token: str) -> None:
|
||||
_sess_revoke(token)
|
||||
|
||||
# ---------- Чаты ----------
|
||||
def create_chat(self, title: str, member_ids: List[UUID]) -> Chat:
|
||||
with self._lock, connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
# проверяем всех участников
|
||||
cur.execute(
|
||||
"SELECT id FROM users WHERE id = ANY(%s)",
|
||||
(list(member_ids),),
|
||||
)
|
||||
found = {r[0] for r in cur.fetchall()}
|
||||
if len(found) != len(set(member_ids)):
|
||||
raise ValueError("unknown_member")
|
||||
chat = Chat(
|
||||
id=uuid4(), title=title,
|
||||
member_ids=list(member_ids), created_at=now_utc(),
|
||||
)
|
||||
cur.execute(
|
||||
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)",
|
||||
(chat.id, chat.title, chat.created_at),
|
||||
)
|
||||
cur.executemany(
|
||||
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
|
||||
[(chat.id, uid) for uid in member_ids],
|
||||
)
|
||||
conn.commit()
|
||||
return chat
|
||||
|
||||
def get_chat(self, chat_id: UUID) -> Optional[Chat]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, title, created_at FROM chats WHERE id = %s",
|
||||
(chat_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
cur.execute(
|
||||
"SELECT user_id FROM chat_members WHERE chat_id = %s", (chat_id,),
|
||||
)
|
||||
members = [r[0] for r in cur.fetchall()]
|
||||
return _row_to_chat(row, members)
|
||||
|
||||
def list_chats_for_user(self, user_id: UUID) -> List[Chat]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT c.id, c.title, c.created_at FROM chats c"
|
||||
" JOIN chat_members m ON m.chat_id = c.id"
|
||||
" WHERE m.user_id = %s ORDER BY c.created_at, c.id",
|
||||
(user_id,),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
chats = []
|
||||
for row in rows:
|
||||
cur.execute(
|
||||
"SELECT user_id FROM chat_members WHERE chat_id = %s", (row[0],),
|
||||
)
|
||||
members = [r[0] for r in cur.fetchall()]
|
||||
chats.append(_row_to_chat(row, members))
|
||||
return chats
|
||||
|
||||
# ---------- Сообщения ----------
|
||||
def _load_message_attachments(self, cur, message_ids: List[UUID]) -> dict[UUID, List[UUID]]:
|
||||
if not message_ids:
|
||||
return {}
|
||||
cur.execute(
|
||||
"SELECT message_id, attachment_id, position FROM message_attachments"
|
||||
" WHERE message_id = ANY(%s) ORDER BY message_id, position",
|
||||
(list(message_ids),),
|
||||
)
|
||||
result: dict[UUID, List[UUID]] = {}
|
||||
for mid, aid, _pos in cur.fetchall():
|
||||
result.setdefault(mid, []).append(aid)
|
||||
return result
|
||||
|
||||
def list_messages_page(
|
||||
self, chat_id: UUID, limit: int, after: Optional[tuple] = None,
|
||||
) -> List[Message]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
if after is None:
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, sender_id, text, created_at FROM messages"
|
||||
" WHERE chat_id = %s ORDER BY created_at, id LIMIT %s",
|
||||
(chat_id, limit),
|
||||
)
|
||||
else:
|
||||
after_ts, after_id = after
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, sender_id, text, created_at FROM messages"
|
||||
" WHERE chat_id = %s AND (created_at, id) > (%s, %s)"
|
||||
" ORDER BY created_at, id LIMIT %s",
|
||||
(chat_id, after_ts, after_id, limit),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
ids = [r[0] for r in rows]
|
||||
att_map = self._load_message_attachments(cur, ids)
|
||||
return [_row_to_message(r, att_map.get(r[0], [])) for r in rows]
|
||||
|
||||
# ---------- Идемпотентность (lab3) ----------
|
||||
def add_message_idempotent(
|
||||
self,
|
||||
chat_id: UUID,
|
||||
sender_id: UUID,
|
||||
text: str,
|
||||
attachment_ids: List[UUID],
|
||||
user_id: UUID,
|
||||
method: str,
|
||||
path: str,
|
||||
key: str,
|
||||
body_hash: str,
|
||||
) -> tuple[str, Optional[Message], Optional[dict]]:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO idempotency_keys"
|
||||
" (user_id, method, path, key, body_hash, response_status, response_body)"
|
||||
" VALUES (%s, %s, %s, %s, %s, 0, '{}'::jsonb)"
|
||||
" ON CONFLICT (user_id, method, path, key) DO NOTHING"
|
||||
" RETURNING key",
|
||||
(user_id, method, path, key, body_hash),
|
||||
)
|
||||
won = cur.fetchone() is not None
|
||||
|
||||
if won:
|
||||
message = Message(
|
||||
id=uuid4(), chat_id=chat_id, sender_id=sender_id,
|
||||
text=text, created_at=now_utc(),
|
||||
attachment_ids=list(attachment_ids),
|
||||
)
|
||||
cur.execute(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text, created_at)"
|
||||
" VALUES (%s, %s, %s, %s, %s)",
|
||||
(message.id, message.chat_id, message.sender_id,
|
||||
message.text, message.created_at),
|
||||
)
|
||||
if attachment_ids:
|
||||
cur.executemany(
|
||||
"INSERT INTO message_attachments"
|
||||
" (message_id, attachment_id, position)"
|
||||
" VALUES (%s, %s, %s)",
|
||||
[(message.id, aid, idx)
|
||||
for idx, aid in enumerate(attachment_ids)],
|
||||
)
|
||||
body_json = _json.loads(message.model_dump_json())
|
||||
cur.execute(
|
||||
"UPDATE idempotency_keys"
|
||||
" SET response_status = %s, response_body = %s"
|
||||
" WHERE user_id = %s AND method = %s AND path = %s AND key = %s",
|
||||
(201, _json.dumps(body_json),
|
||||
user_id, method, path, key),
|
||||
)
|
||||
conn.commit()
|
||||
return ("created", message, None)
|
||||
|
||||
cur.execute(
|
||||
"SELECT body_hash, response_status, response_body"
|
||||
" FROM idempotency_keys"
|
||||
" WHERE user_id = %s AND method = %s AND path = %s AND key = %s",
|
||||
(user_id, method, path, key),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
|
||||
if row is None:
|
||||
return ("retry", None, None)
|
||||
return (
|
||||
"replay",
|
||||
None,
|
||||
{
|
||||
"body_hash": row[0],
|
||||
"response_status": row[1],
|
||||
"response_body": row[2],
|
||||
},
|
||||
)
|
||||
|
||||
# ---------- Вложения ----------
|
||||
def create_attachment(self, attachment: Attachment, object_key: str) -> Attachment:
|
||||
"""lab4 fallback (синхронный ready). Не используется в lab5."""
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO attachments"
|
||||
" (id, chat_id, owner_id, filename, content_type, size_bytes,"
|
||||
" sha256, object_key, status, error_code, created_at, updated_at)"
|
||||
" VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||
(
|
||||
attachment.id, attachment.chat_id, attachment.owner_id,
|
||||
attachment.filename, attachment.content_type,
|
||||
attachment.size_bytes, attachment.sha256, object_key,
|
||||
attachment.status, attachment.error_code,
|
||||
attachment.created_at, attachment.updated_at,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
return attachment
|
||||
|
||||
def create_attachment_queued(
|
||||
self,
|
||||
attachment: Attachment,
|
||||
staging_key: str,
|
||||
outbox_payload: dict,
|
||||
) -> Attachment:
|
||||
"""lab5: attachment в queued + строка outbox в ОДНОЙ транзакции."""
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO attachments"
|
||||
" (id, chat_id, owner_id, filename, content_type, size_bytes,"
|
||||
" sha256, object_key, status, error_code, processing_until,"
|
||||
" created_at, updated_at)"
|
||||
" VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||
(
|
||||
attachment.id, attachment.chat_id, attachment.owner_id,
|
||||
attachment.filename, attachment.content_type,
|
||||
attachment.size_bytes, attachment.sha256, staging_key,
|
||||
"queued", None, None,
|
||||
attachment.created_at, attachment.updated_at,
|
||||
),
|
||||
)
|
||||
cur.execute(
|
||||
"INSERT INTO outbox (job_id, payload) VALUES (%s, %s)",
|
||||
(outbox_payload["job_id"], _json.dumps(outbox_payload)),
|
||||
)
|
||||
conn.commit()
|
||||
return attachment
|
||||
|
||||
def claim_processing(self, attachment_id: UUID, lease_seconds: int = 60) -> bool:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
now = now_utc()
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='processing',"
|
||||
" processing_until=%s, updated_at=%s"
|
||||
" WHERE id=%s AND status IN ('queued','processing')"
|
||||
" RETURNING id",
|
||||
(now + timedelta(seconds=lease_seconds), now, attachment_id),
|
||||
)
|
||||
won = cur.fetchone() is not None
|
||||
conn.commit()
|
||||
return won
|
||||
|
||||
def recover_stuck_processing(self) -> int:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
now = now_utc()
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='queued', processing_until=NULL,"
|
||||
" updated_at=%s"
|
||||
" WHERE status='processing' AND processing_until IS NOT NULL"
|
||||
" AND processing_until < %s",
|
||||
(now, now),
|
||||
)
|
||||
count = cur.rowcount
|
||||
conn.commit()
|
||||
return count
|
||||
|
||||
def replay_failed_to_queued(self, attachment_id: UUID) -> str:
|
||||
"""Операторский replay: failed → queued с новой записью в outbox.
|
||||
|
||||
Возвращает:
|
||||
- "requeued" — статус был failed, переведён в queued и запланирован job;
|
||||
- "already" — запись уже queued/processing/ready (защита готовых), ничего не меняем;
|
||||
- "missing" — такого вложения нет.
|
||||
|
||||
Ключ эффекта (attachment_id, pipeline_version, variant) и ON CONFLICT
|
||||
в finalize_ready гарантируют, что повтор не создаст дублей вариантов.
|
||||
Новый job_id и строка outbox публикуются отдельным процессом outbox,
|
||||
поэтому разрыв между COMMIT и publish закрыт тем же механизмом, что и при upload.
|
||||
"""
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT status FROM attachments WHERE id = %s FOR UPDATE",
|
||||
(attachment_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
conn.rollback()
|
||||
return "missing"
|
||||
status = row[0]
|
||||
if status != "failed":
|
||||
conn.rollback()
|
||||
return "already"
|
||||
|
||||
now = now_utc()
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='queued', error_code=NULL,"
|
||||
" processing_until=NULL, updated_at=%s WHERE id=%s",
|
||||
(now, attachment_id),
|
||||
)
|
||||
|
||||
job_id = uuid4()
|
||||
payload = {
|
||||
"job_id": str(job_id),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(attachment_id),
|
||||
"pipeline_version": 1,
|
||||
"created_at": now.isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
cur.execute(
|
||||
"INSERT INTO outbox (job_id, payload) VALUES (%s, %s)",
|
||||
(job_id, _json.dumps(payload)),
|
||||
)
|
||||
conn.commit()
|
||||
return "requeued"
|
||||
|
||||
def finalize_ready(
|
||||
self,
|
||||
attachment_id: UUID,
|
||||
pipeline_version: int,
|
||||
variants: list[dict],
|
||||
) -> None:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
original = next(v for v in variants if v["name"] == "original")
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='ready', error_code=NULL,"
|
||||
" object_key=%s, processing_until=NULL, updated_at=%s"
|
||||
" WHERE id=%s",
|
||||
(original["object_key"], now_utc(), attachment_id),
|
||||
)
|
||||
for v in variants:
|
||||
if v["name"] == "original":
|
||||
continue
|
||||
cur.execute(
|
||||
"INSERT INTO attachment_variants"
|
||||
" (attachment_id, pipeline_version, variant, object_key,"
|
||||
" content_type, size_bytes, width, height, sha256)"
|
||||
" VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)"
|
||||
" ON CONFLICT (attachment_id, pipeline_version, variant)"
|
||||
" DO NOTHING",
|
||||
(
|
||||
attachment_id, pipeline_version, v["name"],
|
||||
v["object_key"], v["content_type"],
|
||||
v["size_bytes"], v["width"], v["height"], v["sha256"],
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
def finalize_failed(self, attachment_id: UUID, error_code: str) -> None:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='failed', error_code=%s,"
|
||||
" processing_until=NULL, updated_at=%s WHERE id=%s",
|
||||
(error_code, now_utc(), attachment_id),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
def get_attachment(self, attachment_id: UUID) -> Optional[Attachment]:
|
||||
pair = self.get_attachment_with_key(attachment_id)
|
||||
return pair[0] if pair else None
|
||||
|
||||
def get_attachment_with_key(
|
||||
self, attachment_id: UUID
|
||||
) -> Optional[tuple[Attachment, str]]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, owner_id, filename, content_type, size_bytes,"
|
||||
" sha256, status, error_code, created_at, updated_at, object_key"
|
||||
" FROM attachments WHERE id = %s",
|
||||
(attachment_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
att = _row_to_attachment(row[:11], self.get_attachment_variants(attachment_id))
|
||||
return att, row[11]
|
||||
|
||||
def list_attachments_by_ids(
|
||||
self, ids: List[UUID], chat_id: UUID
|
||||
) -> dict[UUID, tuple[Attachment, str]]:
|
||||
if not ids:
|
||||
return {}
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, owner_id, filename, content_type, size_bytes,"
|
||||
" sha256, status, error_code, created_at, updated_at, object_key"
|
||||
" FROM attachments WHERE chat_id = %s AND id = ANY(%s)",
|
||||
(chat_id, list(ids)),
|
||||
)
|
||||
result: dict[UUID, tuple[Attachment, str]] = {}
|
||||
for row in cur.fetchall():
|
||||
att = _row_to_attachment(row[:11])
|
||||
result[row[0]] = (att, row[11])
|
||||
return result
|
||||
|
||||
def delete_attachment(self, attachment_id: UUID) -> None:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute("DELETE FROM attachments WHERE id = %s", (attachment_id,))
|
||||
conn.commit()
|
||||
|
||||
def get_attachment_variants(self, attachment_id: UUID) -> list[dict]:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT variant, content_type, size_bytes, width, height, sha256"
|
||||
" FROM attachment_variants WHERE attachment_id=%s"
|
||||
" ORDER BY variant",
|
||||
(attachment_id,),
|
||||
)
|
||||
return [
|
||||
{
|
||||
"name": r[0], "content_type": r[1], "size_bytes": r[2],
|
||||
"width": r[3], "height": r[4], "sha256": r[5],
|
||||
}
|
||||
for r in cur.fetchall()
|
||||
]
|
||||
|
||||
def get_staging_key(self, attachment_id: UUID) -> Optional[str]:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT object_key FROM attachments WHERE id=%s",
|
||||
(attachment_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return row[0] if row else None
|
||||
|
||||
# ---------- Outbox (lab5 level 4) ----------
|
||||
def list_unpublished_outbox(self, limit: int = 100) -> list[tuple[int, dict]]:
|
||||
"""Возвращает [(outbox_id, payload_dict), ...].
|
||||
|
||||
Всегда dict; если payload в БД пришёл строкой (например, из старой
|
||||
версии), распаковываем через json.loads.
|
||||
"""
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, payload FROM outbox WHERE published_at IS NULL"
|
||||
" ORDER BY id LIMIT %s",
|
||||
(limit,),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
result: list[tuple[int, dict]] = []
|
||||
for r in rows:
|
||||
raw = r[1]
|
||||
if isinstance(raw, dict):
|
||||
payload = raw
|
||||
else:
|
||||
payload = _json.loads(raw)
|
||||
if not isinstance(payload, dict):
|
||||
# защита от мусора — пропустить
|
||||
continue
|
||||
result.append((int(r[0]), payload))
|
||||
return result
|
||||
|
||||
def mark_outbox_published(self, outbox_id: int) -> None:
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"UPDATE outbox SET published_at=now() WHERE id=%s",
|
||||
(outbox_id,),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
storage = PostgresStorage() # единственный экземпляр на процесс
|
||||
@@ -0,0 +1,156 @@
|
||||
"""RabbitMQ: topology, publisher with confirms, consumer с manual ack.
|
||||
|
||||
- Основная очередь: durable quorum queue.
|
||||
- Retry: TTL-очереди с dead-letter обратно в основную; x-retry-count.
|
||||
- DLQ: финальные ошибки и исчерпанные retry.
|
||||
- Publisher confirms: publish() ждёт подтверждения брокера.
|
||||
|
||||
ВАЖНО: setup_topology вызывается в worker при старте и в outbox
|
||||
однократно при первом publish. Не декларируем топологию на каждый
|
||||
publish — иначе гонка с параллельными декларациями.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
from typing import Optional
|
||||
|
||||
import pika
|
||||
|
||||
log = logging.getLogger("rabbit")
|
||||
|
||||
EXCHANGE = "messenger.attachments"
|
||||
QUEUE = "attachment.process.v1"
|
||||
RETRY_EXCHANGE = "messenger.attachments.retry"
|
||||
DLX = "messenger.attachments.dlx"
|
||||
DLQ = "attachment.process.v1.dlq"
|
||||
|
||||
RETRY_DELAYS = [5, 15, 60]
|
||||
MAX_ATTEMPTS = len(RETRY_DELAYS) + 1
|
||||
|
||||
_topology_ready = False
|
||||
_topology_lock = threading.Lock()
|
||||
|
||||
|
||||
def _url() -> str:
|
||||
return os.environ.get("RABBITMQ_URL", "amqp://guest:guest@rabbitmq:5672/%2F")
|
||||
|
||||
|
||||
def connection_params() -> pika.ConnectionParameters:
|
||||
return pika.URLParameters(_url())
|
||||
|
||||
|
||||
def connect() -> pika.BlockingConnection:
|
||||
return pika.BlockingConnection(connection_params())
|
||||
|
||||
|
||||
def setup_topology(channel: pika.adapters.blocking_connection.BlockingChannel) -> None:
|
||||
channel.exchange_declare(EXCHANGE, exchange_type="direct", durable=True)
|
||||
channel.exchange_declare(RETRY_EXCHANGE, exchange_type="direct", durable=True)
|
||||
channel.exchange_declare(DLX, exchange_type="direct", durable=True)
|
||||
|
||||
channel.queue_declare(DLQ, durable=True, arguments={"x-queue-type": "quorum"})
|
||||
channel.queue_bind(DLQ, DLX, routing_key=DLQ)
|
||||
|
||||
channel.queue_declare(
|
||||
QUEUE,
|
||||
durable=True,
|
||||
arguments={
|
||||
"x-queue-type": "quorum",
|
||||
"x-dead-letter-exchange": DLX,
|
||||
"x-dead-letter-routing-key": DLQ,
|
||||
},
|
||||
)
|
||||
channel.queue_bind(QUEUE, EXCHANGE, routing_key=QUEUE)
|
||||
|
||||
for delay in RETRY_DELAYS:
|
||||
qname = f"attachment.retry.{delay}s"
|
||||
channel.queue_declare(
|
||||
qname,
|
||||
durable=True,
|
||||
arguments={
|
||||
"x-message-ttl": delay * 1000,
|
||||
"x-dead-letter-exchange": EXCHANGE,
|
||||
"x-dead-letter-routing-key": QUEUE,
|
||||
},
|
||||
)
|
||||
channel.queue_bind(qname, RETRY_EXCHANGE, routing_key=qname)
|
||||
|
||||
|
||||
def _ensure_topology(ch: pika.adapters.blocking_connection.BlockingChannel) -> None:
|
||||
global _topology_ready
|
||||
if _topology_ready:
|
||||
return
|
||||
with _topology_lock:
|
||||
if _topology_ready:
|
||||
return
|
||||
setup_topology(ch)
|
||||
_topology_ready = True
|
||||
|
||||
|
||||
def publish_job(payload: dict) -> None:
|
||||
"""Публикация job с publisher confirm. Бросает при неудаче."""
|
||||
conn = connect()
|
||||
try:
|
||||
ch = conn.channel()
|
||||
ch.confirm_delivery()
|
||||
_ensure_topology(ch)
|
||||
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
||||
ch.basic_publish(
|
||||
exchange=EXCHANGE,
|
||||
routing_key=QUEUE,
|
||||
body=body.encode("utf-8"),
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2,
|
||||
content_type="application/json",
|
||||
),
|
||||
mandatory=True,
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def publish_retry(payload: dict, retry_count: int) -> None:
|
||||
idx = min(retry_count - 1, len(RETRY_DELAYS) - 1)
|
||||
delay = RETRY_DELAYS[idx]
|
||||
qname = f"attachment.retry.{delay}s"
|
||||
conn = connect()
|
||||
try:
|
||||
ch = conn.channel()
|
||||
ch.confirm_delivery()
|
||||
_ensure_topology(ch)
|
||||
headers = dict(payload.get("_headers") or {})
|
||||
headers["x-retry-count"] = retry_count
|
||||
clean = {k: v for k, v in payload.items() if k != "_headers"}
|
||||
body = json.dumps(clean, ensure_ascii=False, separators=(",", ":"))
|
||||
ch.basic_publish(
|
||||
exchange=RETRY_EXCHANGE,
|
||||
routing_key=qname,
|
||||
body=body.encode("utf-8"),
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2,
|
||||
content_type="application/json",
|
||||
headers=headers,
|
||||
),
|
||||
mandatory=True,
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def publish_dlq(payload: dict) -> None:
|
||||
conn = connect()
|
||||
try:
|
||||
ch = conn.channel()
|
||||
ch.confirm_delivery()
|
||||
_ensure_topology(ch)
|
||||
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
||||
ch.basic_publish(
|
||||
exchange=DLX,
|
||||
routing_key=DLQ,
|
||||
body=body.encode("utf-8"),
|
||||
properties=pika.BasicProperties(delivery_mode=2, content_type="application/json"),
|
||||
mandatory=True,
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Операторский replay failed-задач: failed → queued + запись в outbox.
|
||||
|
||||
Использование:
|
||||
python -m app.storage.replay_failed <attachment_id> [<attachment_id> ...]
|
||||
python -m app.storage.replay_failed --all-failed
|
||||
|
||||
Защита:
|
||||
- переводит ТОЛЬКО failed; queued/processing/ready не трогает (возвращает "already");
|
||||
- новая строка outbox с новым job_id — публикация через существующий outbox-процесс;
|
||||
- идемпотентность эффекта по (attachment_id, pipeline_version, variant)
|
||||
не даёт создать дубли вариантов, если повторная обработка уже была выполнена.
|
||||
Логи пишутся только с ID и статусом, без секретов и содержимого файлов.
|
||||
"""
|
||||
import logging
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
from .db import init_pool, close_pool
|
||||
from .postgres import storage
|
||||
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
stream=sys.stdout,
|
||||
)
|
||||
log = logging.getLogger("replay_failed")
|
||||
|
||||
|
||||
def _parse_args(argv):
|
||||
if not argv:
|
||||
print(
|
||||
"usage: python -m app.storage.replay_failed <attachment_id> [...] | --all-failed",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return None
|
||||
if argv == ["--all-failed"]:
|
||||
return "all"
|
||||
ids = []
|
||||
for raw in argv:
|
||||
try:
|
||||
ids.append(uuid.UUID(raw))
|
||||
except ValueError:
|
||||
print("invalid attachment_id: %r" % raw, file=sys.stderr)
|
||||
return None
|
||||
return ids
|
||||
|
||||
|
||||
def _list_failed_ids() -> list:
|
||||
from .db import connection
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT id FROM attachments WHERE status='failed' ORDER BY updated_at")
|
||||
return [r[0] for r in cur.fetchall()]
|
||||
|
||||
|
||||
def main(argv) -> int:
|
||||
parsed = _parse_args(argv)
|
||||
if parsed is None:
|
||||
return 2
|
||||
init_pool()
|
||||
try:
|
||||
if parsed == "all":
|
||||
ids = _list_failed_ids()
|
||||
else:
|
||||
ids = parsed
|
||||
requeued = already = missing = 0
|
||||
for aid in ids:
|
||||
result = storage.replay_failed_to_queued(aid)
|
||||
if result == "requeued":
|
||||
requeued += 1
|
||||
log.info("event=replay_requeued attachment_id=%s", aid)
|
||||
elif result == "already":
|
||||
already += 1
|
||||
log.info("event=replay_skipped_not_failed attachment_id=%s", aid)
|
||||
else:
|
||||
missing += 1
|
||||
log.info("event=replay_missing attachment_id=%s", aid)
|
||||
log.info(
|
||||
"event=replay_done requested=%d requeued=%d skipped=%d missing=%d",
|
||||
len(ids), requeued, already, missing,
|
||||
)
|
||||
return 0 if missing == 0 else 1
|
||||
finally:
|
||||
close_pool()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,98 @@
|
||||
"""S3-клиент (MinIO) для lab4/lab5.
|
||||
|
||||
Object key генерирует сервер:
|
||||
staging: staging/<chat_id>/<attachment_id>/original
|
||||
final: attachments/<chat_id>/<attachment_id>/original
|
||||
variant: attachments/<chat_id>/<attachment_id>/<variant>
|
||||
filename используется только для отображения, не в ключе.
|
||||
"""
|
||||
import os
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
|
||||
import boto3
|
||||
from botocore.client import Config
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
|
||||
def _endpoint() -> str:
|
||||
return os.environ["S3_ENDPOINT"]
|
||||
|
||||
|
||||
def _bucket() -> str:
|
||||
return os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
|
||||
|
||||
def client():
|
||||
"""Клиент с прикладными credentials (не admin).
|
||||
|
||||
Явные короткие таймауты: connect/read — чтобы при недоступности S3
|
||||
запросы падали быстро и LB отдавал 503, а не 504 по своему timeout.
|
||||
"""
|
||||
return boto3.client(
|
||||
"s3",
|
||||
endpoint_url=_endpoint(),
|
||||
region_name=os.environ.get("S3_REGION", "us-east-1"),
|
||||
aws_access_key_id=os.environ["S3_APP_KEY_ID"],
|
||||
aws_secret_access_key=os.environ["S3_APP_SECRET_KEY"],
|
||||
config=Config(
|
||||
signature_version="s3v4",
|
||||
s3={"addressing_style": "path"},
|
||||
connect_timeout=2,
|
||||
read_timeout=3,
|
||||
retries={"max_attempts": 0},
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def staging_key(chat_id: UUID, attachment_id: UUID) -> str:
|
||||
"""Staging — приватный prefix, worker читает отсюда."""
|
||||
return "staging/%s/%s/original" % (chat_id, attachment_id)
|
||||
|
||||
|
||||
def original_key(chat_id: UUID, attachment_id: UUID) -> str:
|
||||
"""Финальный ключ оригинала. Не зависит от filename."""
|
||||
return "attachments/%s/%s/original" % (chat_id, attachment_id)
|
||||
|
||||
|
||||
def variant_key(chat_id: UUID, attachment_id: UUID, variant: str) -> str:
|
||||
return "attachments/%s/%s/%s" % (chat_id, attachment_id, variant)
|
||||
|
||||
|
||||
def put_bytes(key: str, data: bytes, content_type: str) -> None:
|
||||
client().put_object(
|
||||
Bucket=_bucket(),
|
||||
Key=key,
|
||||
Body=data,
|
||||
ContentType=content_type,
|
||||
ContentLength=len(data),
|
||||
)
|
||||
|
||||
|
||||
def get_object(key: str):
|
||||
"""Возвращает (bytes, content_type). Бросает ClientError при отсутствии."""
|
||||
resp = client().get_object(Bucket=_bucket(), Key=key)
|
||||
body = resp["Body"].read()
|
||||
ctype = resp.get("ContentType") or "application/octet-stream"
|
||||
return body, ctype
|
||||
|
||||
|
||||
def delete_object(key: str) -> None:
|
||||
client().delete_object(Bucket=_bucket(), Key=key)
|
||||
|
||||
|
||||
def head_object(key: str) -> Optional[dict]:
|
||||
try:
|
||||
return client().head_object(Bucket=_bucket(), Key=key)
|
||||
except ClientError as exc:
|
||||
if exc.response.get("Error", {}).get("Code") in ("404", "NoSuchKey", "NotFound"):
|
||||
return None
|
||||
raise
|
||||
|
||||
|
||||
def list_objects(prefix: str = "attachments/"):
|
||||
"""Итератор по объектам bucket. Используется cleanup-сервисом."""
|
||||
paginator = client().get_paginator("list_objects_v2")
|
||||
for page in paginator.paginate(Bucket=_bucket(), Prefix=prefix):
|
||||
for obj in page.get("Contents", []):
|
||||
yield obj
|
||||
@@ -0,0 +1,176 @@
|
||||
"""Фоновая сверка S3 и PostgreSQL (уровень 4 lab4/lab5).
|
||||
|
||||
- Orphan: объект в S3 есть, а метаданных/вариантов в БД нет.
|
||||
Удаляем только если объект старше ORPHAN_GRACE_SECONDS.
|
||||
- Missing: метаданные есть, объекта в S3 нет — warning.
|
||||
- Staging: объекты staging/ старше grace удаляются (не привязаны к текущей работе).
|
||||
- Также периодически возвращает зависшие processing в queued.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from . import s3
|
||||
from .db import connection, init_pool, close_pool
|
||||
from .postgres import storage
|
||||
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
stream=sys.stdout,
|
||||
)
|
||||
log = logging.getLogger("s3_cleanup")
|
||||
|
||||
|
||||
def _interval() -> int:
|
||||
try:
|
||||
return max(30, int(os.environ.get("CLEANUP_INTERVAL_SECONDS", "300")))
|
||||
except ValueError:
|
||||
return 300
|
||||
|
||||
|
||||
def _grace() -> int:
|
||||
try:
|
||||
return max(0, int(os.environ.get("ORPHAN_GRACE_SECONDS", "3600")))
|
||||
except ValueError:
|
||||
return 3600
|
||||
|
||||
|
||||
def _known_keys() -> set[str]:
|
||||
"""Все ожидаемые object key: оригиналы + варианты."""
|
||||
keys: set[str] = set()
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT id, chat_id, object_key FROM attachments")
|
||||
for aid, cid, okey in cur.fetchall():
|
||||
keys.add(okey)
|
||||
keys.add(s3.original_key(cid, aid))
|
||||
cur.execute("SELECT attachment_id, variant FROM attachment_variants")
|
||||
# нужен chat_id для variant_key
|
||||
# variants: отдельным запросом с join
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT a.chat_id, v.attachment_id, v.variant"
|
||||
" FROM attachment_variants v JOIN attachments a ON a.id = v.attachment_id"
|
||||
)
|
||||
for cid, aid, variant in cur.fetchall():
|
||||
keys.add(s3.variant_key(cid, aid, variant))
|
||||
return keys
|
||||
|
||||
|
||||
def _active_attachment_ids() -> set[str]:
|
||||
"""ID вложений в статусах queued/processing — их staging трогать нельзя."""
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id FROM attachments WHERE status IN ('queued', 'processing')"
|
||||
)
|
||||
return {str(r[0]) for r in cur.fetchall()}
|
||||
|
||||
|
||||
def _run_once() -> dict:
|
||||
now = datetime.now(timezone.utc)
|
||||
grace_cutoff = now - timedelta(seconds=_grace())
|
||||
|
||||
known = _known_keys()
|
||||
active_ids = _active_attachment_ids()
|
||||
orphan_deleted = 0
|
||||
missing = 0
|
||||
scanned = 0
|
||||
staging_deleted = 0
|
||||
|
||||
# attachments/ — orphan по known
|
||||
for obj in s3.list_objects("attachments/"):
|
||||
scanned += 1
|
||||
key = obj["Key"]
|
||||
if key in known:
|
||||
continue
|
||||
# Orphan: в S3 есть, в БД нет. Удаляем только старше grace period.
|
||||
lm = obj.get("LastModified")
|
||||
if lm is None:
|
||||
continue
|
||||
if lm.tzinfo is None:
|
||||
lm = lm.replace(tzinfo=timezone.utc)
|
||||
if lm > grace_cutoff:
|
||||
# Свежий объект — возможно in-flight upload; не трогаем.
|
||||
continue
|
||||
try:
|
||||
s3.delete_object(key)
|
||||
orphan_deleted += 1
|
||||
log.info("event=orphan_deleted key=%s", key)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.error("event=orphan_delete_failed key=%s type=%s",
|
||||
key, type(exc).__name__)
|
||||
|
||||
# staging/ — удаляем только старое И не принадлежащее активной задаче.
|
||||
# Ключ: staging/<chat_id>/<attachment_id>/original
|
||||
for obj in s3.list_objects("staging/"):
|
||||
key = obj["Key"]
|
||||
parts = key.split("/")
|
||||
# Ожидаем минимум 4 части: staging / chat_id / attachment_id / original
|
||||
if len(parts) < 4 or parts[0] != "staging":
|
||||
continue
|
||||
attachment_id = parts[2]
|
||||
if attachment_id in active_ids:
|
||||
# Задача ещё в queued/processing — staging нужен worker'у.
|
||||
continue
|
||||
lm = obj.get("LastModified")
|
||||
if lm is None:
|
||||
continue
|
||||
if lm.tzinfo is None:
|
||||
lm = lm.replace(tzinfo=timezone.utc)
|
||||
if lm > grace_cutoff:
|
||||
continue
|
||||
try:
|
||||
s3.delete_object(key)
|
||||
staging_deleted += 1
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# missing
|
||||
for key in known:
|
||||
if s3.head_object(key) is None:
|
||||
missing += 1
|
||||
log.warning("event=missing_object key=%s", key)
|
||||
|
||||
# зависшие processing → queued
|
||||
try:
|
||||
recovered = storage.recover_stuck_processing()
|
||||
if recovered:
|
||||
log.info("event=stuck_processing_recovered count=%s", recovered)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.error("event=recover_stuck_failed type=%s", type(exc).__name__)
|
||||
|
||||
return {
|
||||
"scanned": scanned,
|
||||
"orphan_deleted": orphan_deleted,
|
||||
"missing": missing,
|
||||
"known": len(known),
|
||||
"staging_deleted": staging_deleted,
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
init_pool()
|
||||
interval = _interval()
|
||||
log.info("event=cleanup_start interval_s=%s grace_s=%s", interval, _grace())
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
stats = _run_once()
|
||||
log.info(
|
||||
"event=cleanup_pass scanned=%s known=%s orphan_deleted=%s"
|
||||
" missing=%s staging_deleted=%s",
|
||||
stats["scanned"], stats["known"], stats["orphan_deleted"],
|
||||
stats["missing"], stats["staging_deleted"],
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.error("event=cleanup_failed type=%s", type(exc).__name__)
|
||||
time.sleep(interval)
|
||||
finally:
|
||||
close_pool()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Хранилище сессий. Redis (основной режим, lab2 level 4) или PostgreSQL (fallback).
|
||||
|
||||
Ключевое: при недоступности Redis поднимаем RuntimeError("redis_unavailable"),
|
||||
чтобы main.py отдал 503 unavailable, а не 500 internal_error.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
|
||||
from ..models.schemas import User
|
||||
from . import db as _db
|
||||
|
||||
try:
|
||||
import redis as _redis
|
||||
except ImportError: # pragma: no cover
|
||||
_redis = None
|
||||
|
||||
|
||||
_SESSION_PREFIX = "sess:"
|
||||
|
||||
|
||||
def now_utc() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _store() -> str:
|
||||
return os.environ.get("SESSION_STORE", "redis").strip().lower()
|
||||
|
||||
|
||||
def _redis_client():
|
||||
"""Возвращает подключённый клиент Redis или поднимает RuntimeError.
|
||||
|
||||
RuntimeError("redis_unavailable: ...") ловит main.runtime_error_handler → 503.
|
||||
"""
|
||||
if _redis is None:
|
||||
raise RuntimeError("redis_unavailable: redis library is not installed")
|
||||
url = os.environ.get("REDIS_URL", "redis://redis:6379/0")
|
||||
try:
|
||||
client = _redis.from_url(
|
||||
url,
|
||||
decode_responses=True,
|
||||
socket_timeout=2.0,
|
||||
socket_connect_timeout=2.0,
|
||||
)
|
||||
client.ping()
|
||||
return client
|
||||
except _redis.RedisError as exc:
|
||||
raise RuntimeError("redis_unavailable: %s" % type(exc).__name__) from exc
|
||||
|
||||
|
||||
def _user_key(user_id: UUID) -> str:
|
||||
return str(user_id)
|
||||
|
||||
|
||||
def create_session(user_id: UUID, ttl_seconds: int) -> tuple[str, datetime]:
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires_at = now_utc() + timedelta(seconds=ttl_seconds)
|
||||
if _store() == "redis":
|
||||
r = _redis_client()
|
||||
payload = json.dumps({"user_id": _user_key(user_id), "expires_at": expires_at.isoformat()})
|
||||
try:
|
||||
# SETEX: TTL — сама суть Redis-сессий
|
||||
r.setex(_SESSION_PREFIX + token, ttl_seconds, payload)
|
||||
except _redis.RedisError as exc:
|
||||
raise RuntimeError("redis_unavailable: %s" % type(exc).__name__) from exc
|
||||
else:
|
||||
with _db.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO sessions (token, user_id, expires_at) VALUES (%s, %s, %s)",
|
||||
(token, user_id, expires_at),
|
||||
)
|
||||
conn.commit()
|
||||
return token, expires_at
|
||||
|
||||
|
||||
def get_session_user(token: str) -> Optional[User]:
|
||||
if _store() == "redis":
|
||||
r = _redis_client()
|
||||
try:
|
||||
raw = r.get(_SESSION_PREFIX + token)
|
||||
except _redis.RedisError as exc:
|
||||
raise RuntimeError("redis_unavailable: %s" % type(exc).__name__) from exc
|
||||
if raw is None:
|
||||
return None
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
user_id = UUID(data["user_id"])
|
||||
expires_at = datetime.fromisoformat(data["expires_at"])
|
||||
except Exception:
|
||||
return None
|
||||
if expires_at <= now_utc():
|
||||
try:
|
||||
r.delete(_SESSION_PREFIX + token)
|
||||
except _redis.RedisError:
|
||||
pass
|
||||
return None
|
||||
return _load_user(user_id)
|
||||
# postgres fallback
|
||||
with _db.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.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 = %s",
|
||||
(token,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
if row[4] <= now_utc():
|
||||
cur.execute("DELETE FROM sessions WHERE token = %s", (token,))
|
||||
conn.commit()
|
||||
return None
|
||||
return User(id=row[0], username=row[1], display_name=row[2], created_at=row[3])
|
||||
|
||||
|
||||
def revoke_session(token: str) -> None:
|
||||
if _store() == "redis":
|
||||
r = _redis_client()
|
||||
try:
|
||||
r.delete(_SESSION_PREFIX + token)
|
||||
except _redis.RedisError as exc:
|
||||
raise RuntimeError("redis_unavailable: %s" % type(exc).__name__) from exc
|
||||
return
|
||||
with _db.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("DELETE FROM sessions WHERE token = %s", (token,))
|
||||
conn.commit()
|
||||
|
||||
|
||||
def _load_user(user_id: UUID) -> Optional[User]:
|
||||
with _db.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
|
||||
(user_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return User(id=row[0], username=row[1], display_name=row[2], created_at=row[3]) if row else None
|
||||
Reference in New Issue
Block a user