forked from mtusi2026/mtusi2026lab2
Compare commits
2
Commits
313d2c23fe
...
e9553e33d6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e9553e33d6 | ||
|
|
d20190a693 |
@@ -0,0 +1,28 @@
|
||||
@echo off
|
||||
REM Windows-эквивалент scripts/restart.sh для lab2.
|
||||
REM
|
||||
REM Методичка:
|
||||
REM Перезапустите API и ВСЕ используемые хранилища состояний (БД, сессии, S3, брокер, если применимо).
|
||||
REM Сохраните постоянные тома и схемы/данные; не используйте -v / flush / re-seed.
|
||||
REM Разрешите оператору снять защиту, если это необходимо в lab7; не выводите учетные данные.
|
||||
REM Выходите из программы с кодом 0 только после выполнения запланированного действия; тест отдельно проверяет готовность API.
|
||||
|
||||
REM Перезапуск API. PostgreSQL НЕ трогаем — volume с данными сохраняется.
|
||||
docker restart mtusi-messenger-lab2 >nul 2>&1
|
||||
if errorlevel 1 (
|
||||
docker stop mtusi-messenger-lab2 >nul 2>&1
|
||||
docker run -d --rm --name mtusi-messenger-lab2 ^
|
||||
-p 127.0.0.1:8080:8080 ^
|
||||
--env-file .env ^
|
||||
mtusi-messenger:lab2 >nul
|
||||
)
|
||||
|
||||
REM Ждём readiness
|
||||
set /a i=0
|
||||
:wait_loop
|
||||
if %i% geq 90 exit /b 1
|
||||
curl -fsS http://localhost:8080/health/ready >nul 2>&1
|
||||
if not errorlevel 1 exit /b 0
|
||||
set /a i+=1
|
||||
timeout /t 1 /nobreak >nul
|
||||
goto wait_loop
|
||||
+14
-7
@@ -87,13 +87,20 @@ _ERROR_CODES = {
|
||||
}
|
||||
|
||||
|
||||
def _error_response(status_code: int, message: str, request_id: str) -> JSONResponse:
|
||||
def _unauthorized_challenge(path: str) -> str:
|
||||
"""Basic — только для POST /api/v1/auth/sessions; остальное — Bearer."""
|
||||
if path == "/api/v1/auth/sessions":
|
||||
return 'Basic realm="messenger", charset="UTF-8"'
|
||||
return 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
def _error_response(
|
||||
status_code: int, message: str, request_id: str, path: str = ""
|
||||
) -> JSONResponse:
|
||||
code = _ERROR_CODES.get(status_code, "internal_error")
|
||||
headers = {}
|
||||
if status_code == 401:
|
||||
# Basic — только для /auth/sessions; для остальных endpoint — Bearer.
|
||||
# Клиент получает корректный challenge.
|
||||
headers["WWW-Authenticate"] = 'Bearer realm="messenger"'
|
||||
headers["WWW-Authenticate"] = _unauthorized_challenge(path)
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content={"error": {"code": code, "message": message, "request_id": request_id}},
|
||||
@@ -105,13 +112,13 @@ def _error_response(status_code: int, message: str, request_id: str) -> JSONResp
|
||||
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
message = exc.detail if isinstance(exc.detail, str) else "Ошибка"
|
||||
return _error_response(exc.status_code, message, request_id)
|
||||
return _error_response(exc.status_code, message, request_id, request.url.path)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
return _error_response(400, "Неверный запрос", request_id)
|
||||
return _error_response(400, "Неверный запрос", request_id, request.url.path)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
@@ -119,7 +126,7 @@ async def unhandled_exception_handler(request: Request, exc: Exception):
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
# Внутренние детали не раскрываем; пишем в лог без секретов
|
||||
logger.error("event=unhandled_exception type=%s request_id=%s", type(exc).__name__, request_id)
|
||||
return _error_response(500, "Внутренняя ошибка", request_id)
|
||||
return _error_response(500, "Внутренняя ошибка", request_id, request.url.path)
|
||||
|
||||
|
||||
app.include_router(health.router)
|
||||
|
||||
Reference in New Issue
Block a user