Files
mtusi2026lab5/app/errors.py
T
RainakandClaude Opus 5.5 0a221b0675 ЛР5 БВТ2304 Запорожец на 5
RabbitMQ (quorum queue, publisher confirms, manual ack, DLX) + отдельный worker:
staging в S3 + вложение/job/outbox одной транзакцией -> 202 queued; relay outbox,
lease с heartbeat и fencing (worker_id, attempt), retry с backoff+jitter, failed-реестр,
безопасный replay с audit; thumbnail/crop/WebP в изолированном процессе с лимитами.
Тесты окон отказа (fault injection), трек 1 «Очередь под перегрузкой» с backpressure.
Перенесено исправление замечания lab3 PR #99 (U+0000 в тексте).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:33:52 +03:00

49 lines
1.8 KiB
Python

"""Единый формат ошибок {"error":{"code","message","request_id"}}."""
from contextvars import ContextVar
from fastapi.responses import JSONResponse
request_id_var: ContextVar[str] = ContextVar('request_id', default='-')
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
class ApiError(Exception):
def __init__(self, status: int, code: str, message: str, headers: dict | None = None):
super().__init__(message)
self.status = status
self.code = code
self.message = message
self.headers = headers or {}
def invalid(message: str = 'Некорректный запрос') -> ApiError:
return ApiError(400, 'invalid_request', message)
def not_found() -> ApiError:
# Одинаковый ответ для "нет такого" и "чужое": существование чужого чата не раскрывается.
return ApiError(404, 'not_found', 'Объект не найден')
def unauthorized_bearer() -> ApiError:
return ApiError(401, 'unauthorized', 'Требуется действительная сессия', {'WWW-Authenticate': BEARER_CHALLENGE})
def unauthorized_basic() -> ApiError:
return ApiError(401, 'unauthorized', 'Неверные учётные данные', {'WWW-Authenticate': BASIC_CHALLENGE})
def unavailable() -> ApiError:
return ApiError(503, 'unavailable', 'Сервис временно недоступен')
def error_response(status: int, code: str, message: str, headers: dict | None = None) -> JSONResponse:
rid = request_id_var.get()
return JSONResponse(
status_code=status,
content={'error': {'code': code, 'message': message, 'request_id': rid}},
headers=headers,
)