Skip to content
Merged

Dev #66

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,4 @@ Dockerfile
docker-compose.yml
.dockerignore
nginx.conf
nginx/
23 changes: 23 additions & 0 deletions .impeccable/surfaces/nginx-50x-html.md
Original file line number Diff line number Diff line change
@@ -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.
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
15 changes: 15 additions & 0 deletions app/app.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions compose.production.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,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
Expand Down
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ services:
restart: unless-stopped
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
- ./nginx:/usr/share/nginx/html/_nginx:ro
depends_on:
- web

Expand Down
19 changes: 19 additions & 0 deletions nginx.conf
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
127 changes: 127 additions & 0 deletions nginx/50x.html

Large diffs are not rendered by default.

77 changes: 77 additions & 0 deletions tests/test_error_fallback.py
Original file line number Diff line number Diff line change
@@ -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()
Loading