diff --git a/AGENTS.md b/AGENTS.md index 26aaca3..a09820e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,6 +27,7 @@ - В каталоге 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`: блокировка, проверка версии, валидация, история, атомарная запись. - Для нового 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 сайта не запускается. Обычная сборка не получает служебную разметку. - Приём публичных форм пока возвращает HTTP 501; MCP и changeset — заготовки. Не показывай успешную отправку без работающего обработчика. - Проверяй мобильную и широкую версии, клавиатурную навигацию, фокус, подписи полей и контраст. Анимации учитывают `prefers-reduced-motion`. diff --git a/scripts/qa_errors_001.py b/scripts/qa_errors_001.py new file mode 100644 index 0000000..5233aed --- /dev/null +++ b/scripts/qa_errors_001.py @@ -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() diff --git a/specs/001-antirion-admin/openapi.json b/specs/001-antirion-admin/openapi.json index d6a7cd0..b3f19d6 100644 --- a/specs/001-antirion-admin/openapi.json +++ b/specs/001-antirion-admin/openapi.json @@ -346,6 +346,10 @@ "title": "Message", "type": "string" }, + "request_id": { + "title": "Request Id", + "type": "string" + }, "revision": { "anyOf": [ { @@ -381,7 +385,8 @@ }, "required": [ "code", - "message" + "message", + "request_id" ], "title": "ErrorBody", "type": "object" @@ -975,6 +980,16 @@ "200": { "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -1005,6 +1020,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -1015,6 +1040,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -1062,6 +1097,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -1092,6 +1137,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -1102,6 +1157,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -1176,6 +1241,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -1206,6 +1281,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -1216,6 +1301,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -1278,6 +1373,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -1308,6 +1413,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -1318,6 +1433,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -1391,6 +1516,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -1421,6 +1556,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -1431,6 +1576,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -1504,6 +1659,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -1534,6 +1699,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -1544,6 +1719,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -1607,6 +1792,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -1637,6 +1832,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -1647,6 +1852,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -1720,6 +1935,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -1750,6 +1975,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -1760,6 +1995,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -1833,6 +2078,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -1863,6 +2118,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -1873,6 +2138,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -1946,6 +2221,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -1976,6 +2261,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -1986,6 +2281,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -2059,6 +2364,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -2089,6 +2404,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -2099,6 +2424,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -2162,6 +2497,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -2192,6 +2537,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -2202,6 +2557,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -2275,6 +2640,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -2305,6 +2680,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -2315,6 +2700,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -2388,6 +2783,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -2418,6 +2823,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -2428,6 +2843,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -2492,6 +2917,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -2522,6 +2957,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -2532,6 +2977,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -2596,6 +3051,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -2626,6 +3091,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -2636,6 +3111,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -2690,6 +3175,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -2720,6 +3215,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -2730,6 +3235,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -2794,6 +3309,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -2824,6 +3349,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -2834,6 +3369,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -2898,6 +3443,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -2928,6 +3483,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -2938,6 +3503,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -3012,6 +3587,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -3042,6 +3627,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -3052,6 +3647,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -3114,6 +3719,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -3144,6 +3759,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -3154,6 +3779,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -3243,6 +3878,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -3273,6 +3918,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -3283,6 +3938,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -3334,6 +3999,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -3364,6 +4039,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -3374,6 +4059,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -3438,6 +4133,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -3468,6 +4173,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -3478,6 +4193,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -3542,6 +4267,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -3572,6 +4307,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -3582,6 +4327,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -3636,6 +4391,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -3666,6 +4431,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -3676,6 +4451,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -3740,6 +4525,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -3770,6 +4565,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -3780,6 +4585,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -3844,6 +4659,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -3874,6 +4699,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -3884,6 +4719,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -3950,6 +4795,16 @@ "200": { "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -3980,6 +4835,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -3990,6 +4855,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -4047,6 +4922,16 @@ "200": { "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -4077,6 +4962,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -4087,6 +4982,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -4130,6 +5035,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -4160,6 +5075,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -4170,6 +5095,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -4213,6 +5148,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -4243,6 +5188,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -4253,6 +5208,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -4306,6 +5271,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -4336,6 +5311,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -4346,6 +5331,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -4400,6 +5395,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -4430,6 +5435,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -4440,6 +5455,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { @@ -4483,6 +5508,16 @@ }, "description": "Successful Response" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Bad Request" + }, "401": { "content": { "application/json": { @@ -4513,6 +5548,16 @@ }, "description": "Not Found" }, + "405": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Method Not Allowed" + }, "409": { "content": { "application/json": { @@ -4523,6 +5568,16 @@ }, "description": "Conflict" }, + "413": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + }, + "description": "Request Entity Too Large" + }, "422": { "content": { "application/json": { diff --git a/specs/001-antirion-admin/runtime.md b/specs/001-antirion-admin/runtime.md index c24dd0f..35a2e65 100644 --- a/specs/001-antirion-admin/runtime.md +++ b/specs/001-antirion-admin/runtime.md @@ -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. -Ошибки 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` также работают. Воспроизводимый экспорт без секретов и работающего сайта: diff --git a/specs/001-antirion-admin/verification.md b/specs/001-antirion-admin/verification.md index 506651f..4ee927a 100644 --- a/specs/001-antirion-admin/verification.md +++ b/specs/001-antirion-admin/verification.md @@ -6,6 +6,16 @@ Ниже сохранены результаты функциональной реализации 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 не установлена; новый обработчик сохраняет исходное исключение при повторении. + ## Выполненные проверки | Проверка | Результат | diff --git a/src/site_engine/web/admin/api_client.py b/src/site_engine/web/admin/api_client.py index 6b8d864..d090c15 100644 --- a/src/site_engine/web/admin/api_client.py +++ b/src/site_engine/web/admin/api_client.py @@ -5,11 +5,21 @@ from contextlib import asynccontextmanager import httpx +from ..error_handling import error_headers, log, request_id + class ApiError(Exception): def __init__(self, status: int, data: dict): - self.status, self.data = status, data - super().__init__(data.get("error", {}).get("message", "Ошибка API")) + self.status = status + 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: @@ -17,10 +27,47 @@ class AdminApi: self.client = client 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: - raise ApiError(response.status_code, response.json()) - return response.json() + raise ApiError(response.status_code, payload) + return payload @asynccontextmanager diff --git a/src/site_engine/web/admin/application.py b/src/site_engine/web/admin/application.py index 06589ef..55b923a 100644 --- a/src/site_engine/web/admin/application.py +++ b/src/site_engine/web/admin/application.py @@ -69,7 +69,7 @@ class AdminApplication: def page(self, template, principal, section, status=200, **extra): 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( "message.html.j2", principal, @@ -79,6 +79,7 @@ class AdminApplication: text=text, issues=[], links=[], + error=error, ) def editor_context( @@ -286,7 +287,9 @@ class AdminApplication: ) return await self.route(request, api, principal, form) 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: _navigation.reset(token) @@ -381,17 +384,19 @@ class AdminApplication: }, ) except ApiError as exc: - data = await api.call("GET", "/site") - return self.page( - "pages_list.html.j2", - principal, - "pages", - exc.status, - **pages_view(data, {}), - create_open=True, - created=False, - errors=[str(exc)], - values={k: form.first(k) for k in ("page_id", "title", "layout")}, + data = _navigation.get() or await api.call("GET", "/site") + return exc.annotate( + self.page( + "pages_list.html.j2", + principal, + "pages", + exc.status, + **pages_view(data, {}), + create_open=True, + created=False, + errors=[str(exc)], + values={k: form.first(k) for k in ("page_id", "title", "layout")}, + ) ) return redirect_result( "/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()} ) 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") - return self.page( - "entries_list.html.j2", - principal, - "content", - exc.status, - **data, - errors=[str(exc)], - slug=form.first("slug"), - filters={}, + return exc.annotate( + self.page( + "entries_list.html.j2", + principal, + "content", + exc.status, + **data, + errors=[str(exc)], + slug=form.first("slug"), + filters={}, + ) ) return redirect_result(f"/admin/content/{match[1]}/{snap['id']}") if path == "/publish" or path.startswith("/publish/rollback/"): @@ -445,22 +456,22 @@ class AdminApplication: data = await api.call("POST" if post else "GET", endpoint) return self.page("publish.html.j2", principal, "publish", **data, issues=[]) except ApiError as exc: - data = await api.call("GET", "/releases") - return self.page( - "publish.html.j2", - principal, - "publish", - exc.status, - **data, - issues=exc.data["error"].get("issues") - or [ - { - "code": "E_OPERATION", - "message": str(exc), - "path": "", - "severity": "error", - } - ], + navigation = _navigation.get() or {} + data = {"current": navigation.get("current"), "builds": []} + try: + data = await api.call("GET", "/releases") + except ApiError: + data["releases_unavailable"] = True + return exc.annotate( + self.page( + "publish.html.j2", + principal, + "publish", + exc.status, + **data, + issues=exc.data["error"].get("issues") or [], + error=exc.data["error"], + ) ) # HTML editor endpoints mirror the document path and operation; JSON paths remain separate. @@ -636,7 +647,7 @@ class AdminApplication: ) if err.get("committed"): result.headers["X-Document-Committed"] = "1" - return result + return exc.annotate(result) def form_action(self, snap, form, legacy="", block_id=""): op = ( diff --git a/src/site_engine/web/admin/static/admin.js b/src/site_engine/web/admin/static/admin.js index 1858c80..68cd85e 100644 --- a/src/site_engine/web/admin/static/admin.js +++ b/src/site_engine/web/admin/static/admin.js @@ -6,6 +6,40 @@ let menuInvoker; const compact = matchMedia('(max-width: 760px)'); 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() { const narrow = document.getElementById('app')?.classList.contains('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.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]'); if (close) { event.preventDefault(); close.closest('dialog').close(); } const opener = event.target.closest('[data-open-modal]'); diff --git a/src/site_engine/web/admin/static/editor.js b/src/site_engine/web/admin/static/editor.js index 92baea5..713dae3 100644 --- a/src/site_engine/web/admin/static/editor.js +++ b/src/site_engine/web/admin/static/editor.js @@ -44,7 +44,10 @@ revision:current.rev, mode:current.mode, selection:current.selection, readonly:current.readonlySelection};} function requestPreview() { 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) { const data=new FormData(form), values={}; @@ -172,7 +175,10 @@ if(current.inspectorDirty||current.busy){notice('Сначала примените изменения инспектора.');return;} current.selection=block.scope==='page'?block.id:''; 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) { const state=current,p=state?.preview; diff --git a/src/site_engine/web/admin/static/shell.css b/src/site_engine/web/admin/static/shell.css index 8a5c971..798833f 100644 --- a/src/site_engine/web/admin/static/shell.css +++ b/src/site_engine/web/admin/static/shell.css @@ -28,6 +28,10 @@ .shell-dialog [hidden] { display: none !important; } /* Native dialog supplies modal focus/semantics; dimensions and contents match the design. */ .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. */ @media(max-width:900px) { .live-pip .mono { max-width: 70px; } } @media(max-width:760px) { diff --git a/src/site_engine/web/admin/templates/base.html.j2 b/src/site_engine/web/admin/templates/base.html.j2 index d5d570e..fbdc1ab 100644 --- a/src/site_engine/web/admin/templates/base.html.j2 +++ b/src/site_engine/web/admin/templates/base.html.j2 @@ -15,6 +15,7 @@
{% block body %}{% endblock %} +{{ text }}
{% endif %} +{% if error|default(none) %}Код: {{ error.code }} · ID запроса: {{ error.request_id }}
{{ i.code }} {{ i.path }} {{ i.message }}{% if i.hint %} ({{ i.hint }}){% endif %}{{ error.code }} · ID запроса: {{ error.request_id }}{{ i.code }} {{ i.path }} {{ i.message }}{escape(message)}
Код: {code}
ID запроса: {correlation}