Реализовать обязательный минимум: балансировку, общие повторы и сохранность при отказе

This commit is contained in:
2026-10-23 18:35:04 +03:00
parent 366b4be7b8
commit bdcf00a412
28 changed files with 288 additions and 19 deletions
+12 -8
View File
@@ -1,4 +1,6 @@
import uuid
import os
import socket
from contextlib import asynccontextmanager
import psycopg
from psycopg_pool import PoolTimeout
@@ -25,7 +27,8 @@ def create_app() -> FastAPI:
finally:
await run_in_threadpool(storage.pool.close)
app = FastAPI(title="MTUSI Messenger Lab2", version="1.2.0", lifespan=lifespan)
instance_id = os.getenv("INSTANCE_ID", socket.gethostname()) + "-" + uuid.uuid4().hex[:8]
app = FastAPI(title="MTUSI Messenger Lab3", version="1.3.0", lifespan=lifespan)
@app.exception_handler(psycopg.OperationalError)
@app.exception_handler(psycopg.errors.QueryCanceled)
@@ -38,11 +41,11 @@ def create_app() -> FastAPI:
@app.middleware("http")
async def add_request_id(request: Request, call_next):
"""Middleware: добавляет X-Request-Id и реализует ограничение очереди запросов (трек 2)."""
"""Добавляет идентификаторы запроса и процесса, ограничивает очередь."""
request_id = request.headers.get("X-Request-Id", "") or str(uuid.uuid4())
request.state.request_id = request_id
# Трек 2: ограничение очереди запросов — возвращаем 503 при переполнении
# Ограничение числа обслуживаемых запросов в процессе.
if not storage.acquire_request_slot():
return JSONResponse(
status_code=503,
@@ -53,12 +56,13 @@ def create_app() -> FastAPI:
"request_id": request_id,
}
).model_dump(),
headers={"X-Request-Id": request_id},
headers={"X-Request-Id": request_id, "X-Instance-Id": instance_id},
)
try:
response = await call_next(request)
response.headers["X-Request-Id"] = request_id
response.headers["X-Instance-Id"] = instance_id
return response
finally:
storage.release_request_slot()
@@ -82,7 +86,7 @@ def create_app() -> FastAPI:
"request_id": request_id,
}
).model_dump(),
headers={"X-Request-Id": request_id},
headers={"X-Request-Id": request_id, "X-Instance-Id": instance_id},
)
@app.exception_handler(RequestValidationError)
@@ -103,7 +107,7 @@ def create_app() -> FastAPI:
"request_id": request_id,
}
).model_dump(),
headers={"X-Request-Id": request_id},
headers={"X-Request-Id": request_id, "X-Instance-Id": instance_id},
)
@app.exception_handler(PydanticValidationError)
@@ -124,7 +128,7 @@ def create_app() -> FastAPI:
"request_id": request_id,
}
).model_dump(),
headers={"X-Request-Id": request_id},
headers={"X-Request-Id": request_id, "X-Instance-Id": instance_id},
)
@app.exception_handler(Exception)
@@ -140,7 +144,7 @@ def create_app() -> FastAPI:
"request_id": request_id,
}
).model_dump(),
headers={"X-Request-Id": request_id},
headers={"X-Request-Id": request_id, "X-Instance-Id": instance_id},
)
# Подключаем роуты
+1
View File
@@ -96,6 +96,7 @@ class CreateMessage(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
text: str = Field(..., min_length=1, max_length=4000)
attachment_ids: list[str] = Field(default_factory=list, max_length=0)
@field_validator("text")
@classmethod
+9 -3
View File
@@ -1,10 +1,11 @@
from uuid import UUID
import re
from fastapi import APIRouter, Depends, HTTPException, Request
from src.models import CreateMessage, Message, MessagePage
from src.routes.common import get_request_id, make_error, require_user
from src.storage import LimitExceeded, ValidationError, storage
from src.storage import ConflictError, LimitExceeded, ValidationError, storage
router = APIRouter()
@@ -16,7 +17,7 @@ def create_message(
body: CreateMessage,
x_user_id: str = Depends(require_user),
):
"""Отправить сообщение в чат. Отправитель определяется по X-User-Id."""
"""Отправить сообщение от владельца Bearer-сессии с общей защитой повторов."""
request_id = get_request_id(request)
chat_id_str = str(chat_id)
@@ -28,8 +29,13 @@ def create_message(
)
try:
msg = storage.create_message(chat_id_str, x_user_id, body.text)
key = request.headers.get('Idempotency-Key', '')
if not re.fullmatch(r'[A-Za-z0-9._:-]{1,128}', key):
raise HTTPException(400, detail=make_error('invalid_request', 'неверный Idempotency-Key', request_id).model_dump())
msg = storage.create_message(chat_id_str, x_user_id, body.text, key)
return msg
except ConflictError as e:
raise HTTPException(409, detail=make_error('conflict', str(e), request_id).model_dump())
except LimitExceeded as e:
raise HTTPException(
status_code=429,
+13 -2
View File
@@ -50,7 +50,7 @@ def public_row(row):
class PostgresStorage:
def __init__(self):
self.pool = ConnectionPool(setting('DATABASE_URL', ''), min_size=1, max_size=10,
self.pool = ConnectionPool(setting('DATABASE_URL', ''), min_size=1, max_size=int(os.getenv("POOL_SIZE", "10")),
timeout=3, max_waiting=32, open=False, check=ConnectionPool.check_connection,
kwargs={'row_factory': dict_row, 'connect_timeout': 3,
'options': '-c statement_timeout=3000 -c lock_timeout=2000'})
@@ -194,9 +194,20 @@ class PostgresStorage:
next_cursor = self._encode_cursor('chats',user_id,page[-1].created_at,page[-1].id) if len(rows)>limit else None
return page,next_cursor
def create_message(self, chat_id, sender_id, text):
def create_message(self, chat_id, sender_id, text, key):
# Блокировка сериализует один ключ на всех репликах; результат и сообщение атомарны.
with self.pool.connection() as conn:
scope = json.dumps([sender_id, chat_id, key])
conn.execute('SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))', (scope,))
old = conn.execute('SELECT * FROM message_requests WHERE user_id=%s AND chat_id=%s AND key=%s AND expires_at>clock_timestamp()', (sender_id,chat_id,key)).fetchone()
if old:
if old['body'] != text:
raise ConflictError('ключ уже использован с другим сообщением')
row = conn.execute('SELECT * FROM messages WHERE id=%s', (old['message_id'],)).fetchone()
return Message(**public_row(row))
conn.execute('DELETE FROM message_requests WHERE user_id=%s AND chat_id=%s AND key=%s', (sender_id,chat_id,key))
row = conn.execute('INSERT INTO messages (id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) RETURNING *', (uuid.uuid4(),chat_id,sender_id,text)).fetchone()
conn.execute("INSERT INTO message_requests VALUES (%s,%s,%s,%s,%s,clock_timestamp()+interval '24 hours')", (sender_id,chat_id,key,text,row['id']))
return Message(**public_row(row))
def list_messages(self, chat_id, cursor, limit):