From d2c63c5e4d78a80bdf5dbc2b7f51a42ae6bbe187 Mon Sep 17 00:00:00 2001 From: alyoshaslab <139561770+ohfkgsofsex@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:21:40 +0300 Subject: [PATCH] feat: Error handling for HTTP 50x Made so server errors that are not handled by FastAPI are handled by nginx instead of just throwing plain text "Internal Server Error". --- .dockerignore | 1 + .impeccable/surfaces/nginx-50x-html.md | 23 +++++ README.md | 18 ++++ app/app.py | 15 +++ compose.production.yaml | 1 + docker-compose.yml | 1 + nginx.conf | 19 ++++ nginx/50x.html | 127 +++++++++++++++++++++++++ tests/test_error_fallback.py | 77 +++++++++++++++ 9 files changed, 282 insertions(+) create mode 100644 .impeccable/surfaces/nginx-50x-html.md create mode 100644 nginx/50x.html create mode 100644 tests/test_error_fallback.py diff --git a/.dockerignore b/.dockerignore index 04feeb8..15b3b8a 100644 --- a/.dockerignore +++ b/.dockerignore @@ -30,3 +30,4 @@ Dockerfile docker-compose.yml .dockerignore nginx.conf +nginx/ diff --git a/.impeccable/surfaces/nginx-50x-html.md b/.impeccable/surfaces/nginx-50x-html.md new file mode 100644 index 0000000..2c5e297 --- /dev/null +++ b/.impeccable/surfaces/nginx-50x-html.md @@ -0,0 +1,23 @@ +--- +version: 1 +slug: "nginx-50x-html" +primary_target: "nginx/50x.html" +related_targets: ["nginx.conf", "app/app.py"] +--- + +## Mode +Read / understand the server failure and find the recovery actions. + +## Direction +Follow DESIGN.md's flat reading surface, left-aligned text, display heading +scale and 1.35 Cyrillic heading leading, 1.7 prose leading, shared gutters, +44px controls and visible keyboard focus. Keep the illustration centered. +The existing red/yellow palette is pinned by the owner for this failure page; +do not replace it with the site's leaf/lake palette. Keep the existing copy, +including the status signature, and all link destinations. + +## Independence +One HTML file with inline CSS and the existing WebP data URI. No JavaScript, +application assets, font downloads or CDN. Use DESIGN.md's local font stacks +and their system fallbacks. Preserve the nginx/X-Accel-Redirect behavior and +HTTP error status. Do not add animations, decorative gradients or card shadows. diff --git a/README.md b/README.md index e4fb121..ef36f0a 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,24 @@ Docker Compose настраивает два контейнера: - **web**: Python-приложение на порту 8000 (внутренний) - **nginx**: Reverse proxy на порту 8005 (внешний) +Обработанные FastAPI ошибки (включая `HTTPException(500)` и готовые ответы 5xx) +nginx передаёт без подмены тела и статуса (`proxy_intercept_errors off`). +При необработанном исключении обработчик `Exception` возвращает статус 500 +и `X-Accel-Redirect: /_nginx/server-error`. nginx выполняет внутренний переход, +генерирует 500 и отдаёт автономную страницу `nginx/50x.html` с тем же статусом. +Оба внутренних адреса недоступны по прямому запросу клиента. +Без nginx ответ остаётся простым текстом `Internal Server Error` со статусом 500. + +Эта же автономная страница появляется при ошибках самого nginx (500–508, 510, +511), например если приложение недоступно, оборвало соединение до отправки +заголовков (502) или не ответило вовремя (504). Исходный HTTP-статус сохраняется. +Если ошибка возникла после начала отправки ответа, заменить его уже нельзя. +Стили и картинка (WebP в base64) +встроены в один HTML-файл: приложение, его статика, +JavaScript, внешние шрифты и CDN не нужны. Каталог `nginx/` монтируется +только для чтения в обоих Compose-файлах. Страница ошибки не кэшируется. +Для применения изменений приложения и nginx: `docker compose up -d --build --force-recreate`. + #### Управление контентом Контент хранится в Docker volume `es-doc-content` и автоматически обновляется при запуске контейнера из репозитория [es-doc-assets](https://github.com/sovue/es-doc-assets). diff --git a/app/app.py b/app/app.py index 9b50b94..49e4af5 100644 --- a/app/app.py +++ b/app/app.py @@ -1,6 +1,7 @@ from fastapi import FastAPI, Request from starlette.exceptions import HTTPException from starlette.middleware.gzip import GZipMiddleware +from starlette.responses import PlainTextResponse import time from .routes import main_router @@ -30,6 +31,20 @@ async def http_exception_handler(request: Request, exc: HTTPException): 'description': description }, status_code=exc.status_code) +@app.exception_handler(Exception) +async def unhandled_exception_handler(request: Request, exc: Exception): + # nginx handles this internal redirect with its standalone error page. + # Keep a safe 500 body for direct ASGI clients and local development. + # ServerErrorMiddleware re-raises the exception for the server to log it. + return PlainTextResponse( + 'Internal Server Error', + status_code=500, + headers={ + 'X-Accel-Redirect': '/_nginx/server-error', + 'Cache-Control': 'no-store', + }, + ) + class LogRequests: """Pure ASGI middleware, not `@app.middleware("http")` (BaseHTTPMiddleware): that wrapper buffers the whole response through a second task and breaks diff --git a/compose.production.yaml b/compose.production.yaml index 2bfd9fd..73b196e 100644 --- a/compose.production.yaml +++ b/compose.production.yaml @@ -33,6 +33,7 @@ services: - "${ES_DOC_HTTP_PORT:-8005}:80" volumes: - ./nginx.conf:/etc/nginx/nginx.conf:ro + - ./nginx:/usr/share/nginx/html/_nginx:ro healthcheck: test: [CMD, wget, --spider, --quiet, http://127.0.0.1/healthz] interval: 30s diff --git a/docker-compose.yml b/docker-compose.yml index 72cb341..9fde603 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -30,6 +30,7 @@ services: restart: unless-stopped volumes: - ./nginx.conf:/etc/nginx/nginx.conf:ro + - ./nginx:/usr/share/nginx/html/_nginx:ro depends_on: - web diff --git a/nginx.conf b/nginx.conf index 09ac7a9..28802c1 100644 --- a/nginx.conf +++ b/nginx.conf @@ -12,6 +12,25 @@ http { client_max_body_size 10M; + # Preserve application responses, including errors handled by FastAPI. + # Unhandled exceptions explicitly opt in via X-Accel-Redirect below. + proxy_intercept_errors off; + error_page 500 501 502 503 504 505 506 507 508 510 511 /_nginx/50x.html; + + location = /_nginx/server-error { + internal; + # A direct redirect to a static file would return 200. Generate a + # local 500 first so error_page serves the file with the right status. + return 500; + } + + location = /_nginx/50x.html { + internal; + root /usr/share/nginx/html; + charset utf-8; + add_header Cache-Control "no-store" always; + } + location / { proxy_pass http://web:8000; proxy_set_header Host $host; diff --git a/nginx/50x.html b/nginx/50x.html new file mode 100644 index 0000000..c61bb60 --- /dev/null +++ b/nginx/50x.html @@ -0,0 +1,127 @@ + + + + + + + + Сайт временно недоступен — ES Doc + + + + +
+ Вы, уж, простите Юлю, у неё лапки... +

Что-то пошло не так...

+

Ошибка на стороне сервера, мы уже её чиним.
+ Попробуйте обновить страницу позже. Если ошибка останется - напишите нам.

+ +

ES DOC / НЕОБРАБОТАННАЯ ОШИБКА СЕРВЕРА

+
+ + diff --git a/tests/test_error_fallback.py b/tests/test_error_fallback.py new file mode 100644 index 0000000..7f9edd6 --- /dev/null +++ b/tests/test_error_fallback.py @@ -0,0 +1,77 @@ +import unittest +from unittest.mock import patch + +from fastapi import FastAPI, HTTPException +from httpx import ASGITransport, AsyncClient +from starlette.responses import PlainTextResponse, StreamingResponse + +from app.app import app + + +class ErrorFallbackTests(unittest.IsolatedAsyncioTestCase): + def setUp(self): + # Reuse the production handlers without adding test routes to the site. + self.app = FastAPI(exception_handlers=app.exception_handlers) + + @self.app.get('/unhandled') + async def unhandled(): + raise RuntimeError('private exception details') + + @self.app.get('/handled/{status}') + async def handled(status: int): + raise HTTPException(status) + + @self.app.get('/upstream-failure') + async def upstream_failure(): + return PlainTextResponse('Application recovery message', status_code=502) + + @self.app.get('/stream') + async def stream(): + async def chunks(): + yield b'already started' + raise RuntimeError('stream failed') + return StreamingResponse(chunks()) + + async def get(self, path): + async with AsyncClient( + transport=ASGITransport(app=self.app, raise_app_exceptions=False), + base_url='http://test', + ) as client: + return await client.get(path) + + async def test_unhandled_exception_requests_nginx_fallback(self): + response = await self.get('/unhandled') + self.assertEqual(response.status_code, 500) + self.assertEqual(response.headers['x-accel-redirect'], '/_nginx/server-error') + self.assertEqual(response.headers['cache-control'], 'no-store') + self.assertEqual(response.text, 'Internal Server Error') + + async def test_handled_errors_keep_application_page(self): + for status in (404, 500, 503): + with self.subTest(status=status): + response = await self.get(f'/handled/{status}') + self.assertEqual(response.status_code, status) + self.assertNotIn('x-accel-redirect', response.headers) + self.assertIn('text/html', response.headers['content-type']) + self.assertIn(f'Ошибка {status}', response.text) + + async def test_explicit_502_keeps_application_response(self): + response = await self.get('/upstream-failure') + self.assertEqual(response.status_code, 502) + self.assertEqual(response.text, 'Application recovery message') + self.assertNotIn('x-accel-redirect', response.headers) + + async def test_broken_error_template_requests_nginx_fallback(self): + with patch('app.app.templates.TemplateResponse', side_effect=RuntimeError('template failed')): + response = await self.get('/handled/500') + self.assertEqual(response.status_code, 500) + self.assertEqual(response.headers['x-accel-redirect'], '/_nginx/server-error') + + async def test_started_response_is_not_replaced(self): + response = await self.get('/stream') + self.assertEqual(response.status_code, 200) + self.assertNotIn('x-accel-redirect', response.headers) + + +if __name__ == '__main__': + unittest.main()