forked from mtusi2026/mtusi2026lab3
feat: ЛР3 - Nginx балансировка, идемпотентность сообщений и failover
This commit is contained in:
+101
-29
@@ -2,6 +2,7 @@ import asyncio
|
||||
import base64
|
||||
from contextlib import asynccontextmanager
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import uuid
|
||||
@@ -72,10 +73,10 @@ class PostgresStorage:
|
||||
self.redis_client: redis.Redis | None = None
|
||||
|
||||
@asynccontextmanager
|
||||
async def acquire_conn(self, timeout: float = 2.0):
|
||||
async def acquire_conn(self, timeout: float = 5.0):
|
||||
if self.pg_pool is None:
|
||||
raise asyncpg.InterfaceError("Пул подключений к PostgreSQL не инициализирован")
|
||||
async with asyncio.timeout(4.0):
|
||||
async with asyncio.timeout(10.0):
|
||||
async with self.pg_pool.acquire(timeout=timeout) as conn:
|
||||
yield conn
|
||||
|
||||
@@ -85,8 +86,8 @@ class PostgresStorage:
|
||||
DATABASE_URL,
|
||||
min_size=2,
|
||||
max_size=20,
|
||||
command_timeout=2.0,
|
||||
timeout=2.0,
|
||||
command_timeout=5.0,
|
||||
timeout=5.0,
|
||||
)
|
||||
|
||||
logger.info("Подключение к Redis: %s", CACHE_URL.split("@")[-1])
|
||||
@@ -97,18 +98,6 @@ class PostgresStorage:
|
||||
socket_timeout=3.0,
|
||||
)
|
||||
|
||||
try:
|
||||
async with self.acquire_conn() as conn:
|
||||
col_type = await conn.fetchval(
|
||||
"SELECT data_type FROM information_schema.columns WHERE table_name = 'messages' AND column_name = 'text'"
|
||||
)
|
||||
if col_type in ("text", "character varying"):
|
||||
await conn.execute(
|
||||
"ALTER TABLE messages ALTER COLUMN text TYPE BYTEA USING text::bytea"
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning("Не удалось проверить/обновить схему messages.text: %s", exc)
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
if self.pg_pool:
|
||||
await self.pg_pool.close()
|
||||
@@ -136,7 +125,7 @@ class PostgresStorage:
|
||||
) -> UserResponse:
|
||||
user_id = uuid.uuid4()
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
pwd_hash = hash_password(password)
|
||||
pwd_hash = await asyncio.to_thread(hash_password, password)
|
||||
|
||||
try:
|
||||
async with self.acquire_conn() as conn:
|
||||
@@ -177,7 +166,8 @@ class PostgresStorage:
|
||||
if not row:
|
||||
return None
|
||||
|
||||
if not verify_password(row["password_hash"], password):
|
||||
is_valid = await asyncio.to_thread(verify_password, row["password_hash"], password)
|
||||
if not is_valid:
|
||||
return None
|
||||
|
||||
return UserResponse(
|
||||
@@ -417,8 +407,13 @@ class PostgresStorage:
|
||||
|
||||
# ------------------ Сообщения ------------------
|
||||
|
||||
@staticmethod
|
||||
def compute_request_hash(text: str) -> str:
|
||||
canonical = json.dumps({"text": text}, sort_keys=True, ensure_ascii=False)
|
||||
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||
|
||||
async def send_message(
|
||||
self, caller_id: str, chat_id: str, text: str
|
||||
self, caller_id: str, chat_id: str, text: str, idempotency_key: str
|
||||
) -> MessageResponse:
|
||||
try:
|
||||
cid = uuid.UUID(chat_id)
|
||||
@@ -426,9 +421,7 @@ class PostgresStorage:
|
||||
except ValueError:
|
||||
raise NotFoundError("Чат не найден")
|
||||
|
||||
msg_id = uuid.uuid4()
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
text_bytes = text.encode("utf-8")
|
||||
req_hash = self.compute_request_hash(text)
|
||||
|
||||
async with self.acquire_conn() as conn:
|
||||
is_member = await conn.fetchval(
|
||||
@@ -439,17 +432,96 @@ class PostgresStorage:
|
||||
if not is_member:
|
||||
raise NotFoundError("Чат не найден")
|
||||
|
||||
await conn.execute(
|
||||
# 1. Проверяем, обрабатывался ли уже этот idempotency_key
|
||||
existing = await conn.fetchrow(
|
||||
"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
SELECT ik.message_id, ik.request_hash, m.text, m.created_at AS msg_created_at
|
||||
FROM idempotency_keys ik
|
||||
JOIN messages m ON m.id = ik.message_id
|
||||
WHERE ik.user_id = $1 AND ik.chat_id = $2 AND ik.idempotency_key = $3
|
||||
""",
|
||||
msg_id,
|
||||
cid,
|
||||
c_caller,
|
||||
text_bytes,
|
||||
now,
|
||||
cid,
|
||||
idempotency_key,
|
||||
)
|
||||
if existing:
|
||||
if existing["request_hash"] == req_hash:
|
||||
raw_text = existing["text"]
|
||||
msg_text = (
|
||||
raw_text.decode("utf-8")
|
||||
if isinstance(raw_text, (bytes, bytearray))
|
||||
else str(raw_text)
|
||||
)
|
||||
return MessageResponse(
|
||||
id=str(existing["message_id"]),
|
||||
chat_id=chat_id,
|
||||
sender_id=caller_id,
|
||||
text=msg_text,
|
||||
created_at=_format_dt(existing["msg_created_at"]),
|
||||
)
|
||||
else:
|
||||
raise ConflictError("Ключ идемпотентности уже использован с другим телом запроса")
|
||||
|
||||
msg_id = uuid.uuid4()
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
text_bytes = text.encode("utf-8")
|
||||
|
||||
try:
|
||||
async with conn.transaction():
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
""",
|
||||
msg_id,
|
||||
cid,
|
||||
c_caller,
|
||||
text_bytes,
|
||||
now,
|
||||
)
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO idempotency_keys (user_id, chat_id, idempotency_key, message_id, request_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
""",
|
||||
c_caller,
|
||||
cid,
|
||||
idempotency_key,
|
||||
msg_id,
|
||||
req_hash,
|
||||
now,
|
||||
)
|
||||
except asyncpg.UniqueViolationError:
|
||||
# Конкурентная вставка из другой реплики выиграла гонку
|
||||
winner = await conn.fetchrow(
|
||||
"""
|
||||
SELECT ik.message_id, ik.request_hash, m.text, m.created_at AS msg_created_at
|
||||
FROM idempotency_keys ik
|
||||
JOIN messages m ON m.id = ik.message_id
|
||||
WHERE ik.user_id = $1 AND ik.chat_id = $2 AND ik.idempotency_key = $3
|
||||
""",
|
||||
c_caller,
|
||||
cid,
|
||||
idempotency_key,
|
||||
)
|
||||
if winner:
|
||||
if winner["request_hash"] == req_hash:
|
||||
raw_text = winner["text"]
|
||||
msg_text = (
|
||||
raw_text.decode("utf-8")
|
||||
if isinstance(raw_text, (bytes, bytearray))
|
||||
else str(raw_text)
|
||||
)
|
||||
return MessageResponse(
|
||||
id=str(winner["message_id"]),
|
||||
chat_id=chat_id,
|
||||
sender_id=caller_id,
|
||||
text=msg_text,
|
||||
created_at=_format_dt(winner["msg_created_at"]),
|
||||
)
|
||||
else:
|
||||
raise ConflictError("Ключ идемпотентности уже использован с другим телом запроса")
|
||||
raise
|
||||
|
||||
return MessageResponse(
|
||||
id=str(msg_id),
|
||||
|
||||
Reference in New Issue
Block a user