Make admin and API errors visible and traceable
Return structured JSON errors with request IDs, log unexpected exceptions with tracebacks, and show HTTP and network failures in the admin UI without losing unsaved source. Preserve publication errors when release listing also fails, handle cancelled preview promises, and add regression tests, browser failure scenarios, and updated API documentation.
This commit is contained in:
@@ -27,6 +27,7 @@
|
|||||||
- В каталоге Fragment сохраняй `name`, `description` и категории из дизайна: «Список коллекций», «Текстовая секция», «Markdown body», «Карточки». Под названием показывай назначение из `fragment.yaml:description`, передаваемое через API; ID доступен для поиска и в title. `section` содержит свой текст и поддерживает слоты, `richtext` по умолчанию выводит `page.body`. Изменения builtin/API/шаблонов требуют пересборки Docker-образа; одного bind-mount сайта недостаточно.
|
- В каталоге Fragment сохраняй `name`, `description` и категории из дизайна: «Список коллекций», «Текстовая секция», «Markdown body», «Карточки». Под названием показывай назначение из `fragment.yaml:description`, передаваемое через API; ID доступен для поиска и в title. `section` содержит свой текст и поддерживает слоты, `richtext` по умолчанию выводит `page.body`. Изменения builtin/API/шаблонов требуют пересборки Docker-образа; одного bind-mount сайта недостаточно.
|
||||||
- В админских формах сохраняй `action`, `method`, имена полей, `csrf`, `etag` (параметр сервиса — `if_match`) и передачу ошибок. Запись контента проходит через `ContentService`: блокировка, проверка версии, валидация, история, атомарная запись.
|
- В админских формах сохраняй `action`, `method`, имена полей, `csrf`, `etag` (параметр сервиса — `if_match`) и передачу ошибок. Запись контента проходит через `ContentService`: блокировка, проверка версии, валидация, история, атомарная запись.
|
||||||
- Для нового UI HTML и JSON имеют отдельные маршруты. Серверный клиент вызывает API через `httpx.ASGITransport`; внутренние credentials не попадают в браузер, автор и эпоха проверяются на API-границе. Буфер/превью не сохраняют контент до явного Save.
|
- Для нового UI HTML и JSON имеют отдельные маршруты. Серверный клиент вызывает API через `httpx.ASGITransport`; внутренние credentials не попадают в браузер, автор и эпоха проверяются на API-границе. Буфер/превью не сохраняют контент до явного Save.
|
||||||
|
- Ошибки JSON API возвращай как `error: {code, message, request_id, …}` с корректным HTTP-статусом. Общая граница — `web/error_handling.py`: неожиданные исключения записываются со стеком в `uvicorn.error`, метод, путь и ID связывают HTML-запрос с внутренним API. Не добавляй в лог тело запроса, cookies и Authorization. В htmx ошибки HTTP/сети показываются через уведомление из дизайна; 5xx не должны заменять несохранённый исходник редактора. Проверка отказов — `PYTHONPATH=src python scripts/qa_errors_001.py`.
|
||||||
- Сохраняй autoescape, санитайзер Markdown и CSP. JS для админки подключай внешним локальным файлом. Пассивное превью не исполняет скрипты. Интерактивное использует `web/preview_app.py` на отдельном origin, nonce bridge и защищённые immutable snapshots; JS сайта не запускается. Обычная сборка не получает служебную разметку.
|
- Сохраняй autoescape, санитайзер Markdown и CSP. JS для админки подключай внешним локальным файлом. Пассивное превью не исполняет скрипты. Интерактивное использует `web/preview_app.py` на отдельном origin, nonce bridge и защищённые immutable snapshots; JS сайта не запускается. Обычная сборка не получает служебную разметку.
|
||||||
- Приём публичных форм пока возвращает HTTP 501; MCP и changeset — заготовки. Не показывай успешную отправку без работающего обработчика.
|
- Приём публичных форм пока возвращает HTTP 501; MCP и changeset — заготовки. Не показывай успешную отправку без работающего обработчика.
|
||||||
- Проверяй мобильную и широкую версии, клавиатурную навигацию, фокус, подписи полей и контраст. Анимации учитывают `prefers-reduced-motion`.
|
- Проверяй мобильную и широкую версии, клавиатурную навигацию, фокус, подписи полей и контраст. Анимации учитывают `prefers-reduced-motion`.
|
||||||
|
|||||||
@@ -0,0 +1,181 @@
|
|||||||
|
"""Exercise server failures and network errors in a real browser on a temporary site."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from playwright.sync_api import expect, sync_playwright
|
||||||
|
from qa_001 import PASSWORD, ROOT, serve
|
||||||
|
|
||||||
|
from site_engine.build.pipeline import build_site
|
||||||
|
from site_engine.services.auth import hash_password
|
||||||
|
from site_engine.web.app import create_app
|
||||||
|
|
||||||
|
|
||||||
|
class CapturedLogs(logging.Handler):
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.records = []
|
||||||
|
|
||||||
|
def emit(self, record):
|
||||||
|
self.records.append(record)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
out = Path(os.environ.get("QA_ERRORS_OUT", "/tmp/cms-errors-qa"))
|
||||||
|
out.mkdir(parents=True, exist_ok=True)
|
||||||
|
checks, errors, dialogs = [], [], []
|
||||||
|
captured = CapturedLogs()
|
||||||
|
logger = logging.getLogger("uvicorn.error")
|
||||||
|
try:
|
||||||
|
with tempfile.TemporaryDirectory(prefix="cms-errors-") as temp:
|
||||||
|
work = Path(temp)
|
||||||
|
site, dist = work / "site", work / "dist"
|
||||||
|
shutil.copytree(
|
||||||
|
ROOT / "examples/ai-studio", site, ignore=shutil.ignore_patterns(".engine")
|
||||||
|
)
|
||||||
|
build_site(site, dist)
|
||||||
|
live = (dist / "current").resolve()
|
||||||
|
env = {
|
||||||
|
"SITE_ROOT": str(site),
|
||||||
|
"SITE_DIST": str(dist),
|
||||||
|
"SITE_STATE_DIR": str(work / "state"),
|
||||||
|
"SITE_ADMIN_LOGIN": "admin",
|
||||||
|
"SITE_ADMIN_PASSWORD_HASH": hash_password(PASSWORD, n=2**10),
|
||||||
|
"SITE_SECRET_KEY": "temporary-error-qa-secret-" * 3,
|
||||||
|
"SITE_COOKIE_SECURE": "0",
|
||||||
|
"SITE_ADMIN_ORIGIN": "",
|
||||||
|
"SITE_PREVIEW_ORIGIN": "",
|
||||||
|
}
|
||||||
|
with (
|
||||||
|
patch.dict(os.environ, env),
|
||||||
|
serve(create_app()) as origin,
|
||||||
|
sync_playwright() as pw,
|
||||||
|
):
|
||||||
|
logger.addHandler(captured) # Uvicorn replaces its handlers on startup.
|
||||||
|
kind = getattr(pw, os.environ.get("QA_BROWSER", "chromium"))
|
||||||
|
options = {"headless": True}
|
||||||
|
if kind.name == "chromium":
|
||||||
|
options["args"] = ["--no-sandbox", "--no-proxy-server"]
|
||||||
|
if kind.name == "firefox":
|
||||||
|
options["firefox_user_prefs"] = {"network.proxy.type": 0}
|
||||||
|
if os.environ.get("QA_BROWSER_EXECUTABLE"):
|
||||||
|
options["executable_path"] = os.environ["QA_BROWSER_EXECUTABLE"]
|
||||||
|
browser = kind.launch(**options)
|
||||||
|
page = browser.new_page(viewport={"width": 1440, "height": 960})
|
||||||
|
page.on(
|
||||||
|
"pageerror",
|
||||||
|
lambda e: errors.append({"message": str(e), "stack": e.stack, "url": page.url}),
|
||||||
|
)
|
||||||
|
|
||||||
|
def native(dialog):
|
||||||
|
dialogs.append(dialog.message)
|
||||||
|
dialog.dismiss()
|
||||||
|
|
||||||
|
page.on("dialog", native)
|
||||||
|
page.goto(origin + "/admin/login")
|
||||||
|
page.locator('[name="login"]').fill("admin")
|
||||||
|
page.locator('[name="password"]').fill(PASSWORD)
|
||||||
|
page.get_by_role("button", name="Войти", exact=True).click()
|
||||||
|
page.wait_for_url(origin + "/admin/")
|
||||||
|
page.goto(origin + "/admin/publish")
|
||||||
|
with patch(
|
||||||
|
"site_engine.web.api.routes.publish",
|
||||||
|
side_effect=PermissionError("QA publish denied"),
|
||||||
|
):
|
||||||
|
page.get_by_role("button", name="Опубликовать текущий черновик сайта").click()
|
||||||
|
with page.expect_response(
|
||||||
|
lambda r: r.url.endswith("/admin/publish") and r.request.method == "POST"
|
||||||
|
) as failed:
|
||||||
|
page.locator("#confirm-dialog").get_by_role(
|
||||||
|
"button", name="Продолжить"
|
||||||
|
).click()
|
||||||
|
response = failed.value
|
||||||
|
assert response.status == 500
|
||||||
|
correlation = response.headers["x-request-id"]
|
||||||
|
expect(page.locator("#workspace")).to_contain_text("storage_error")
|
||||||
|
expect(page.locator("#workspace")).to_contain_text(correlation)
|
||||||
|
toast = page.locator("#request-error")
|
||||||
|
expect(toast).to_be_visible()
|
||||||
|
expect(toast).to_contain_text(correlation)
|
||||||
|
expect(toast).to_contain_text("Ошибка доступа к файлам")
|
||||||
|
assert (dist / "current").resolve() == live
|
||||||
|
assert any(
|
||||||
|
correlation in r.getMessage() and r.exc_info for r in captured.records
|
||||||
|
)
|
||||||
|
checks.append(
|
||||||
|
"publish_500_visible_in_page_and_notification_with_traceback_and_same_request_id"
|
||||||
|
)
|
||||||
|
page.screenshot(path=str(out / "publish-error-1440.png"))
|
||||||
|
page.set_viewport_size({"width": 390, "height": 844})
|
||||||
|
expect(toast).to_be_visible()
|
||||||
|
assert toast.bounding_box()["x"] >= 0
|
||||||
|
page.screenshot(path=str(out / "publish-error-390.png"))
|
||||||
|
checks.append("persistent_error_notification_at_desktop_and_mobile_widths")
|
||||||
|
page.set_viewport_size({"width": 1440, "height": 960})
|
||||||
|
page.goto(origin + "/admin/pages/index")
|
||||||
|
expect(page.locator("#preview-result iframe")).to_be_visible()
|
||||||
|
page.locator("[data-editor-mode=expert]").click()
|
||||||
|
source = page.locator("#document-source")
|
||||||
|
original = (site / "pages/index.md").read_text()
|
||||||
|
edited = original + "\nQA unsaved error check\n"
|
||||||
|
source.fill(edited)
|
||||||
|
with patch(
|
||||||
|
"site_engine.services.pages.PageService.save_source",
|
||||||
|
side_effect=RuntimeError("QA save failure"),
|
||||||
|
):
|
||||||
|
with page.expect_response(
|
||||||
|
lambda r: r.url.endswith("/admin/editor/pages/index/save")
|
||||||
|
) as failed:
|
||||||
|
page.get_by_role("button", name="Сохранить документ", exact=True).click()
|
||||||
|
assert failed.value.status == 500
|
||||||
|
expect(page.locator("#request-error")).to_contain_text("internal_error")
|
||||||
|
expect(source).to_have_value(edited)
|
||||||
|
expect(source).to_be_editable()
|
||||||
|
assert (site / "pages/index.md").read_text() == original
|
||||||
|
checks.append("save_500_preserves_exact_unsaved_source_and_releases_editor")
|
||||||
|
page.route("**/admin/editor/pages/index/save", lambda route: route.abort())
|
||||||
|
page.get_by_role("button", name="Сохранить документ", exact=True).click()
|
||||||
|
expect(page.locator("#request-error")).to_contain_text("network_error")
|
||||||
|
expect(source).to_have_value(edited)
|
||||||
|
expect(source).to_be_editable()
|
||||||
|
page.unroute("**/admin/editor/pages/index/save")
|
||||||
|
checks.append("network_failure_is_visible_and_preserves_unsaved_source")
|
||||||
|
page.get_by_role("button", name="Сохранить документ", exact=True).click()
|
||||||
|
expect(page.locator("#editor-result")).to_have_attribute("data-saved", "1")
|
||||||
|
assert (site / "pages/index.md").read_text() == edited
|
||||||
|
assert (dist / "current").resolve() == live
|
||||||
|
checks.append("save_recovers_after_failure_without_publishing")
|
||||||
|
page.goto(origin + "/admin/publish")
|
||||||
|
page.get_by_role("button", name="Опубликовать текущий черновик сайта").click()
|
||||||
|
with page.expect_response(
|
||||||
|
lambda r: r.url.endswith("/admin/publish") and r.request.method == "POST"
|
||||||
|
) as published:
|
||||||
|
page.locator("#confirm-dialog").get_by_role("button", name="Продолжить").click()
|
||||||
|
assert published.value.status == 200
|
||||||
|
assert (dist / "current").resolve() != live
|
||||||
|
expect(page.locator("#request-error")).to_be_hidden()
|
||||||
|
checks.append("publish_recovers_after_failure")
|
||||||
|
assert not errors, errors
|
||||||
|
assert not dialogs, dialogs
|
||||||
|
report = {
|
||||||
|
"browser": kind.name,
|
||||||
|
"checks": checks,
|
||||||
|
"browser_errors": errors,
|
||||||
|
"native_dialogs": dialogs,
|
||||||
|
}
|
||||||
|
(out / "report.json").write_text(
|
||||||
|
json.dumps(report, ensure_ascii=False, indent=2) + "\n"
|
||||||
|
)
|
||||||
|
print(json.dumps(report, ensure_ascii=False))
|
||||||
|
browser.close()
|
||||||
|
finally:
|
||||||
|
logger.removeHandler(captured)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -45,7 +45,27 @@ HTML-операции нового редактора: `/admin/editor/pages/{id}
|
|||||||
|
|
||||||
Снимок содержит kind/id/path/source/etag/model/schema/issues/revision; результат превью — URL, snapshot, expires_at и revision. ETag — `sha256:` от исходных байтов; проверка актуальной схемы и CAS выполняются под одним SiteLock вместе с history/atomic write. Изменение code/layouts/schemas через content scope запрещено, в том числе через symlink/traversal. Ошибка аудита после записи возвращает признак committed с сохранённым снимком и не выдаётся за отклонённый Save.
|
Снимок содержит kind/id/path/source/etag/model/schema/issues/revision; результат превью — URL, snapshot, expires_at и revision. ETag — `sha256:` от исходных байтов; проверка актуальной схемы и CAS выполняются под одним SiteLock вместе с history/atomic write. Изменение code/layouts/schemas через content scope запрещено, в том числе через symlink/traversal. Ошибка аудита после записи возвращает признак committed с сохранённым снимком и не выдаётся за отклонённый Save.
|
||||||
|
|
||||||
Ошибки API имеют `error: {code, message, issues, …}`; 409 дополнительно содержит submitted/current, 422 validation — неприменимый buffer либо диагностику. Лимит JSON-запроса — 1 MiB; source ограничен DTO и безопасным YAML-парсером. Неожиданная ошибка API возвращается без трассировки и секретов.
|
Ошибки API имеют `error: {code, message, request_id, issues, …}` с соответствующим HTTP-статусом; 409 дополнительно содержит submitted/current, 422 validation — неприменимый buffer либо диагностику. Лимит JSON-запроса — 1 MiB; source ограничен DTO и безопасным YAML-парсером. Неожиданная ошибка API возвращается без трассировки и внутренних путей.
|
||||||
|
|
||||||
|
Пример ответа HTTP 500 на `/admin/api/v1/publish`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"error": {
|
||||||
|
"code": "storage_error",
|
||||||
|
"message": "Ошибка доступа к файлам сервера. Проверьте права и свободное место. Проверьте текущую версию перед повтором операции.",
|
||||||
|
"request_id": "c4a857fd62774d688c5135d104ce3a51"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`X-Request-ID` присутствует в ответах приложения; ID сохраняется при внутреннем вызове API. Коды: `internal_error` — неожиданное исключение; `storage_error` — ошибка файловой системы; `request_validation`/`validation` — запрос/контент; `conflict` — несовпадение версии; `preview_unavailable` — недоступный snapshot. Серверный клиент преобразует отказ транспорта в HTTP 503 `api_unavailable`, некорректный ответ — в HTTP 502 `invalid_api_response`.
|
||||||
|
|
||||||
|
Неожиданные исключения пишутся через `logger.exception` в `uvicorn.error`: `request_failed request_id=… method=POST path=/admin/api/v1/publish code=storage_error`, затем traceback с исходным исключением и местом ошибки. Обработанные HTTP-ошибки дают `request_error` со статусом и кодом. Тело запроса, Authorization, cookies и query string не добавляются в эти записи. В Docker смотреть `docker logs --since 10m flexly-cms`; ID из интерфейса позволяет найти соответствующий стек.
|
||||||
|
|
||||||
|
HTML UI показывает сообщение, код и ID запроса. На публикации ошибку видно и без JavaScript; htmx показывает постоянное уведомление, которое закрывается пользователем. Подготовленная страница ошибки может заменить boosted-страницу; исходник документа при 5xx не заменяется. Отказ сети и timeout также видимы, автоматического повтора мутаций нет. Если после ошибки публикации недоступен список релизов, исходная ошибка операции сохраняется.
|
||||||
|
|
||||||
|
Проверка отказов на временной копии сайта: `PYTHONPATH=src python scripts/qa_errors_001.py`. Сценарий проверяет UI 500, общий ID с traceback, мобильное уведомление, сохранность несохранённого исходника при серверном и сетевом сбое и восстановление Save/Publish после устранения сбоя. Выход — `/tmp/cms-errors-qa/`; браузер — `QA_BROWSER=firefox`, каталог — `QA_ERRORS_OUT=/tmp/cms-errors-firefox`.
|
||||||
|
|
||||||
Схема и локальная страница документации доступны после входа: `/admin/api/v1/openapi.json`, `/admin/api/v1/docs`; сокращённые `/admin/api/openapi.json`, `/admin/api/docs` также работают. Воспроизводимый экспорт без секретов и работающего сайта:
|
Схема и локальная страница документации доступны после входа: `/admin/api/v1/openapi.json`, `/admin/api/v1/docs`; сокращённые `/admin/api/openapi.json`, `/admin/api/docs` также работают. Воспроизводимый экспорт без секретов и работающего сайта:
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,16 @@
|
|||||||
|
|
||||||
Ниже сохранены результаты функциональной реализации A–F. Действующий контракт и инструкции запуска: [runtime.md](runtime.md). Машиночитаемые результаты: [qa-results.json](qa-results.json), JSON-контракт: [openapi.json](openapi.json).
|
Ниже сохранены результаты функциональной реализации A–F. Действующий контракт и инструкции запуска: [runtime.md](runtime.md). Машиночитаемые результаты: [qa-results.json](qa-results.json), JSON-контракт: [openapi.json](openapi.json).
|
||||||
|
|
||||||
|
## Обработка ошибок — 13.11.2026
|
||||||
|
|
||||||
|
- Общая HTTP-граница возвращает JSON `error.code/message/request_id` для API, записывает неожиданные исключения со стеком в `uvicorn.error`. HTML-запрос и вложенные ASGI API-вызовы имеют один ID; тело запроса, cookies, Authorization и query string не добавляются в записи. Код и ID доступны в UI и заголовках ответа.
|
||||||
|
- Проверена настоящая ошибка файловой системы при сборке (`dist` занят файлом), а также инъекции `PermissionError`/`RuntimeError`: JSON 500, HTML-страница публикации и traceback содержат согласованный ID. Если загрузка релизов после неудачной операции тоже падает, сохраняется исходная ошибка, а недоступный список не выдаётся за пустой.
|
||||||
|
- **258 unit/integration-тестов — OK**. Регрессия запущена на временной копии studio-site; недоступный для чтения рабочий `pages/index.md` заменён версией из HEAD только во временной фикстуре. Пользовательские примеры и рабочие данные не изменены.
|
||||||
|
- **Chromium и Firefox: по 6 групп сценариев ошибок — OK**: ошибка публикации видна в странице/уведомлении на 1440 и 390 px; стек содержит ID из UI; 500 Save и обрыв сети сохраняют точный исходник и доступность редактора; последующие Save и Publish успешны. Нативных диалогов и необработанных JS-исключений нет. Исправлен также необработанный Promise отменённого preview-запроса при уходе со страницы.
|
||||||
|
- Обычная браузерная регрессия ai-studio в Chromium: **18 групп, 14 страниц × 5 ширин — OK**; проверены каталог, выбор секций, preview, сохранение, вход и выход.
|
||||||
|
- Ruff для изменённых Python-модулей/тестов/QA, `node --check` admin/editor JS, `git diff --check` — OK. Экспорт OpenAPI совпадает с runtime; ErrorBody включает обязательный `request_id`.
|
||||||
|
- Повторяемый сценарий: `PYTHONPATH=src python scripts/qa_errors_001.py`; отчёты и снимки — `/tmp/cms-errors-qa/`, Firefox — `/tmp/cms-errors-qa-firefox/`. Изменения на пользовательском сервере не разворачивались: для применения нужна пересборка образа и пересоздание контейнера. Причина исторической 500 на сервере по одной строке access log не установлена; новый обработчик сохраняет исходное исключение при повторении.
|
||||||
|
|
||||||
## Выполненные проверки
|
## Выполненные проверки
|
||||||
|
|
||||||
| Проверка | Результат |
|
| Проверка | Результат |
|
||||||
|
|||||||
@@ -5,11 +5,21 @@ from contextlib import asynccontextmanager
|
|||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
|
from ..error_handling import error_headers, log, request_id
|
||||||
|
|
||||||
|
|
||||||
class ApiError(Exception):
|
class ApiError(Exception):
|
||||||
def __init__(self, status: int, data: dict):
|
def __init__(self, status: int, data: dict):
|
||||||
self.status, self.data = status, data
|
self.status = status
|
||||||
super().__init__(data.get("error", {}).get("message", "Ошибка API"))
|
detail = {"code": "api_error", "message": "Ошибка API", "request_id": request_id()}
|
||||||
|
detail.update(data.get("error", {}))
|
||||||
|
self.data = {**data, "error": detail}
|
||||||
|
super().__init__(detail["message"])
|
||||||
|
|
||||||
|
def annotate(self, result):
|
||||||
|
result.headers.update(error_headers(self.data["error"]))
|
||||||
|
result.headers["X-Admin-Error"] = "1"
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
class AdminApi:
|
class AdminApi:
|
||||||
@@ -17,10 +27,47 @@ class AdminApi:
|
|||||||
self.client = client
|
self.client = client
|
||||||
|
|
||||||
async def call(self, method, path, data=None):
|
async def call(self, method, path, data=None):
|
||||||
response = await self.client.request(method, "/admin/api/v1" + path, json=data)
|
try:
|
||||||
|
response = await self.client.request(method, "/admin/api/v1" + path, json=data)
|
||||||
|
except httpx.RequestError:
|
||||||
|
log.exception(
|
||||||
|
"api_unavailable request_id=%s method=%s path=%s", request_id(), method, path
|
||||||
|
)
|
||||||
|
raise ApiError(
|
||||||
|
503,
|
||||||
|
{
|
||||||
|
"error": {
|
||||||
|
"code": "api_unavailable",
|
||||||
|
"message": "API недоступен. Проверьте текущую версию перед повтором.",
|
||||||
|
}
|
||||||
|
},
|
||||||
|
) from None
|
||||||
|
try:
|
||||||
|
payload = response.json()
|
||||||
|
if response.status_code >= 400:
|
||||||
|
detail = payload["error"]
|
||||||
|
if not isinstance(detail["code"], str) or not isinstance(detail["message"], str):
|
||||||
|
raise ValueError("Invalid API error contract")
|
||||||
|
except (ValueError, KeyError, TypeError):
|
||||||
|
log.exception(
|
||||||
|
"invalid_api_response request_id=%s method=%s path=%s status=%s",
|
||||||
|
request_id(),
|
||||||
|
method,
|
||||||
|
path,
|
||||||
|
response.status_code,
|
||||||
|
)
|
||||||
|
raise ApiError(
|
||||||
|
502,
|
||||||
|
{
|
||||||
|
"error": {
|
||||||
|
"code": "invalid_api_response",
|
||||||
|
"message": "API вернул некорректный ответ. Проверьте текущую версию перед повтором.",
|
||||||
|
}
|
||||||
|
},
|
||||||
|
) from None
|
||||||
if response.status_code >= 400:
|
if response.status_code >= 400:
|
||||||
raise ApiError(response.status_code, response.json())
|
raise ApiError(response.status_code, payload)
|
||||||
return response.json()
|
return payload
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
|
|||||||
@@ -69,7 +69,7 @@ class AdminApplication:
|
|||||||
def page(self, template, principal, section, status=200, **extra):
|
def page(self, template, principal, section, status=200, **extra):
|
||||||
return page_result(render(template, **self.ctx(principal, section, **extra)), status)
|
return page_result(render(template, **self.ctx(principal, section, **extra)), status)
|
||||||
|
|
||||||
def message(self, principal, text, status):
|
def message(self, principal, text, status, error=None):
|
||||||
return self.page(
|
return self.page(
|
||||||
"message.html.j2",
|
"message.html.j2",
|
||||||
principal,
|
principal,
|
||||||
@@ -79,6 +79,7 @@ class AdminApplication:
|
|||||||
text=text,
|
text=text,
|
||||||
issues=[],
|
issues=[],
|
||||||
links=[],
|
links=[],
|
||||||
|
error=error,
|
||||||
)
|
)
|
||||||
|
|
||||||
def editor_context(
|
def editor_context(
|
||||||
@@ -286,7 +287,9 @@ class AdminApplication:
|
|||||||
)
|
)
|
||||||
return await self.route(request, api, principal, form)
|
return await self.route(request, api, principal, form)
|
||||||
except ApiError as exc:
|
except ApiError as exc:
|
||||||
return self.message(principal, str(exc), exc.status)
|
return exc.annotate(
|
||||||
|
self.message(principal, str(exc), exc.status, exc.data["error"])
|
||||||
|
)
|
||||||
finally:
|
finally:
|
||||||
_navigation.reset(token)
|
_navigation.reset(token)
|
||||||
|
|
||||||
@@ -381,17 +384,19 @@ class AdminApplication:
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
except ApiError as exc:
|
except ApiError as exc:
|
||||||
data = await api.call("GET", "/site")
|
data = _navigation.get() or await api.call("GET", "/site")
|
||||||
return self.page(
|
return exc.annotate(
|
||||||
"pages_list.html.j2",
|
self.page(
|
||||||
principal,
|
"pages_list.html.j2",
|
||||||
"pages",
|
principal,
|
||||||
exc.status,
|
"pages",
|
||||||
**pages_view(data, {}),
|
exc.status,
|
||||||
create_open=True,
|
**pages_view(data, {}),
|
||||||
created=False,
|
create_open=True,
|
||||||
errors=[str(exc)],
|
created=False,
|
||||||
values={k: form.first(k) for k in ("page_id", "title", "layout")},
|
errors=[str(exc)],
|
||||||
|
values={k: form.first(k) for k in ("page_id", "title", "layout")},
|
||||||
|
)
|
||||||
)
|
)
|
||||||
return redirect_result(
|
return redirect_result(
|
||||||
"/admin/pages?selected=" + quote(snap["id"], safe="") + "&msg=created"
|
"/admin/pages?selected=" + quote(snap["id"], safe="") + "&msg=created"
|
||||||
@@ -423,16 +428,22 @@ class AdminApplication:
|
|||||||
"POST", f"/collections/{match[1]}/entries", {"id": form.first("slug").strip()}
|
"POST", f"/collections/{match[1]}/entries", {"id": form.first("slug").strip()}
|
||||||
)
|
)
|
||||||
except ApiError as exc:
|
except ApiError as exc:
|
||||||
|
if exc.status >= 500:
|
||||||
|
return exc.annotate(
|
||||||
|
self.message(principal, str(exc), exc.status, exc.data["error"])
|
||||||
|
)
|
||||||
data = await api.call("GET", f"/collections/{match[1]}/entries")
|
data = await api.call("GET", f"/collections/{match[1]}/entries")
|
||||||
return self.page(
|
return exc.annotate(
|
||||||
"entries_list.html.j2",
|
self.page(
|
||||||
principal,
|
"entries_list.html.j2",
|
||||||
"content",
|
principal,
|
||||||
exc.status,
|
"content",
|
||||||
**data,
|
exc.status,
|
||||||
errors=[str(exc)],
|
**data,
|
||||||
slug=form.first("slug"),
|
errors=[str(exc)],
|
||||||
filters={},
|
slug=form.first("slug"),
|
||||||
|
filters={},
|
||||||
|
)
|
||||||
)
|
)
|
||||||
return redirect_result(f"/admin/content/{match[1]}/{snap['id']}")
|
return redirect_result(f"/admin/content/{match[1]}/{snap['id']}")
|
||||||
if path == "/publish" or path.startswith("/publish/rollback/"):
|
if path == "/publish" or path.startswith("/publish/rollback/"):
|
||||||
@@ -445,22 +456,22 @@ class AdminApplication:
|
|||||||
data = await api.call("POST" if post else "GET", endpoint)
|
data = await api.call("POST" if post else "GET", endpoint)
|
||||||
return self.page("publish.html.j2", principal, "publish", **data, issues=[])
|
return self.page("publish.html.j2", principal, "publish", **data, issues=[])
|
||||||
except ApiError as exc:
|
except ApiError as exc:
|
||||||
data = await api.call("GET", "/releases")
|
navigation = _navigation.get() or {}
|
||||||
return self.page(
|
data = {"current": navigation.get("current"), "builds": []}
|
||||||
"publish.html.j2",
|
try:
|
||||||
principal,
|
data = await api.call("GET", "/releases")
|
||||||
"publish",
|
except ApiError:
|
||||||
exc.status,
|
data["releases_unavailable"] = True
|
||||||
**data,
|
return exc.annotate(
|
||||||
issues=exc.data["error"].get("issues")
|
self.page(
|
||||||
or [
|
"publish.html.j2",
|
||||||
{
|
principal,
|
||||||
"code": "E_OPERATION",
|
"publish",
|
||||||
"message": str(exc),
|
exc.status,
|
||||||
"path": "",
|
**data,
|
||||||
"severity": "error",
|
issues=exc.data["error"].get("issues") or [],
|
||||||
}
|
error=exc.data["error"],
|
||||||
],
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
# HTML editor endpoints mirror the document path and operation; JSON paths remain separate.
|
# HTML editor endpoints mirror the document path and operation; JSON paths remain separate.
|
||||||
@@ -636,7 +647,7 @@ class AdminApplication:
|
|||||||
)
|
)
|
||||||
if err.get("committed"):
|
if err.get("committed"):
|
||||||
result.headers["X-Document-Committed"] = "1"
|
result.headers["X-Document-Committed"] = "1"
|
||||||
return result
|
return exc.annotate(result)
|
||||||
|
|
||||||
def form_action(self, snap, form, legacy="", block_id=""):
|
def form_action(self, snap, form, legacy="", block_id=""):
|
||||||
op = (
|
op = (
|
||||||
|
|||||||
@@ -6,6 +6,40 @@
|
|||||||
let menuInvoker;
|
let menuInvoker;
|
||||||
const compact = matchMedia('(max-width: 760px)');
|
const compact = matchMedia('(max-width: 760px)');
|
||||||
const rail = matchMedia('(max-width: 1050px)');
|
const rail = matchMedia('(max-width: 1050px)');
|
||||||
|
function showRequestError(error, status) {
|
||||||
|
const box = document.getElementById('request-error');
|
||||||
|
if (!box) return;
|
||||||
|
box.querySelector('[data-request-error-message]').textContent = error.message || 'Не удалось выполнить запрос.';
|
||||||
|
box.querySelector('[data-request-error-details]').textContent = [
|
||||||
|
status ? 'HTTP ' + status : '', error.code || 'http_error',
|
||||||
|
error.request_id ? 'ID запроса: ' + error.request_id : ''
|
||||||
|
].filter(Boolean).join(' · ');
|
||||||
|
box.hidden = false;
|
||||||
|
}
|
||||||
|
function xhrError(xhr) {
|
||||||
|
try { const value = JSON.parse(xhr.responseText); if (value.error?.message) return value.error; } catch (_) {}
|
||||||
|
try { const value = JSON.parse(xhr.getResponseHeader('HX-Trigger')); if (value?.['admin:error']) return value['admin:error']; } catch (_) {}
|
||||||
|
return {
|
||||||
|
code: xhr.getResponseHeader('X-Error-Code') || 'http_error',
|
||||||
|
message: 'Не удалось выполнить запрос. Проверьте текущую версию перед повтором.',
|
||||||
|
request_id: xhr.getResponseHeader('X-Request-ID')
|
||||||
|
};
|
||||||
|
}
|
||||||
|
document.addEventListener('htmx:beforeSwap', event => {
|
||||||
|
const detail = event.detail;
|
||||||
|
// Only replace a boosted page with a deliberately rendered error page. Keep editor buffers intact.
|
||||||
|
if (detail.xhr.status >= 500 && detail.xhr.getResponseHeader('X-Admin-Error') === '1'
|
||||||
|
&& detail.requestConfig?.boosted && detail.target === document.body) {
|
||||||
|
detail.shouldSwap = true;
|
||||||
|
detail.isError = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
document.addEventListener('htmx:afterRequest', event => {
|
||||||
|
const xhr = event.detail.xhr;
|
||||||
|
if (xhr.status >= 400) showRequestError(xhrError(xhr), xhr.status);
|
||||||
|
});
|
||||||
|
document.addEventListener('htmx:sendError', () => showRequestError({code:'network_error', message:'Нет связи с сервером. Правки остаются в редакторе. Проверьте текущую версию перед повтором.'}));
|
||||||
|
document.addEventListener('htmx:timeout', () => showRequestError({code:'request_timeout', message:'Время ожидания ответа истекло. Проверьте текущую версию перед повтором операции.'}));
|
||||||
function updateCollapse() {
|
function updateCollapse() {
|
||||||
const narrow = document.getElementById('app')?.classList.contains('narrow');
|
const narrow = document.getElementById('app')?.classList.contains('narrow');
|
||||||
document.querySelector('[data-action="collapse"]')?.setAttribute('aria-expanded', String(compact.matches || (rail.matches ? narrow : !narrow)));
|
document.querySelector('[data-action="collapse"]')?.setAttribute('aria-expanded', String(compact.matches || (rail.matches ? narrow : !narrow)));
|
||||||
@@ -58,6 +92,7 @@
|
|||||||
document.querySelectorAll('form[action^="/admin/publish/rollback/"]').forEach(form => form.dataset.confirm = 'Вернуть выбранный релиз? Рабочие файлы сохранятся.');
|
document.querySelectorAll('form[action^="/admin/publish/rollback/"]').forEach(form => form.dataset.confirm = 'Вернуть выбранный релиз? Рабочие файлы сохранятся.');
|
||||||
}
|
}
|
||||||
document.addEventListener('click', event => {
|
document.addEventListener('click', event => {
|
||||||
|
if (event.target.closest('[data-close-request-error]')) document.getElementById('request-error').hidden = true;
|
||||||
const close = event.target.closest('[data-close-dialog]');
|
const close = event.target.closest('[data-close-dialog]');
|
||||||
if (close) { event.preventDefault(); close.closest('dialog').close(); }
|
if (close) { event.preventDefault(); close.closest('dialog').close(); }
|
||||||
const opener = event.target.closest('[data-open-modal]');
|
const opener = event.target.closest('[data-open-modal]');
|
||||||
|
|||||||
@@ -44,7 +44,10 @@
|
|||||||
revision:current.rev, mode:current.mode, selection:current.selection, readonly:current.readonlySelection};}
|
revision:current.rev, mode:current.mode, selection:current.selection, readonly:current.readonlySelection};}
|
||||||
function requestPreview() {
|
function requestPreview() {
|
||||||
if (!current || !window.htmx || current.busy || one('#editor-result')?.dataset.valid !== '1') return;
|
if (!current || !window.htmx || current.busy || one('#editor-result')?.dataset.valid !== '1') return;
|
||||||
htmx.ajax('POST', '/admin/editor' + current.root.dataset.base + '/preview', {target:'#preview-result', swap:'outerHTML', values:params()});
|
const state=current;
|
||||||
|
htmx.ajax('POST', '/admin/editor' + current.root.dataset.base + '/preview', {target:'#preview-result', swap:'outerHTML', values:params()}).catch(()=>{
|
||||||
|
if(current===state && state.root.isConnected) notice('Превью недоступно. Правки остаются в редакторе.');
|
||||||
|
});
|
||||||
}
|
}
|
||||||
function formValues(form, submitter) {
|
function formValues(form, submitter) {
|
||||||
const data=new FormData(form), values={};
|
const data=new FormData(form), values={};
|
||||||
@@ -172,7 +175,10 @@
|
|||||||
if(current.inspectorDirty||current.busy){notice('Сначала примените изменения инспектора.');return;}
|
if(current.inspectorDirty||current.busy){notice('Сначала примените изменения инспектора.');return;}
|
||||||
current.selection=block.scope==='page'?block.id:'';
|
current.selection=block.scope==='page'?block.id:'';
|
||||||
current.readonlySelection=block.scope==='page'?'':JSON.stringify(block);
|
current.readonlySelection=block.scope==='page'?'':JSON.stringify(block);
|
||||||
htmx.ajax('POST','/admin/editor'+current.root.dataset.base+'/select',{target:'#editor-result',swap:'outerHTML',values:params()});
|
const state=current;
|
||||||
|
htmx.ajax('POST','/admin/editor'+current.root.dataset.base+'/select',{target:'#editor-result',swap:'outerHTML',values:params()}).catch(()=>{
|
||||||
|
if(current===state && state.root.isConnected) notice('Не удалось выбрать блок. Правки остаются в редакторе.');
|
||||||
|
});
|
||||||
}
|
}
|
||||||
function passivePreview(frame) {
|
function passivePreview(frame) {
|
||||||
const state=current,p=state?.preview;
|
const state=current,p=state?.preview;
|
||||||
|
|||||||
@@ -28,6 +28,10 @@
|
|||||||
.shell-dialog [hidden] { display: none !important; }
|
.shell-dialog [hidden] { display: none !important; }
|
||||||
/* Native dialog supplies modal focus/semantics; dimensions and contents match the design. */
|
/* Native dialog supplies modal focus/semantics; dimensions and contents match the design. */
|
||||||
.shell-dialog header .header-btn { flex: none; }
|
.shell-dialog header .header-btn { flex: none; }
|
||||||
|
.request-error { max-width: min(460px,calc(100vw - 32px)); overflow-wrap: anywhere; }
|
||||||
|
.request-error[hidden] { display: none; }
|
||||||
|
.request-error p { margin: 0 0 8px; }
|
||||||
|
.request-error button { background: transparent; color: inherit; border: 1px solid currentColor; padding: 4px 8px; cursor: pointer; }
|
||||||
/* Runtime build IDs are timestamp/hash values, longer than the mock's r00027. */
|
/* Runtime build IDs are timestamp/hash values, longer than the mock's r00027. */
|
||||||
@media(max-width:900px) { .live-pip .mono { max-width: 70px; } }
|
@media(max-width:900px) { .live-pip .mono { max-width: 70px; } }
|
||||||
@media(max-width:760px) {
|
@media(max-width:760px) {
|
||||||
|
|||||||
@@ -15,6 +15,7 @@
|
|||||||
</head>
|
</head>
|
||||||
<body data-skin='light'{% block bodyattrs %}{% endblock %}>
|
<body data-skin='light'{% block bodyattrs %}{% endblock %}>
|
||||||
{% block body %}{% endblock %}
|
{% block body %}{% endblock %}
|
||||||
|
<div class='toast request-error' id='request-error' role='alert' aria-atomic='true' hidden><p data-request-error-message></p><p data-request-error-details></p><button type='button' data-close-request-error>Закрыть</button></div>
|
||||||
{% block scripts %}{% endblock %}
|
{% block scripts %}{% endblock %}
|
||||||
<script src='{{ static_url("admin.js") }}' defer></script>
|
<script src='{{ static_url("admin.js") }}' defer></script>
|
||||||
<script src='{{ static_url("pages.js") }}' defer></script>
|
<script src='{{ static_url("pages.js") }}' defer></script>
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
{% block content %}
|
{% block content %}
|
||||||
<h1>{{ title }}</h1>
|
<h1>{{ title }}</h1>
|
||||||
{% if text %}<p>{{ text }}</p>{% endif %}
|
{% if text %}<p>{{ text }}</p>{% endif %}
|
||||||
|
{% if error|default(none) %}<p>Код: <code>{{ error.code }}</code> · ID запроса: <code>{{ error.request_id }}</code></p>{% endif %}
|
||||||
{% if issues %}
|
{% if issues %}
|
||||||
<ul class='issues'>
|
<ul class='issues'>
|
||||||
{% for i in issues %}<li class='{{ i.severity }}'><code>{{ i.code }}</code> {{ i.path }} {{ i.message }}{% if i.hint %} <small>({{ i.hint }})</small>{% endif %}</li>{% endfor %}
|
{% for i in issues %}<li class='{{ i.severity }}'><code>{{ i.code }}</code> {{ i.path }} {{ i.message }}{% if i.hint %} <small>({{ i.hint }})</small>{% endif %}</li>{% endfor %}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
{% block title %}Публикация — админка{% endblock %}
|
{% block title %}Публикация — админка{% endblock %}
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<h1>Публикация</h1>
|
<h1>Публикация</h1>
|
||||||
|
{% if error|default(none) %}<ul class='issues' role='alert'><li class='error'>{{ error.message }}<br>Код: <code>{{ error.code }}</code> · ID запроса: <code>{{ error.request_id }}</code></li></ul>{% endif %}
|
||||||
{% if issues %}
|
{% if issues %}
|
||||||
<h2>Проблемы сборки</h2>
|
<h2>Проблемы сборки</h2>
|
||||||
<ul class='issues'>{% for i in issues %}<li class='{{ i.severity }}'><code>{{ i.code }}</code> {{ i.path }} {{ i.message }}</li>{% endfor %}</ul>
|
<ul class='issues'>{% for i in issues %}<li class='{{ i.severity }}'><code>{{ i.code }}</code> {{ i.path }} {{ i.message }}</li>{% endfor %}</ul>
|
||||||
@@ -25,7 +26,7 @@
|
|||||||
</form>{% endif %}</td>
|
</form>{% endif %}</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% else %}
|
{% else %}
|
||||||
<tr><td colspan='2'>Релизов пока нет</td></tr>
|
<tr><td colspan='2'>{% if releases_unavailable|default(false) %}Список релизов недоступен. Обновите страницу после устранения ошибки.{% else %}Релизов пока нет{% endif %}</td></tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
|
|||||||
@@ -94,6 +94,7 @@ class Create(DTO):
|
|||||||
class ErrorBody(DTO):
|
class ErrorBody(DTO):
|
||||||
code: str
|
code: str
|
||||||
message: str
|
message: str
|
||||||
|
request_id: str
|
||||||
revision: int | None = None
|
revision: int | None = None
|
||||||
submitted_source: str | None = None
|
submitted_source: str | None = None
|
||||||
base_etag: str | None = None
|
base_etag: str | None = None
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ from fastapi import APIRouter, Depends, Request
|
|||||||
from fastapi.exceptions import RequestValidationError
|
from fastapi.exceptions import RequestValidationError
|
||||||
from fastapi.responses import HTMLResponse, JSONResponse, Response
|
from fastapi.responses import HTMLResponse, JSONResponse, Response
|
||||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||||
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||||
|
|
||||||
from ...core.models import STATUSES
|
from ...core.models import STATUSES
|
||||||
from ...errors import ConflictError, EngineError, UnsafePathError
|
from ...errors import ConflictError, EngineError, UnsafePathError
|
||||||
@@ -17,6 +18,7 @@ from ...services.preview import asset_path
|
|||||||
from ...services.publish import publish, rollback
|
from ...services.publish import publish, rollback
|
||||||
from ...services.workspace import entries, filter_pages, releases, workspace
|
from ...services.workspace import entries, filter_pages, releases, workspace
|
||||||
from ...storage.locks import SiteLock
|
from ...storage.locks import SiteLock
|
||||||
|
from ..error_handling import error_response, log, request_id
|
||||||
from .models import (
|
from .models import (
|
||||||
Buffer,
|
Buffer,
|
||||||
CollectionRow,
|
CollectionRow,
|
||||||
@@ -62,7 +64,9 @@ def install_api(app, auth, root, dist, previews):
|
|||||||
router = APIRouter(
|
router = APIRouter(
|
||||||
prefix="/admin/api/v1",
|
prefix="/admin/api/v1",
|
||||||
dependencies=[Depends(context)],
|
dependencies=[Depends(context)],
|
||||||
responses={s: {"model": ErrorEnvelope} for s in (401, 403, 404, 409, 422, 500)},
|
responses={
|
||||||
|
s: {"model": ErrorEnvelope} for s in (400, 401, 403, 404, 405, 409, 413, 422, 500)
|
||||||
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
def service(kind, collection=""):
|
def service(kind, collection=""):
|
||||||
@@ -79,11 +83,7 @@ def install_api(app, auth, root, dist, previews):
|
|||||||
"submitted_source": buffer.get("source"),
|
"submitted_source": buffer.get("source"),
|
||||||
"base_etag": buffer.get("etag"),
|
"base_etag": buffer.get("etag"),
|
||||||
}
|
}
|
||||||
return JSONResponse(
|
return error_response(status, code, message, **{"issues": [], **details, **extra})
|
||||||
{"error": {"code": code, "message": str(message), "issues": [], **details, **extra}},
|
|
||||||
status_code=status,
|
|
||||||
headers={"Cache-Control": "no-store"},
|
|
||||||
)
|
|
||||||
|
|
||||||
def invoke(fn, svc=None, identity=None, buf=None):
|
def invoke(fn, svc=None, identity=None, buf=None):
|
||||||
try:
|
try:
|
||||||
@@ -103,6 +103,7 @@ def install_api(app, auth, root, dist, previews):
|
|||||||
current=current,
|
current=current,
|
||||||
)
|
)
|
||||||
except AuditCommitError as exc:
|
except AuditCommitError as exc:
|
||||||
|
log.exception("audit_after_commit request_id=%s", request_id())
|
||||||
return error(
|
return error(
|
||||||
500,
|
500,
|
||||||
"audit_after_commit",
|
"audit_after_commit",
|
||||||
@@ -211,13 +212,23 @@ def install_api(app, auth, root, dist, previews):
|
|||||||
def preview_html(snapshot: str, token: str = ""):
|
def preview_html(snapshot: str, token: str = ""):
|
||||||
from ..preview_app import snapshot_response
|
from ..preview_app import snapshot_response
|
||||||
|
|
||||||
return snapshot_response(previews, snapshot, token)
|
response = snapshot_response(previews, snapshot, token)
|
||||||
|
return (
|
||||||
|
error(403, "preview_unavailable", "Превью недоступно")
|
||||||
|
if response.status_code >= 400
|
||||||
|
else response
|
||||||
|
)
|
||||||
|
|
||||||
@router.get("/preview/{snapshot}/assets/{asset:path}", response_class=Response)
|
@router.get("/preview/{snapshot}/assets/{asset:path}", response_class=Response)
|
||||||
def preview_asset(snapshot: str, asset: str, token: str = ""):
|
def preview_asset(snapshot: str, asset: str, token: str = ""):
|
||||||
from ..preview_app import snapshot_response
|
from ..preview_app import snapshot_response
|
||||||
|
|
||||||
return snapshot_response(previews, snapshot, token, asset)
|
response = snapshot_response(previews, snapshot, token, asset)
|
||||||
|
return (
|
||||||
|
error(403, "preview_unavailable", "Превью недоступно")
|
||||||
|
if response.status_code >= 400
|
||||||
|
else response
|
||||||
|
)
|
||||||
|
|
||||||
@router.post("/pages", response_model=Snapshot, status_code=201)
|
@router.post("/pages", response_model=Snapshot, status_code=201)
|
||||||
def page_create(body: Create, ctx: Ctx):
|
def page_create(body: Create, ctx: Ctx):
|
||||||
@@ -324,14 +335,7 @@ def install_api(app, auth, root, dist, previews):
|
|||||||
if len(chunks) > 1048576:
|
if len(chunks) > 1048576:
|
||||||
return error(413, "body_too_large", "Максимум 1 MiB")
|
return error(413, "body_too_large", "Максимум 1 MiB")
|
||||||
request._body = bytes(chunks)
|
request._body = bytes(chunks)
|
||||||
try:
|
response = await call_next(request)
|
||||||
response = await call_next(request)
|
|
||||||
except Exception: # noqa: BLE001 — HTTP boundary must return a content-free error envelope.
|
|
||||||
return error(
|
|
||||||
500,
|
|
||||||
"internal_error",
|
|
||||||
"Ошибка сервера. Проверьте текущую версию перед повтором.",
|
|
||||||
)
|
|
||||||
response.headers["Cache-Control"] = "no-store"
|
response.headers["Cache-Control"] = "no-store"
|
||||||
response.headers["X-Content-Type-Options"] = "nosniff"
|
response.headers["X-Content-Type-Options"] = "nosniff"
|
||||||
return response
|
return response
|
||||||
@@ -347,9 +351,11 @@ def install_api(app, auth, root, dist, previews):
|
|||||||
|
|
||||||
app.openapi = contract_schema
|
app.openapi = contract_schema
|
||||||
|
|
||||||
@app.exception_handler(HTTPException)
|
@app.exception_handler(StarletteHTTPException)
|
||||||
async def http_error(request, exc):
|
async def http_error(request, exc):
|
||||||
return error(exc.status_code, "http_error", exc.detail)
|
response = error(exc.status_code, "http_error", exc.detail)
|
||||||
|
response.headers.update(exc.headers or {})
|
||||||
|
return response
|
||||||
|
|
||||||
@app.exception_handler(RequestValidationError)
|
@app.exception_handler(RequestValidationError)
|
||||||
async def validation_error(request, exc):
|
async def validation_error(request, exc):
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ def create_app():
|
|||||||
from ..services.preview import PreviewConfig, PreviewStore
|
from ..services.preview import PreviewConfig, PreviewStore
|
||||||
from .admin.handlers import AdminHandlers
|
from .admin.handlers import AdminHandlers
|
||||||
from .admin.routes import create_admin_router
|
from .admin.routes import create_admin_router
|
||||||
|
from .error_handling import RequestErrorMiddleware
|
||||||
|
|
||||||
app = FastAPI(title="Site Engine", docs_url=None, redoc_url=None, openapi_url=None)
|
app = FastAPI(title="Site Engine", docs_url=None, redoc_url=None, openapi_url=None)
|
||||||
paths = SitePaths.from_env()
|
paths = SitePaths.from_env()
|
||||||
@@ -83,4 +84,5 @@ def create_app():
|
|||||||
return FileResponse(target, status_code=404)
|
return FileResponse(target, status_code=404)
|
||||||
return PlainTextResponse("Не найдено", status_code=404)
|
return PlainTextResponse("Не найдено", status_code=404)
|
||||||
|
|
||||||
|
app.add_middleware(RequestErrorMiddleware)
|
||||||
return app
|
return app
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
"""HTTP error contracts, request correlation and server-side exception logging."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from contextvars import ContextVar
|
||||||
|
from html import escape
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from fastapi.responses import HTMLResponse, JSONResponse
|
||||||
|
from starlette.datastructures import MutableHeaders
|
||||||
|
|
||||||
|
log = logging.getLogger("uvicorn.error")
|
||||||
|
_request_id = ContextVar("request_id", default="")
|
||||||
|
|
||||||
|
|
||||||
|
def request_id():
|
||||||
|
return _request_id.get()
|
||||||
|
|
||||||
|
|
||||||
|
def error_headers(error):
|
||||||
|
detail = {
|
||||||
|
"code": error["code"],
|
||||||
|
"message": error["message"],
|
||||||
|
"request_id": error.get("request_id") or request_id(),
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
"Cache-Control": "no-store",
|
||||||
|
"X-Content-Type-Options": "nosniff",
|
||||||
|
"X-Error-Code": detail["code"],
|
||||||
|
"X-Request-ID": detail["request_id"],
|
||||||
|
"HX-Trigger": json.dumps({"admin:error": detail}, ensure_ascii=True),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def error_response(status, code, message, **extra):
|
||||||
|
detail = {"code": code, "message": str(message), "request_id": request_id(), **extra}
|
||||||
|
return JSONResponse({"error": detail}, status_code=status, headers=error_headers(detail))
|
||||||
|
|
||||||
|
|
||||||
|
class RequestErrorMiddleware:
|
||||||
|
"""Share IDs with nested ASGI API calls; never log bodies, cookies or query strings."""
|
||||||
|
|
||||||
|
def __init__(self, app):
|
||||||
|
self.app = app
|
||||||
|
|
||||||
|
async def __call__(self, scope, receive, send):
|
||||||
|
if scope["type"] != "http":
|
||||||
|
return await self.app(scope, receive, send)
|
||||||
|
correlation = request_id() or uuid4().hex
|
||||||
|
token = _request_id.set(correlation)
|
||||||
|
started = False
|
||||||
|
status, code = 200, ""
|
||||||
|
|
||||||
|
async def send_response(message):
|
||||||
|
nonlocal started, status, code
|
||||||
|
if message["type"] == "http.response.start":
|
||||||
|
started = True
|
||||||
|
status = message["status"]
|
||||||
|
headers = MutableHeaders(scope=message)
|
||||||
|
headers["X-Request-ID"] = correlation
|
||||||
|
code = headers.get("X-Error-Code", "http_error")
|
||||||
|
await send(message)
|
||||||
|
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
await self.app(scope, receive, send_response)
|
||||||
|
except Exception as exc:
|
||||||
|
code = "storage_error" if isinstance(exc, OSError) else "internal_error"
|
||||||
|
log.exception(
|
||||||
|
"request_failed request_id=%s method=%s path=%s code=%s",
|
||||||
|
correlation,
|
||||||
|
scope["method"],
|
||||||
|
scope["path"],
|
||||||
|
code,
|
||||||
|
)
|
||||||
|
if started:
|
||||||
|
raise
|
||||||
|
message = (
|
||||||
|
"Ошибка доступа к файлам сервера. Проверьте права и свободное место. "
|
||||||
|
if code == "storage_error"
|
||||||
|
else "Внутренняя ошибка сервера. "
|
||||||
|
) + "Проверьте текущую версию перед повтором операции."
|
||||||
|
response = error_response(500, code, message)
|
||||||
|
headers = dict(scope.get("headers", []))
|
||||||
|
if not scope["path"].startswith("/admin/api/") and not headers.get(b"hx-request"):
|
||||||
|
from .admin.handlers import ADMIN_HEADERS
|
||||||
|
|
||||||
|
response = HTMLResponse(
|
||||||
|
"<!doctype html><html lang='ru'><meta charset='utf-8'>"
|
||||||
|
"<title>Ошибка сервера</title><h1>Ошибка сервера</h1>"
|
||||||
|
f"<p>{escape(message)}</p><p>Код: <code>{code}</code></p>"
|
||||||
|
f"<p>ID запроса: <code>{correlation}</code></p>"
|
||||||
|
"<p><a href='/admin/'>Вернуться в админку</a></p></html>",
|
||||||
|
status_code=500,
|
||||||
|
headers={
|
||||||
|
**ADMIN_HEADERS,
|
||||||
|
**error_headers(
|
||||||
|
{
|
||||||
|
"code": code,
|
||||||
|
"message": message,
|
||||||
|
"request_id": correlation,
|
||||||
|
}
|
||||||
|
),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
await response(scope, receive, send_response)
|
||||||
|
else:
|
||||||
|
if status >= 400:
|
||||||
|
log.warning(
|
||||||
|
"request_error request_id=%s method=%s path=%s status=%s code=%s",
|
||||||
|
correlation,
|
||||||
|
scope["method"],
|
||||||
|
scope["path"],
|
||||||
|
status,
|
||||||
|
code,
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
_request_id.reset(token)
|
||||||
@@ -52,6 +52,104 @@ class ApiTests(SiteTestCase):
|
|||||||
def source(self):
|
def source(self):
|
||||||
return self.api("GET", "/pages/index/source").json()
|
return self.api("GET", "/pages/index/source").json()
|
||||||
|
|
||||||
|
def test_unexpected_publish_error_has_json_code_request_id_and_traceback(self):
|
||||||
|
with (
|
||||||
|
patch("site_engine.web.api.routes.publish", side_effect=RuntimeError("publish probe")),
|
||||||
|
self.assertLogs("uvicorn.error", level="ERROR") as captured,
|
||||||
|
):
|
||||||
|
response = self.api("POST", "/publish")
|
||||||
|
self.assertEqual(response.status_code, 500)
|
||||||
|
detail = response.json()["error"]
|
||||||
|
self.assertEqual(detail["code"], "internal_error")
|
||||||
|
self.assertTrue(detail["message"])
|
||||||
|
self.assertRegex(detail["request_id"], r"^[a-f0-9]{32}$")
|
||||||
|
self.assertEqual(response.headers["x-request-id"], detail["request_id"])
|
||||||
|
self.assertIn("no-store", response.headers["cache-control"])
|
||||||
|
self.assertNotIn("publish probe", response.text)
|
||||||
|
output = "\n".join(captured.output)
|
||||||
|
self.assertIn(detail["request_id"], output)
|
||||||
|
self.assertIn("POST", output)
|
||||||
|
self.assertIn("/admin/api/v1/publish", output)
|
||||||
|
self.assertIn("RuntimeError: publish probe", output)
|
||||||
|
self.assertTrue(any(record.exc_info for record in captured.records))
|
||||||
|
self.assertNotIn(self.password, output)
|
||||||
|
self.assertNotIn("test-credential", output)
|
||||||
|
|
||||||
|
def test_real_publish_storage_failure_reaches_html_and_logs(self):
|
||||||
|
# A file instead of the release directory causes a real filesystem failure on every OS.
|
||||||
|
self.out.write_text("occupied by a file")
|
||||||
|
with self.assertLogs("uvicorn.error", level="ERROR") as captured:
|
||||||
|
response = self.client.post(
|
||||||
|
"/admin/publish",
|
||||||
|
data={"csrf": self.csrf},
|
||||||
|
headers={"Origin": "http://testserver", "HX-Request": "true", "HX-Boosted": "true"},
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 500)
|
||||||
|
self.assertEqual(response.headers["x-error-code"], "storage_error")
|
||||||
|
self.assertEqual(response.headers["x-admin-error"], "1")
|
||||||
|
self.assertIn("Ошибка доступа к файлам", response.text)
|
||||||
|
self.assertIn(response.headers["x-request-id"], response.text)
|
||||||
|
self.assertIn(response.headers["x-request-id"], "\n".join(captured.output))
|
||||||
|
self.assertIn("FileExistsError", "\n".join(captured.output))
|
||||||
|
self.assertEqual(self.out.read_text(), "occupied by a file")
|
||||||
|
|
||||||
|
def test_publish_error_keeps_original_error_if_release_listing_also_fails(self):
|
||||||
|
from site_engine.web.admin.api_client import AdminApi, ApiError
|
||||||
|
|
||||||
|
original = AdminApi.call
|
||||||
|
|
||||||
|
async def failing(api, method, path, data=None):
|
||||||
|
if path == "/publish":
|
||||||
|
raise ApiError(
|
||||||
|
500, {"error": {"code": "publish_failed", "message": "Publish failure"}}
|
||||||
|
)
|
||||||
|
if path == "/releases" and getattr(api, "listed", False):
|
||||||
|
raise ApiError(
|
||||||
|
500, {"error": {"code": "list_failed", "message": "Listing failure"}}
|
||||||
|
)
|
||||||
|
if path == "/releases":
|
||||||
|
api.listed = True
|
||||||
|
return await original(api, method, path, data)
|
||||||
|
|
||||||
|
with patch.object(AdminApi, "call", failing):
|
||||||
|
response = self.client.post(
|
||||||
|
"/admin/publish", data={"csrf": self.csrf}, headers={"Origin": "http://testserver"}
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 500)
|
||||||
|
self.assertIn("Publish failure", response.text)
|
||||||
|
self.assertNotIn("Listing failure", response.text)
|
||||||
|
self.assertIn("Список релизов недоступен", response.text)
|
||||||
|
self.assertEqual(response.headers["x-error-code"], "publish_failed")
|
||||||
|
|
||||||
|
def test_validation_and_http_errors_include_correlation(self):
|
||||||
|
for response in (
|
||||||
|
self.api("POST", "/pages", {}),
|
||||||
|
self.api("DELETE", "/publish"),
|
||||||
|
self.api("GET", "/preview/" + "a" * 32 + "/html"),
|
||||||
|
self.client.get("/admin/api/v1/site"),
|
||||||
|
):
|
||||||
|
self.assertGreaterEqual(response.status_code, 400)
|
||||||
|
detail = response.json()["error"]
|
||||||
|
self.assertTrue(detail["code"])
|
||||||
|
self.assertTrue(detail["message"])
|
||||||
|
self.assertEqual(response.headers["x-request-id"], detail["request_id"])
|
||||||
|
|
||||||
|
def test_unexpected_login_error_is_visible_and_logged(self):
|
||||||
|
with (
|
||||||
|
patch.object(self.app.state.auth, "login", side_effect=RuntimeError("login probe")),
|
||||||
|
self.assertLogs("uvicorn.error", level="ERROR") as captured,
|
||||||
|
):
|
||||||
|
response = self.client.post(
|
||||||
|
"/admin/login",
|
||||||
|
data={"login": "admin", "password": self.password},
|
||||||
|
headers={"Origin": "http://testserver"},
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 500)
|
||||||
|
self.assertIn("internal_error", response.text)
|
||||||
|
self.assertIn(response.headers["x-request-id"], response.text)
|
||||||
|
self.assertIn("RuntimeError: login probe", "\n".join(captured.output))
|
||||||
|
self.assertNotIn(self.password, "\n".join(captured.output))
|
||||||
|
|
||||||
def test_fragment_names_and_descriptions_reach_catalog_through_api(self):
|
def test_fragment_names_and_descriptions_reach_catalog_through_api(self):
|
||||||
fragments = self.source()["schema"]["fragments"]
|
fragments = self.source()["schema"]["fragments"]
|
||||||
expected = {
|
expected = {
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
"""Failures in the UI-to-API transport must remain actionable API errors."""
|
||||||
|
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from site_engine.web.admin.api_client import AdminApi, ApiError
|
||||||
|
|
||||||
|
|
||||||
|
class ApiClientTests(unittest.IsolatedAsyncioTestCase):
|
||||||
|
async def test_invalid_error_payloads_do_not_expose_raw_response(self):
|
||||||
|
for raw in (
|
||||||
|
b"sensitive upstream response",
|
||||||
|
b"null",
|
||||||
|
b"[]",
|
||||||
|
b'{"error":{"message":"missing code"}}',
|
||||||
|
):
|
||||||
|
with self.subTest(raw=raw):
|
||||||
|
transport = httpx.MockTransport(
|
||||||
|
lambda request, raw=raw: httpx.Response(500, content=raw)
|
||||||
|
)
|
||||||
|
async with httpx.AsyncClient(
|
||||||
|
transport=transport, base_url="http://internal"
|
||||||
|
) as client:
|
||||||
|
with (
|
||||||
|
self.assertLogs("uvicorn.error", level="ERROR") as logs,
|
||||||
|
self.assertRaises(ApiError) as captured,
|
||||||
|
):
|
||||||
|
await AdminApi(client).call("POST", "/publish")
|
||||||
|
self.assertEqual(captured.exception.status, 502)
|
||||||
|
self.assertEqual(captured.exception.data["error"]["code"], "invalid_api_response")
|
||||||
|
self.assertNotIn(raw.decode(), str(captured.exception))
|
||||||
|
self.assertNotIn("sensitive upstream response", "\n".join(logs.output))
|
||||||
|
|
||||||
|
async def test_api_transport_failure_becomes_service_unavailable(self):
|
||||||
|
def unavailable(request):
|
||||||
|
raise httpx.ConnectError("connection probe", request=request)
|
||||||
|
|
||||||
|
async with httpx.AsyncClient(
|
||||||
|
transport=httpx.MockTransport(unavailable), base_url="http://internal"
|
||||||
|
) as client:
|
||||||
|
with (
|
||||||
|
self.assertLogs("uvicorn.error", level="ERROR") as logs,
|
||||||
|
self.assertRaises(ApiError) as captured,
|
||||||
|
):
|
||||||
|
await AdminApi(client).call("POST", "/publish")
|
||||||
|
self.assertEqual(captured.exception.status, 503)
|
||||||
|
self.assertEqual(captured.exception.data["error"]["code"], "api_unavailable")
|
||||||
|
self.assertIn("ConnectError", "\n".join(logs.output))
|
||||||
Reference in New Issue
Block a user