добавлена обработка отказов зависимостей и тесты транзакций

This commit is contained in:
2026-10-08 01:10:50 +03:00
parent 4922e68dca
commit c1200032b5
5 changed files with 316 additions and 9 deletions
+13
View File
@@ -1,5 +1,9 @@
from collections.abc import AsyncIterator
import socket
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_sessionmaker,
@@ -42,3 +46,12 @@ SessionFactory = async_sessionmaker(
async def get_db_session() -> AsyncIterator[AsyncSession]:
async with SessionFactory() as session:
yield session
async def ping_database() -> bool:
try:
async with engine.connect() as connection:
await connection.execute(text("SELECT 1"))
return True
except (SQLAlchemyError, OSError):
return False
+52 -2
View File
@@ -1,5 +1,6 @@
from datetime import datetime, timedelta, timezone
from uuid import UUID, uuid4
import socket
from fastapi import Depends, FastAPI, Request
from fastapi.exceptions import RequestValidationError
@@ -10,11 +11,11 @@ from fastapi.security import (
HTTPBasicCredentials,
HTTPBearer,
)
from sqlalchemy.exc import IntegrityError
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.exceptions import HTTPException as StarletteHTTPException
from src.database import get_db_session
from src.database import get_db_session, ping_database
from src.errors import APIError
from src.models import CreateUser, SessionResponse, User, CreateChat, Chat, ChatPage, CreateMessage, Message, MessagePage
from src.repositories import (
@@ -32,6 +33,7 @@ from src.sessions import (
create_session,
delete_session,
get_session_user_id,
ping_session_store,
)
@@ -151,6 +153,44 @@ async def api_error_handler(request: Request, exc: APIError):
)
@app.exception_handler(SQLAlchemyError)
async def database_exception_handler(
request: Request,
exc: SQLAlchemyError,
):
request_id = request.state.request_id
return JSONResponse(
status_code=503,
content={
"error": {
"code": "service_unavailable",
"message": "Database unavailable",
"request_id": request_id,
}
},
)
@app.exception_handler(OSError)
async def database_connection_exception_handler(
request: Request,
exc: OSError,
):
request_id = request.state.request_id
return JSONResponse(
status_code=503,
content={
"error": {
"code": "service_unavailable",
"message": "Database unavailable",
"request_id": request_id,
}
},
)
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(
request: Request,
@@ -204,6 +244,16 @@ async def health_live():
@app.get("/health/ready")
async def health_ready():
database_ready = await ping_database()
session_store_ready = await ping_session_store()
if not database_ready or not session_store_ready:
raise APIError(
status_code=503,
code="service_unavailable",
message="Service dependencies unavailable",
)
return {"status": "ok"}
+34 -7
View File
@@ -3,6 +3,9 @@ import secrets
from uuid import UUID
from redis.asyncio import Redis
from redis.exceptions import RedisError
from src.errors import APIError
CACHE_URL_FILE = "/run/secrets/cache_url"
@@ -31,21 +34,35 @@ redis_client = Redis.from_url(
)
def session_store_unavailable() -> APIError:
return APIError(
status_code=503,
code="service_unavailable",
message="Session store unavailable",
)
async def create_session(user_id: UUID) -> tuple[str, int]:
token = secrets.token_urlsafe(32)
ttl = get_session_ttl_seconds()
await redis_client.set(
f"session:{token}",
str(user_id),
ex=ttl,
)
try:
await redis_client.set(
f"session:{token}",
str(user_id),
ex=ttl,
)
except RedisError as exc:
raise session_store_unavailable() from exc
return token, ttl
async def get_session_user_id(token: str) -> UUID | None:
value = await redis_client.get(f"session:{token}")
try:
value = await redis_client.get(f"session:{token}")
except RedisError as exc:
raise session_store_unavailable() from exc
if value is None:
return None
@@ -57,4 +74,14 @@ async def get_session_user_id(token: str) -> UUID | None:
async def delete_session(token: str) -> None:
await redis_client.delete(f"session:{token}")
try:
await redis_client.delete(f"session:{token}")
except RedisError as exc:
raise session_store_unavailable() from exc
async def ping_session_store() -> bool:
try:
return bool(await redis_client.ping())
except RedisError:
return False
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
import json
import threading
import urllib.error
import urllib.request
import uuid
BASE_URL = "http://localhost:8080"
def register(username: str, barrier: threading.Barrier) -> tuple[int, dict]:
body = json.dumps(
{
"username": username,
"display_name": "Race User",
"password": "correct-password-123",
}
).encode("utf-8")
request = urllib.request.Request(
BASE_URL + "/api/v1/users",
data=body,
headers={"Content-Type": "application/json"},
method="POST",
)
# Оба потока доходят сюда и только потом одновременно продолжают.
barrier.wait()
try:
with urllib.request.urlopen(request, timeout=10) as response:
return response.status, json.loads(response.read())
except urllib.error.HTTPError as error:
return error.code, json.loads(error.read())
def main() -> None:
username = "race_" + uuid.uuid4().hex[:16]
barrier = threading.Barrier(2)
results: list[tuple[int, dict] | None] = [None, None]
def worker(index: int) -> None:
results[index] = register(username, barrier)
threads = [
threading.Thread(target=worker, args=(0,)),
threading.Thread(target=worker, args=(1,)),
]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
statuses = sorted(result[0] for result in results if result is not None)
if statuses != [201, 409]:
raise AssertionError(
f"expected exactly one 201 and one 409, got {statuses}"
)
created = [
result
for result in results
if result is not None and result[0] == 201
]
conflicts = [
result
for result in results
if result is not None and result[0] == 409
]
if len(created) != 1 or created[0][1]["username"] != username:
raise AssertionError("unexpected successful registration response")
if (
len(conflicts) != 1
or conflicts[0][1]["error"]["code"] != "conflict"
):
raise AssertionError("unexpected conflict response")
print(
"PASS: concurrent registration produced exactly "
"one 201 and one 409."
)
if __name__ == "__main__":
main()
+124
View File
@@ -0,0 +1,124 @@
#!/usr/bin/env python3
import asyncio
from uuid import uuid4
from sqlalchemy import text
from sqlalchemy.exc import IntegrityError
from src.database import SessionFactory
async def main() -> None:
chat_id = uuid4()
async with SessionFactory() as session:
# Берём реального существующего пользователя.
result = await session.execute(
text(
"""
SELECT id
FROM users
ORDER BY created_at
LIMIT 1
"""
)
)
user_id = result.scalar_one_or_none()
if user_id is None:
raise AssertionError("test requires at least one existing user")
try:
# Шаг 1: успешно создаём чат.
await session.execute(
text(
"""
INSERT INTO chats (id, title)
VALUES (:chat_id, :title)
"""
),
{
"chat_id": chat_id,
"title": "Rollback automated test",
},
)
# Шаг 2: успешно добавляем реального участника.
await session.execute(
text(
"""
INSERT INTO chat_members (chat_id, user_id)
VALUES (:chat_id, :user_id)
"""
),
{
"chat_id": chat_id,
"user_id": user_id,
},
)
# Шаг 3: намеренно нарушаем внешний ключ.
await session.execute(
text(
"""
INSERT INTO chat_members (chat_id, user_id)
VALUES (:chat_id, :user_id)
"""
),
{
"chat_id": chat_id,
"user_id": uuid4(),
},
)
raise AssertionError("expected foreign key violation")
except IntegrityError:
await session.rollback()
# После rollback начинаем новую транзакцию и проверяем БД.
chat_result = await session.execute(
text(
"""
SELECT COUNT(*)
FROM chats
WHERE id = :chat_id
"""
),
{"chat_id": chat_id},
)
chat_count = chat_result.scalar_one()
member_result = await session.execute(
text(
"""
SELECT COUNT(*)
FROM chat_members
WHERE chat_id = :chat_id
"""
),
{"chat_id": chat_id},
)
member_count = member_result.scalar_one()
if chat_count != 0:
raise AssertionError(
f"chat survived rollback: count={chat_count}"
)
if member_count != 0:
raise AssertionError(
f"chat members survived rollback: count={member_count}"
)
print(
"PASS: failed compound transaction rolled back "
"chat and membership inserts."
)
if __name__ == "__main__":
asyncio.run(main())