выполнение лр2 на 4
Skeleton contracts / contracts (pull_request) Failing after 37s

This commit is contained in:
Ilya
2026-10-09 12:44:56 +03:00
parent e914e384fc
commit 13fa1852cb
30 changed files with 585 additions and 238 deletions
+3 -34
View File
@@ -1,4 +1,3 @@
"""Lab 2: messenger API on PostgreSQL with Bearer sessions and a Valkey session cache."""
from __future__ import annotations
import logging
@@ -39,18 +38,13 @@ async def lifespan(_app: FastAPI):
app = FastAPI(title="MTUSI Messenger — lab2", lifespan=lifespan)
# ---------------------------------------------------------------------------
# Cross-cutting: request id + uniform error envelope
# ---------------------------------------------------------------------------
# PostgreSQL unreachable, restarting or pool exhausted -> bounded 503, never a hang.
DB_UNAVAILABLE = (
OSError, # includes ConnectionRefusedError and TimeoutError (pool acquire / connect)
OSError,
asyncpg.PostgresConnectionError,
asyncpg.InterfaceError,
asyncpg.TooManyConnectionsError,
asyncpg.exceptions.OperatorInterventionError, # admin shutdown, cannot connect now
asyncpg.exceptions.QueryCanceledError, # statement timeout
asyncpg.exceptions.OperatorInterventionError,
asyncpg.exceptions.QueryCanceledError,
)
@@ -70,8 +64,6 @@ async def request_id_middleware(request: Request, call_next):
try:
response = await call_next(request)
except Exception:
# Unhandled errors must be answered here: Starlette's own 500 handler runs
# outside this middleware and would drop the X-Request-Id header.
logger.exception("unhandled error for request_id=%s", request_id)
response = JSONResponse(status_code=500, content=error_body("internal_error", "internal error", request_id))
response.headers["X-Request-Id"] = request_id
@@ -104,11 +96,6 @@ for _exc in DB_UNAVAILABLE:
app.add_exception_handler(_exc, db_unavailable_handler)
# ---------------------------------------------------------------------------
# Auth: Basic only on POST /auth/sessions, Bearer everywhere else.
# X-User-Id is ignored since lab2.
# ---------------------------------------------------------------------------
async def current_user(request: Request) -> dict:
return await auth.authenticate(store, cache, request.headers.get("Authorization"))
@@ -124,10 +111,6 @@ def not_found() -> ApiError:
return ApiError(404, "not_found", "chat not found")
# ---------------------------------------------------------------------------
# Health
# ---------------------------------------------------------------------------
@app.get("/health/live", response_model=Health)
async def liveness():
return Health()
@@ -135,7 +118,6 @@ async def liveness():
@app.get("/health/ready", response_model=Health)
async def readiness():
# PostgreSQL is critical; Valkey is not (the API bypasses the cache without it).
try:
await store.ping()
except DB_UNAVAILABLE:
@@ -143,10 +125,6 @@ async def readiness():
return Health()
# ---------------------------------------------------------------------------
# Users and sessions
# ---------------------------------------------------------------------------
@app.post("/api/v1/users", response_model=User, status_code=201)
async def register_user(body: CreateUser):
if not body.display_name.strip() or not body.password.strip():
@@ -171,10 +149,6 @@ async def delete_session(request: Request):
return Response(status_code=204)
# ---------------------------------------------------------------------------
# Chats
# ---------------------------------------------------------------------------
@app.post("/api/v1/chats", response_model=Chat, status_code=201)
async def create_chat(body: CreateChat, user: dict = Depends(current_user)):
if not body.title.strip():
@@ -203,15 +177,10 @@ async def get_chat(chat_id: str, user: dict = Depends(current_user)):
return chat
# ---------------------------------------------------------------------------
# Messages
# ---------------------------------------------------------------------------
@app.post("/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=201)
async def create_message(chat_id: str, body: CreateMessage, user: dict = Depends(current_user)):
chat_uuid = parse_uuid(chat_id, "chat_id")
if not body.text.strip():
# Access is checked before content: an outsider gets 404 even for a blank text.
if not await store.is_member(chat_uuid, uuid.UUID(user["id"])):
raise not_found()
raise ApiError(400, "invalid_request", "text must not be blank")