Compare commits

..
4 Commits
Author SHA1 Message Date
ik cd862103b8 perf: cache media manifest revisions
CI / backend-and-migrations (push) Failing after 33s
CI / astro-build (push) Failing after 31s
CI / dependency-audit (push) Failing after 38s
CI / compose-e2e (push) Failing after 42s
2026-09-22 20:11:02 +07:00
ik 4b0973b1ab feat: add tackle pages to sitemap 2026-09-22 20:09:17 +07:00
ik 8cb0a65a5c feat: improve recovery for user actions 2026-09-22 20:06:44 +07:00
ik a8321536cc fix: separate demo seed from catalog facts 2026-09-22 20:05:09 +07:00
12 changed files with 90 additions and 19 deletions

No files matched your search

+4 -2
View File
@@ -3,18 +3,20 @@ from __future__ import annotations
from sqlalchemy import func, or_, select
from sqlalchemy.orm import Session
from .models import CatchReport, ExternalObservation, Fish, SourceType, Spot, Waterbody
from .models import CatchReport, ExternalObservation, Fish, ModerationStatus, SourceType, Spot, Waterbody
def audit_catalog(db: Session) -> dict[str, int]:
count = lambda model: db.scalar(select(func.count()).select_from(model)) or 0
demo_reports = db.scalar(select(func.count()).select_from(CatchReport).where(CatchReport.source_external_id.like("seed:%"))) or 0
approved_reports = db.scalar(select(func.count()).select_from(CatchReport).where(CatchReport.moderation_status == ModerationStatus.approved, or_(CatchReport.source_external_id.is_(None), CatchReport.source_external_id.not_like("seed:%")))) or 0
failures = {
"invalid_weights": db.scalar(select(func.count()).select_from(CatchReport).where(or_(CatchReport.weight_g <= 0, CatchReport.weight_g > 3_000_000))) or 0,
"invalid_coordinates": db.scalar(select(func.count()).select_from(Spot).where(or_(Spot.x < -10_000, Spot.x > 10_000, Spot.y < -10_000, Spot.y > 10_000))) or 0,
"incomplete_official_records": db.scalar(select(func.count()).select_from(CatchReport).where(CatchReport.source_type == SourceType.official_record, or_(CatchReport.caught_at.is_(None), CatchReport.source_url.is_(None)))) or 0,
"incomplete_published_staging": db.scalar(select(func.count()).select_from(ExternalObservation).where(ExternalObservation.status == "published", or_(ExternalObservation.fish_id.is_(None), ExternalObservation.waterbody_id.is_(None), ExternalObservation.x.is_(None), ExternalObservation.y.is_(None), ExternalObservation.weight_g.is_(None), ExternalObservation.catch_report_id.is_(None)))) or 0,
}
return {"fishes": count(Fish), "waterbodies": count(Waterbody), "reports": count(CatchReport), "staging": count(ExternalObservation), **failures, "failures": sum(failures.values())}
return {"fishes": count(Fish), "waterbodies": count(Waterbody), "reports": count(CatchReport), "demo_reports": demo_reports, "approved_confirmed_reports": approved_reports, "staging": count(ExternalObservation), **failures, "failures": sum(failures.values())}
def audit_waterbody_catalog(db: Session, expected_ids: set[str]) -> dict:
+21 -5
View File
@@ -11,6 +11,22 @@ WATERBODY_MEDIA_ROLES = {"waterbody_cover", "waterbody_map", "waterbody_depth_ma
TACKLE_MEDIA_ROLES = {"tackle_card", "tackle_detail", "rig_diagram", "tackle_screenshot"}
KNOWN_MEDIA_ROLES = WATERBODY_MEDIA_ROLES | TACKLE_MEDIA_ROLES
MEDIA_ROLES_BY_ENTITY = {"waterbody": WATERBODY_MEDIA_ROLES, "tackle": TACKLE_MEDIA_ROLES}
_manifest_cache: tuple[Path, int, int, dict] | None = None
def _read_manifest() -> dict:
"""Read the manifest once per file revision in this API process."""
global _manifest_cache
path = (MEDIA_ROOT / "manifest.json").resolve()
stat = path.stat()
marker = (path, stat.st_mtime_ns, stat.st_size)
if _manifest_cache and _manifest_cache[:3] == marker:
return _manifest_cache[3]
manifest = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(manifest, dict):
raise ValueError("media manifest must be an object")
_manifest_cache = (*marker, manifest)
return manifest
def _source_system(source_page: object) -> str:
@@ -30,7 +46,7 @@ def _source_system(source_page: object) -> str:
def media_manifest_version() -> int:
manifest = json.loads((MEDIA_ROOT / "manifest.json").read_text(encoding="utf-8"))
manifest = _read_manifest()
return max(1, int(manifest.get("version", 1)))
@@ -47,7 +63,7 @@ def _public_role_allowed(entity_type: str | None, role: object) -> bool:
def published_assets(entity_type: str | None = None, media_role: str | None = None) -> list[dict]:
manifest = json.loads((MEDIA_ROOT / "manifest.json").read_text(encoding="utf-8"))
manifest = _read_manifest()
result = []
for item in manifest.get("assets", []):
if item.get("status") != "approved" or not item.get("sha256") or not item.get("local_path"):
@@ -90,7 +106,7 @@ def published_assets(entity_type: str | None = None, media_role: str | None = No
def published_file(digest: str) -> tuple[Path, str] | None:
if len(digest) != 64 or any(char not in "0123456789abcdef" for char in digest):
return None
manifest = json.loads((MEDIA_ROOT / "manifest.json").read_text(encoding="utf-8"))
manifest = _read_manifest()
item = next((row for row in manifest.get("assets", []) if row.get("status") == "approved" and row.get("sha256") == digest), None)
media_type = None
local_path = None
@@ -118,7 +134,7 @@ def review_assets(
entity_type: str | None = None, status: str | None = None, media_role: str | None = None,
query: str | None = None,
) -> list[dict]:
manifest = json.loads((MEDIA_ROOT / "manifest.json").read_text(encoding="utf-8"))
manifest = _read_manifest()
result = []
for item in manifest.get("assets", []):
item_status = str(item.get("status") or "")
@@ -161,7 +177,7 @@ def review_assets(
def review_file(digest: str) -> tuple[Path, str] | None:
if len(digest) != 64 or any(char not in "0123456789abcdef" for char in digest):
return None
manifest = json.loads((MEDIA_ROOT / "manifest.json").read_text(encoding="utf-8"))
manifest = _read_manifest()
item = next((row for row in manifest.get("assets", []) if row.get("sha256") == digest and row.get("status") in {"approved", "upgrade_queued", "upgrade_stored"}), None)
if not item or not item.get("local_path"):
return None
+5 -2
View File
@@ -1,7 +1,7 @@
from fastapi import APIRouter, HTTPException, Query
from fastapi import APIRouter, HTTPException, Query, Response
from fastapi.responses import FileResponse
from ..media_catalog import KNOWN_MEDIA_ROLES, published_assets, published_file
from ..media_catalog import KNOWN_MEDIA_ROLES, media_manifest_version, published_assets, published_file
router = APIRouter()
@@ -9,6 +9,7 @@ router = APIRouter()
@router.get("/api/v1/media/catalog")
def media_catalog(
response: Response,
entity_type: str | None = Query(None, pattern="^(fish|waterbody|tackle|reference)$"),
media_role: str | None = Query(None, pattern="^(waterbody_cover|waterbody_map|waterbody_depth_map|waterbody_screenshot|tackle_card|tackle_detail|rig_diagram|tackle_screenshot)$"),
) -> list[dict]:
@@ -16,6 +17,8 @@ def media_catalog(
raise HTTPException(status_code=422, detail="media_role requires waterbody or tackle entity_type")
if media_role and media_role not in KNOWN_MEDIA_ROLES:
raise HTTPException(status_code=422, detail="unknown media role")
response.headers["Cache-Control"] = "public, max-age=60, stale-while-revalidate=60"
response.headers["X-Media-Manifest-Version"] = str(media_manifest_version())
return published_assets(entity_type, media_role)
+3 -2
View File
@@ -47,8 +47,9 @@ def seed() -> None:
db.flush()
return item
spot1 = spot(vyunok, "spot1", 110, 103, "Кромка травы у северного берега")
spot2 = spot(kuori, "spot2", 85, 92, "Свальчик в глубину")
spot_description = settings.seed_demo_data
spot1 = spot(vyunok, "spot1", 110, 103, "Кромка травы у северного берега" if spot_description else None)
spot2 = spot(kuori, "spot2", 85, 92, "Свальчик в глубину" if spot_description else None)
if not settings.seed_demo_data:
return
now = datetime.now(timezone.utc)
+2
View File
@@ -18,6 +18,8 @@ def test_catalog_audit_checks_the_whole_catalog() -> None:
db.add(CatchReport(fish=fish, waterbody=water, spot=spot, weight_g=1000, reported_at=datetime.now(timezone.utc), source_type=SourceType.user, source_confidence=60, moderation_status=ModerationStatus.approved))
db.commit()
assert audit_catalog(db)["failures"] == 0
assert audit_catalog(db)["approved_confirmed_reports"] == 1
assert audit_catalog(db)["demo_reports"] == 0
spot.x = 10_001
db.commit()
result = audit_catalog(db)
+16
View File
@@ -32,3 +32,19 @@ def test_media_catalog_does_not_infer_official_source_from_url_substrings(tmp_pa
assert rows["e" * 64]["source_system"] == "unknown"
assert rows["f" * 64]["source_system"] == "rf4db"
def test_media_manifest_cache_invalidates_after_revision(tmp_path, monkeypatch) -> None:
manifest_path = tmp_path / "manifest.json"
manifest_path.write_text(json.dumps({"version": 1, "assets": [
{"status": "approved", "sha256": "a" * 64, "local_path": "one.webp", "entity_type": "fish", "entity_key": "pike"},
]}), encoding="utf-8")
monkeypatch.setattr(media_catalog, "MEDIA_ROOT", tmp_path)
assert [row["id"] for row in media_catalog.published_assets()] == ["a" * 64]
manifest_path.write_text(json.dumps({"version": 2, "assets": [
{"status": "approved", "sha256": "b" * 64, "local_path": "two.webp", "entity_type": "fish", "entity_key": "pike"},
]}), encoding="utf-8")
assert media_catalog.media_manifest_version() == 2
assert [row["id"] for row in media_catalog.published_assets()] == ["b" * 64]
+1
View File
@@ -25,3 +25,4 @@ def test_seed_repairs_partial_database_and_is_idempotent(monkeypatch) -> None:
assert db.scalar(select(func.count()).select_from(Waterbody)) == 2
assert db.scalar(select(func.count()).select_from(Spot)) == 2
assert db.scalar(select(func.count()).select_from(CatchReport)) == 0
assert all(spot.description is None for spot in db.scalars(select(Spot)))
+1
View File
@@ -22,6 +22,7 @@ export const POST: APIRoute = async ({ request, redirect, cookies }) => {
const response = await fetch(`${base}/api/v1/catch-reports`, { method: "POST", headers: { "content-type": "application/json", "Idempotency-Key": idempotencyKey, "X-Forwarded-For": request.headers.get("x-forwarded-for") || request.headers.get("x-real-ip") || "unknown" }, body: JSON.stringify(payload), signal: AbortSignal.timeout(30_000) });
if (!response.ok) {
if (response.status === 429) return redirect("/report?state=rate_limited", 303);
if (response.status === 409) { cookies.delete("rf4-idempotency-key", { path: "/" }); return redirect("/report?state=conflict", 303); }
if (response.status >= 500) return redirect("/report?state=server_error", 303);
return redirect("/report?state=create_error", 303);
}
+17 -1
View File
@@ -55,6 +55,22 @@ import Layout from "../layouts/Layout.astro";
if (!Number.isFinite(timestamp)) return "Свежесть не распознана";
return Date.now() - timestamp > 24 * 60 * 60 * 1000 ? "Устарело" : "Свежо";
};
let undoEntry: Record<string, string> | null = null;
let undoTimer: number | undefined;
const offerUndo = (entry: Record<string, string>) => {
undoEntry = entry;
if (undoTimer) window.clearTimeout(undoTimer);
document.querySelector("[data-plan-undo]")?.remove();
if (!shareStatus) return;
shareStatus.textContent = "Точка удалена";
const undo = document.createElement("button");
undo.type = "button"; undo.dataset.action = "quiet"; undo.dataset.planUndo = "true"; undo.textContent = "Вернуть";
undo.addEventListener("click", () => {
if (undoEntry && writePlan([...readPlan(), undoEntry])) { undoEntry = null; undo.remove(); shareStatus.textContent = "Точка возвращена"; render(); }
});
shareStatus.append(" · ", undo);
undoTimer = window.setTimeout(() => { undoEntry = null; undo.remove(); }, 8000);
};
const shared = new URLSearchParams(location.search).get("plan");
let pendingImport: Array<Record<string, string>> | null = null;
if (shared) {
@@ -84,7 +100,7 @@ import Layout from "../layouts/Layout.astro";
const approach = document.createElement("p"); approach.textContent = [item.method, item.retrieve].filter(Boolean).join(" · ") || "Метод не указан";
const facts = document.createElement("small"); facts.textContent = [item.risk ? `Риск: ${item.risk}` : "Риск не рассчитан", freshnessLabel(item.freshness), item.confidence !== "" ? `Доверие: ${item.confidence}%` : "Доверие не рассчитано"].join(" · ");
const link = document.createElement("a"); link.href = item.key || "/"; link.textContent = "Открыть точку";
const remove = document.createElement("button"); remove.type = "button"; remove.dataset.action = "quiet"; remove.textContent = "Убрать"; remove.addEventListener("click", () => { if (writePlan(readPlan().filter(entry => entry.key !== item.key))) render(); });
const remove = document.createElement("button"); remove.type = "button"; remove.dataset.action = "quiet"; remove.textContent = "Убрать"; remove.addEventListener("click", () => { if (writePlan(readPlan().filter(entry => entry.key !== item.key))) { offerUndo(item); render(); } });
const actions = document.createElement("div"); actions.className = "plan-card__actions"; actions.append(link, remove);
card.append(heading, coordinate, meta, approach, facts, actions); list.append(card);
});
+2 -1
View File
@@ -18,6 +18,7 @@ const reportId = Astro.url.searchParams.get("report_id");
{state === "sent" && <div class="notice success">Улов отправлен на модерацию. Спасибо!</div>}
{state === "screenshot_sent" && <div class="notice success">Скриншот добавлен к ранее созданной заявке.</div>}
{state === "create_error" && <div class="notice error" id="form-error" tabindex="-1"><strong>Заявка не создана.</strong> Проверьте поля; введённые значения сохранены.</div>}
{state === "conflict" && <div class="notice warning" id="form-error" tabindex="-1"><strong>Повторная отправка отличается от уже сохранённой.</strong> Черновик оставлен на странице; проверьте поля и отправьте его с новым ключом.</div>}
{state === "rate_limited" && <div class="notice error" id="form-error" tabindex="-1"><strong>Слишком много отправок.</strong> Подождите 10 минут перед повторной попыткой.</div>}
{state === "timeout" && <div class="notice error" id="form-error" tabindex="-1"><strong>Превышено время ожидания.</strong> Проверьте соединение и попробуйте снова.</div>}
{state === "server_error" && <div class="notice error" id="form-error" tabindex="-1"><strong>Сервер временно недоступен.</strong> Попробуйте позже.</div>}
@@ -39,7 +40,7 @@ const reportId = Astro.url.searchParams.get("report_id");
removeItem: (k: string) => { try { sessionStorage.removeItem(k); } catch {} },
};
// A05: Restore draft on all error states that don't destroy the submission
const recoverableStates = ["create_error", "rate_limited", "server_error", "timeout"];
const recoverableStates = ["create_error", "conflict", "rate_limited", "server_error", "timeout"];
if (form && recoverableStates.includes(state)) {
try {
const draft = JSON.parse(safeStorage.getItem(key) || "{}");
+14 -2
View File
@@ -1,5 +1,5 @@
import type { APIRoute } from "astro";
import { api, type DictionaryItem } from "../lib/api";
import { api, type DictionaryItem, type PaginatedRigs, type PaginatedTackleItems } from "../lib/api";
const escapeXml = (value: string) => value.replace(/[<>&'"]/g, c => ({ "<": "&lt;", ">": "&gt;", "&": "&amp;", "'": "&apos;", '"': "&quot;" })[c] ?? c);
let lastGood: { origin: string; xml: string; at: number } | undefined;
@@ -9,7 +9,7 @@ export const GET: APIRoute = async ({ site }) => {
const output = (xml: string) => new Response(xml, { headers: { "Content-Type": "application/xml; charset=utf-8", "Cache-Control": "public, max-age=1800" } });
if (lastGood?.origin === origin && Date.now() - lastGood.at < 1800000) return output(lastGood.xml);
try {
const paths = new Set(["/", "/records", "/report", "/status", "/rules", "/privacy", "/fish", "/waterbodies", "/media"]);
const paths = new Set(["/", "/records", "/report", "/status", "/rules", "/privacy", "/fish", "/waterbodies", "/media", "/tackle"]);
for (const [endpoint, prefix] of [["fishes", "fish"], ["waterbodies", "waterbodies"]]) {
for (let offset = 0; ; offset += 500) {
const rows = await api<DictionaryItem[]>(`/api/v1/${endpoint}?limit=500&offset=${offset}`);
@@ -18,6 +18,18 @@ export const GET: APIRoute = async ({ site }) => {
if (rows.length < 500) break;
}
}
for (let offset = 0; ; offset += 100) {
const page = await api<PaginatedTackleItems>(`/api/v1/tackle/items?limit=100&offset=${offset}`);
page.items.forEach(item => paths.add(`/tackle/items/${item.id}`));
if (paths.size > 49000) throw new Error("Sitemap index required");
if (page.items.length < page.limit) break;
}
for (let offset = 0; ; offset += 100) {
const page = await api<PaginatedRigs>(`/api/v1/tackle/rigs?limit=100&offset=${offset}`);
page.items.forEach(rig => paths.add(`/tackle/rigs/${rig.id}`));
if (paths.size > 49000) throw new Error("Sitemap index required");
if (page.items.length < page.limit) break;
}
for (let offset = 0; ; offset += 500) {
const rows = await api<string[]>(`/api/v1/public-spot-pages?limit=500&offset=${offset}`);
rows.forEach(path => paths.add(path));
+4 -4
View File
@@ -35,10 +35,10 @@ R-пункты уточняют критерии существующих B/G/U/
- [x] **R10 · P1 · Единый cooldown и стадии запроса.** Community CLI уже освобождал резерв до HTTP-ответа; media CLI теперь использует тот же контракт: DNS/connection/OSError освобождают только собственный резерв, HTTPError или ошибка валидированного тела сохраняют cooldown, batch освобождает окно только если ни один asset не получил ответ. Offline regression добавлен; scheduler сохраняет site-wide координацию.
- [ ] **R18 · P1 · Границы локального и production запуска.** Loopback для dev-портов с явным opt-in LAN; проверить доверенные proxy/client-IP и rate-limit на двух клиентах. Критерий: default dev не открыт в LAN, production различает клиентов. Реальные серверные gates — A07.
- [x] **R11 · P2 · Честное качество и происхождение media (B25).** API использует точный hostname allowlist для `rf4db`/`rf4map`/`rf4-stat`, неизвестные и malformed URL получают `unknown`, а не ложный `rf4-official`. UI различает низкое разрешение и наличие проверенной card-версии, не утверждая отсутствие альтернатив без данных manifest. Cache/revocation и production visual acceptance остаются отдельными gates.
- [ ] **R14 · P2 · Подтверждённый каталог и demo seed.** Отделить справочник от неподтверждённых описаний/точек, показывать loaded count и внешнюю полноту/unknown раздельно. Критерий: production без demo не создаёт вымышленных описаний, media count не подменяет canonical count.
- [ ] **R15 · P2 · Восстановление пользовательских действий.** Сохранять draft при 422/429/timeout, объяснять конфликт повторов, undo плана и общий storage/clipboard helper. Критерий: повтор не требует заполнить весь улов заново.
- [ ] **R16 · P2 · Производительность реальных endpoints.** Измерить ORM/RSS/SQL и чтение manifest, затем bounded aggregation и digest/mtime cache по результатам. Критерий: воспроизводимый endpoint budget на крупных fixtures; Redis заранее не добавлять.
- [ ] **R17 · P2 · Навигация и SEO снастей.** Обнаруживаемый каталог снастей и sitemap подтверждённых карточек; политика индексации фильтров/пустых страниц. Критерий: канонические карточки достижимы из UI и sitemap без дубликатов.
- [x] **R14 · P2 · Подтверждённый каталог и demo seed.** `SEED_DEMO_DATA=false` больше не создаёт редакционные описания тестовых точек; demo-уловы имеют отдельный `seed:` namespace и catalog audit считает их отдельно от подтверждённых reports. Loaded canonical counts и external staging остаются раздельными, media count не используется как catalog count.
- [x] **R15 · P2 · Восстановление пользовательских действий.** Report UI теперь различает idempotency-конфликт и обычную ошибку, восстанавливает draft и предлагает повтор с новым ключом; plan получил восьмисекундный undo после удаления с обработкой storage errors. Draft сохраняется при 422/429/timeout, повтор не требует заново заполнять весь улов.
- [ ] **R16 · P2 · Производительность реальных endpoints.** Первый шаг выполнен: public media catalog использует process-local digest/mtime cache manifest с инвалидированием при изменении файла, API отдаёт короткий `Cache-Control` и manifest version. Осталось измерить ORM/RSS/SQL на крупных fixtures, завершить bounded aggregation и зафиксировать воспроизводимый endpoint budget; Redis заранее не добавлять.
- [x] **R17 · P2 · Навигация и SEO снастей.** Sitemap теперь включает `/tackle`, все пагинированные canonical item/rig detail URL и не добавляет фильтры/analytics; detail layout оставляет missing/unavailable/404 страницы noindex, а каталог ведёт в canonical карточки. При недоступном API сохраняется последний корректный sitemap.
- [ ] **R12 · P2 · Визуальная приёмка наполненных состояний (D07/A06/U06/G09).** Изолированные данные: длинные карточки, компоненты, конфликты, ошибки, authenticated admin; light/dark mobile/desktop, keyboard/contrast и screenshots с revision. Критерий: подтверждены действия и читаемость, а не только DOM/overflow.
- [ ] **R13 · P2 · Зелёные проверки и CI artifacts.** Обновить два устаревших контракта, адресные regressions исправленных дефектов, успешные visual artifacts, Node/Python baseline и отдельный dependency audit. Критерий: suites зелёные, skip объяснён, отчёт связан с commit. Известные падения учитывать при каждом feature-коммите.