diff --git a/.codex/skills/cleanup/SKILL.md b/.codex/skills/cleanup/SKILL.md index 778c16e8..fa881d5a 100644 --- a/.codex/skills/cleanup/SKILL.md +++ b/.codex/skills/cleanup/SKILL.md @@ -19,9 +19,9 @@ Do not refactor architecture, add features, or change behavior. If the user specifies a file or directory, check only that. Otherwise check all uncommitted changes (`git diff HEAD`). -Only report issues present in **newly added or modified** lines of this diff — do not audit unchanged code. +Only report and fix issues present in **newly added or modified** lines of this diff — do not audit unchanged code, and do not rewrite unrelated files during cleanup. -## Token-Saving Rule +## Token-Saving Rule & Harness Checks Prefer deterministic CLI checks before reading files into model context: @@ -29,27 +29,36 @@ Prefer deterministic CLI checks before reading files into model context: git diff --name-only HEAD git diff --unified=0 HEAD -- git diff --check -rg -n "TODO|FIXME|console\.log|debugger|print\(" ``` +Use the repository's focused harness checks for the touched surfaces: + +- Backend Python changes: `scripts/harness/backend-rules-check.sh` (catches direct `print()`, `breakpoint()`, and debugger calls) +- Frontend changes: `scripts/harness/frontend-rules-check.sh` (catches console logs, missing button types, Card nesting, layout height-chain issues) +- Secrets / credentials: `scripts/harness/security-check.sh` + Read full files only when the focused diff does not provide enough surrounding context to make a safe edit. ## Checklist ### 1. Duplicate Logic -- Identical or near-identical code blocks appearing in multiple places -- A function/helper that already exists but is re-implemented elsewhere instead of being reused -- Repeated DOM queries, regex literals, or template strings within the same file +- Identical or near-identical code blocks appearing in multiple places within the modified scope +- A helper that already exists but is re-implemented elsewhere instead of being reused +- Repeated complex queries or template strings that cause actual maintenance hazard +- **Anti-Over-Defensiveness**: Keep one-off logic at its call site. Do not prematurely abstract single-use or 2-use trivial helpers/templates that are clearer inline. ### 2. Magic Numbers / Magic Strings -- Bare numeric literals used in calculations (offsets, timeouts, sizes, thresholds) without a named constant -- Hardcoded strings (IDs, status values, URL fragments) scattered through logic -- Exceptions: `0`, `1`, `-1`, `100`, `""` and other idiomatically clear values are fine +- Bare numeric literals used in calculations (offsets, timeouts, sizes, thresholds) where the intent is completely opaque and naming adds clear value +- Hardcoded domain strings (IDs, status values, protocol fragments) scattered through logic +- **Anti-Over-Defensiveness (AGENTS.md Quality Bar)**: + - Idiomatically clear values such as `0`, `1`, `-1`, `100`, `""` are fine inline. + - **Do NOT over-extract local single-use layout offsets, Three.js coordinates, padding, or math coefficients into module-level globals.** + - Keep one-off logic at its call site unless extraction clarifies a complex operation or lets callers share the same behavior. ### 3. Naming Issues - Cryptic abbreviations (`or_`, `tmp2`, `x2`) - Names that do not match actual behavior -- The same concept referred to by different names in different places +- The same concept referred to by different names in different places within the changed scope ### 4. Dead Code - Commented-out code blocks (3+ lines) @@ -58,12 +67,12 @@ Read full files only when the focused diff does not provide enough surrounding c ### 5. Style Inconsistencies - Trailing whitespace -- Mixed quote styles or indentation within the same file +- Mixed quote styles or indentation within the same file (Python: 4 spaces Black style; TypeScript: 2 spaces Prettier style) - Inconsistent blank-line usage (multiple consecutive blank lines, etc.) ### 6. Other -- Private helper functions that should be exported but are not, causing callers to duplicate the implementation - Overly verbose conditions that can be simplified without changing logic +- Keep fixes strictly scoped to the modified files; do not rewrite external callers or expand cleanup beyond the changed scope. ## Steps @@ -107,30 +116,39 @@ If no issues are found, output "No code smells detected. Code quality looks good Use the Edit tool for **minimal, targeted changes**: -- **Duplicate logic**: extract to a shared constant or function; update all call sites -- **Magic number/string**: declare `const NAME = value` near the top of the relevant scope; replace all usages -- **Naming**: rename the variable/function; update all references +- **Duplicate logic**: extract to a shared constant or helper within the owned file or component scope; update call sites strictly within scope +- **Magic number/string**: declare `const NAME = value` near the top of the relevant scope only when the value is reused across places or its meaning is genuinely opaque; replace usages. Keep one-off UI/math offsets inline per `AGENTS.md` +- **Naming**: rename the variable/function; update all references within the modified scope - **Dead code**: delete it - **Trailing whitespace / style**: fix in place -- **Unexported helper**: add `export`; update callers to import instead of re-implementing +- **Unexported helper**: add `export` only when requested; do not modify unrelated callers Principles: -- Only fix issues identified in the checklist — no extra improvements +- Only fix issues identified in the checklist — no extra improvements or speculative refactorings - Keep each Edit as small as possible -- After fixing, verify the old bad pattern is gone with grep -- Prefer `apply_patch` for targeted edits; use formatters only when the repository already uses them for the touched file type +- After fixing, verify the old bad pattern is gone with grep or deterministic harness checks +- Prefer `apply_patch` or targeted edit tools; use formatters only when the repository already uses them for the touched file type -### Step 5 — Summary +### Step 5 — Verify and summarize + +Run the smallest relevant harness checks for the modified surfaces: +- Python files: `uv run python -m py_compile ` and `scripts/harness/backend-rules-check.sh` +- Frontend files: `scripts/harness/frontend-rules-check.sh` (and `bun run --cwd frontend build` if imports/types were adjusted) +- Formatting / whitespace: `git diff --check` ``` Cleanup complete: Fixed N issues: ✓ earth.js — extracted duplicate vertexShader into ATMOS_VERTEX_SHADER constant - ✓ main.js — extracted TOOLTIP_CURSOR_OFFSET = 14 (4 references updated) - ✓ controls.js — exported updateLayerButtonState; removed duplicate implementation in main.js + ✓ main.js — clarified variable naming in news event payload handler + ✓ controls.js — removed unused dead import ... +Validation: + ✓ git diff --check passed + ✓ scripts/harness/frontend-rules-check.sh passed + Skipped (needs manual review): ! foo.js L45 — large commented-out block; confirm it is safe to delete ``` @@ -141,4 +159,6 @@ Skipped (needs manual review): - **Do not** add new features, abstractions, or parameters - **Do not** rewrite comments (only delete commented-out dead code) - **Do not** touch test file logic +- **Do not** rewrite unrelated files during cleanup (per `AGENTS.md` Prohibited) +- **Do not** over-extract local single-use coordinates, layout numbers, or inline math coefficients into global constants (preventing defensive over-engineering) - If a magic number's intent is uncertain, skip it and flag it in the summary diff --git a/.codex/skills/docs/SKILL.md b/.codex/skills/docs/SKILL.md index ec7d6c56..447883e3 100644 --- a/.codex/skills/docs/SKILL.md +++ b/.codex/skills/docs/SKILL.md @@ -48,18 +48,22 @@ rg -n "class |def |function |export |router|@router|interface |type " 3. Write the doc: -- Explain background/problem, design decisions, constraints, and operational impact. +- Include the context, rationale, or operational impact the reader needs for this change. - Keep code snippets short and directly relevant. - List related files only when they help future maintainers navigate. - Use the repository’s existing language, heading style, and naming conventions. -- For UI labels, chart labels, feature names, datasource names, and other terms that may become mixed Chinese/English copy, check `docs/technical/{zh,en}/naming-glossary.md` and use the documented display name. If a confusing term is missing, update the glossary in both languages as part of the docs change. +- For UI labels, chart labels, feature names, datasource names, and other terms that may become mixed Chinese/English copy, check `docs/technical/{zh,en}/naming-glossary.md` and use the documented display name. Only update the glossary when introducing new, ambiguous, or cross-language public concepts; avoid unnecessary glossary churn for ordinary bug fixes or internal refactors. 4. Verify: - Read the completed doc once for clarity and stale statements. - Verify important referenced paths exist with `test -e` or `rg --files`. -- Run repository-specific doc checks from `docs/documentation-coverage-rules.md` when present. -- For Markdown links, check that user-facing titles are readable and not raw filenames unless the repository rules allow it. +- Run the repository's centralized documentation harness gate: + ```bash + scripts/harness/docs-consistency-check.sh + ``` + This automatically verifies bilingual pairs, public registry whitelist, link anchors, language-scoped links, section deep-links, and stale admin route terms in a single pass. +- Run any additional domain-specific checks from `docs/documentation-coverage-rules.md` when applicable. ## Hard Constraints diff --git a/.codex/skills/release/SKILL.md b/.codex/skills/release/SKILL.md index e5eff680..5e245f2b 100644 --- a/.codex/skills/release/SKILL.md +++ b/.codex/skills/release/SKILL.md @@ -19,9 +19,11 @@ Do not use this skill for ordinary commits that are not being released. ## Versioning Rules - `feature` -> bump minor and reset patch to `0` (`x.y.z` → `x.(y+1).0`; for example `0.41.2` → `0.42.0`) -- `bugfix` -> bump `+0.0.1` +- `improvement` -> bump patch `+0.0.1` (`x.y.z` → `x.y.(z+1)`) +- `bugfix` -> bump patch `+0.0.1` (`x.y.z` → `x.y.(z+1)`) - `docs`, `maintenance`, and `refactor` do not bump by default unless the user explicitly wants a release +Mixed bugfix and small feature/UI work defaults to `improvement` unless the user explicitly chooses another release type. When intent is mixed, prefer the user's stated release intent. ## Required Files @@ -53,28 +55,32 @@ Do not inspect full diffs unless deciding whether changed code belongs in the re ### Step 1 — Environment check ```bash -git branch --show-current # must be on dev +git branch --show-current # check current branch git status --short # check for unrelated uncommitted changes cat VERSION # read current version ``` -If not on `dev`, stop and tell the user. Do not proceed. +Default release branch is `dev`. If not on `dev` (e.g. on a dedicated maintenance or release branch), report the active branch and confirm before proceeding, rather than hard-failing. If unrelated uncommitted changes exist, list them and ask the user whether to include them or stash first. ### Step 2 — Determine release type and next version -- If the user provided an explicit type (`feature` / `bugfix`), use it -- Otherwise infer from `git diff --stat HEAD`, `git diff --name-only HEAD`, focused diffs for changed code, and recent `git log` +- If the user provided an explicit type (`feature` / `improvement` / `bugfix`), use it +- Otherwise infer from `git diff --stat HEAD`, `git diff --name-only HEAD`, focused diffs for changed code, and recent `git log`: + - New features or major capabilities -> `feature` + - Mixed bugfix and small feature/UI work -> default to `improvement` (per `rules.md`) + - Bugfixes only -> `bugfix` - Compute the next version: - `feature`: increment minor and reset patch to `0` (e.g. `0.41.2` → `0.42.0`) - - `bugfix`: increment patch only (e.g. `0.26.2` → `0.26.3`) + - `improvement`: increment patch only (e.g. `0.76.18` → `0.76.19`) + - `bugfix`: increment patch only (e.g. `0.76.18` → `0.76.19`) - **Show the release plan before making any changes:** ``` Release plan: - Type: bugfix - Version: 0.26.2 → 0.26.3 + Type: improvement + Version: 0.76.18 → 0.76.19 Branch: dev Will update: VERSION, frontend/package.json, pyproject.toml, uv.lock, CHANGELOG.md, version-history.md ``` @@ -117,17 +123,25 @@ Get today's date with `date +%Y-%m-%d`. ### Step 6 — Validate -Run the smallest relevant validation for the changes in scope: +Run the smallest relevant harness validation for the changes in scope: -- Python files changed: list changed Python files with `git diff --name-only HEAD -- '*.py'`, then run `python3 -m py_compile ` -- Frontend files changed: list changed frontend files with `git diff --name-only HEAD -- frontend`, then run the project-standard check if available; otherwise skip and say so -- Version consistency: confirm VERSION, package.json, pyproject.toml, and uv.lock all show the same version +- **Version consistency**: confirm `VERSION`, `frontend/package.json`, `pyproject.toml`, and `uv.lock` all show the identical target version: ```bash cat VERSION rg -n "\"version\":|^version =|version = " frontend/package.json pyproject.toml uv.lock ``` +- **Security scan**: run `scripts/harness/security-check.sh` +- **Python files changed**: + - Compile: list changed Python files with `git diff --name-only HEAD -- '*.py'`, then run `uv run python -m py_compile ` + - Service rules: run `scripts/harness/backend-rules-check.sh` +- **Frontend files changed**: + - Rules: run `scripts/harness/frontend-rules-check.sh` + - Build: run `bun run --cwd frontend build` (Bun only; never skip) +- **Docs changed**: run `scripts/harness/docs-consistency-check.sh` +- **Broad / cross-subsystem changes**: run `scripts/harness/quick-check.sh` + ### Step 7 — Pre-commit preview Show what will be committed: @@ -141,29 +155,36 @@ Confirm all required files are present and no unexpected files (debug files, `.e ### Step 8 — Commit, tag, and push ```bash +branch=$(git branch --show-current) git add VERSION frontend/package.json pyproject.toml uv.lock docs/CHANGELOG.md docs/version-history.md # also stage any code changes included in this release git add git commit -m "release: bump version to x.x.x" git tag vx.x.x -git push origin dev -git push origin vx.x.x ``` Commit message format is fixed: `release: bump version to x.x.x` +Push to remote: +- When remote publication is requested: + ```bash + git push origin "$branch" + git push origin vx.x.x + ``` +- If remote publication was not requested or remote access is restricted, report the commit and tag as complete and output the push commands for manual execution. + ### Step 9 — Completion summary ``` -✓ Version bumped: 0.26.2 → 0.26.3 +✓ Version bumped: 0.76.18 → 0.76.19 ✓ CHANGELOG updated ✓ version-history updated ✓ uv.lock regenerated ✓ Validation passed -✓ commit: release: bump version to 0.26.3 -✓ tag: v0.26.3 -✓ Pushed to origin/dev +✓ commit: release: bump version to 0.76.19 +✓ tag: v0.76.19 +✓ Pushed to origin/dev (or reported pending manual push) ``` ## Notes diff --git a/AGENTS.md b/AGENTS.md index e7d0790c..a1fbad51 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,13 +55,19 @@ Preserve user changes already present in the worktree. ### Validation -Fast local harness validation: +For an isolated change, run the smallest check that exercises the affected +behavior, along with any gates required for that area. For example, run the +docs consistency check for a link change, or reproduce a bug at the entry +point where it occurred. + +Use the quick suite when a change affects shared harness wiring or needs +regression checks across areas: ```bash scripts/harness/quick-check.sh ``` -Full local validation: +Use full validation for larger cross-subsystem changes: ```bash scripts/harness/validate.sh @@ -123,6 +129,8 @@ behavior and document the compatibility note in `docs/harness-audit.md` or focused file reads, tests, builds, linters, and harness scripts. - Keep changes scoped to the requested area. Do not mix cleanup, feature work, release work, and documentation unless the task requires it. +- When the user corrects a detail, apply it to the original request. Carry the + correction into the result without turning discarded ideas into new requirements. --- @@ -144,6 +152,12 @@ behavior and document the compatibility note in `docs/harness-audit.md` or visual-dependent part of the work. - Claims of completion need evidence: a relevant test, build, lint, screenshot, diff, direct file check, or harness result. +- Verify the outcome through the entry point the user relies on. A source check + can confirm a code convention. A UI test with a mocked API can confirm what + the user sees for that response. +- When a test fails, identify the behavior or invariant it protects. Fix the + implementation if that regressed. If the behavior is correct and the assertion + pins an obsolete detail, update the test to exercise the behavior. - For UI and rendering changes, verify the rendered result when local tooling allows it. @@ -162,7 +176,14 @@ behavior and document the compatibility note in `docs/harness-audit.md` or ## Quality Bar -- Prefer existing project patterns over new abstractions. +- Prefer existing project patterns and the smallest change that satisfies the + request. Keep one-off logic at its call site unless extraction clarifies a + complex operation or lets callers share the same behavior. +- Validate and normalize external data at the boundary that owns it. Recheck a + guarantee when data crosses a new trust boundary or an operation can invalidate it. +- Before adding a retry, lock, or fallback, identify the failure it addresses + from a requirement, an existing contract, or observed behavior. Catch errors + where the caller can recover, translate them, or add context and propagate them. - Remove stale branches, mocks, compatibility paths, and duplicated helpers once a stable path exists. - Centralize prompts, constants, defaults, and shared request/response handling. diff --git a/VERSION b/VERSION index 63ae2dee..a66f61ae 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.76.18 +0.76.19 diff --git a/backend/app/api/v1/earth.py b/backend/app/api/v1/earth.py index 16474964..cbe9c765 100644 --- a/backend/app/api/v1/earth.py +++ b/backend/app/api/v1/earth.py @@ -13,6 +13,7 @@ from sqlalchemy import delete, func, select, text from sqlalchemy.ext.asyncio import AsyncSession from app.core.config import settings as app_settings +from app.core.logging import get_logger from app.core.security import decode_token, get_current_user, redis_client from app.db.session import get_db from app.models.collected_data import CollectedData @@ -51,6 +52,7 @@ from app.services.earth_boundaries import ( router = APIRouter() +logger = get_logger(__name__) optional_bearer = HTTPBearer(auto_error=False) REPO_ROOT = Path(__file__).resolve().parents[4] EARTH_BRAND_ASSET_DIR = REPO_ROOT / "data" / "earth-brand" @@ -382,13 +384,28 @@ async def get_earth_news_sources(db: AsyncSession = Depends(get_db)): return await get_earth_news_sources_payload(db) +def _schedule_earth_news_source_refresh() -> None: + try: + from app.services.scheduler import schedule_earth_news_refresh_for_all_regions + + schedule_earth_news_refresh_for_all_regions(force=True) + except Exception as exc: + logger.warning_event( + "Failed to schedule Earth news refresh after source configuration change", + event="earth_news.rss.config_refresh_schedule_failed", + context={"error": str(exc)}, + ) + + @router.put("/news-sources") async def update_earth_news_sources( payload: EarthNewsSourcesPayload, _current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): - return await save_earth_news_sources_payload(db, payload.model_dump()) + result = await save_earth_news_sources_payload(db, payload.model_dump()) + _schedule_earth_news_source_refresh() + return result @router.delete("/news-sources") @@ -397,7 +414,9 @@ async def reset_earth_news_sources( _current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): - return await reset_earth_news_sources_payload(db) + result = await reset_earth_news_sources_payload(db) + _schedule_earth_news_source_refresh() + return result @router.post("/news-sources/test") diff --git a/backend/app/api/v1/news.py b/backend/app/api/v1/news.py index 47389e63..7b0dbdc8 100644 --- a/backend/app/api/v1/news.py +++ b/backend/app/api/v1/news.py @@ -1,17 +1,26 @@ -from fastapi import APIRouter, Depends, HTTPException, Query +from fastapi import APIRouter, Depends, HTTPException, Query, status +from pydantic import BaseModel, Field from sqlalchemy.ext.asyncio import AsyncSession +from uuid import UUID from app.db.session import get_db from app.services.earth_news import ( ALLOWED_NEWS_CATEGORY_KEYS, SUPPORTED_NEWS_LOCALES, REGION_ANCHORS, + determine_focus_region, get_earth_news_payload, ) router = APIRouter() +class EarthNewsRefreshRequest(BaseModel): + lat: float | None = Field(default=None, ge=-90, le=90) + lon: float | None = Field(default=None, ge=-180, le=180) + region: str | None = Field(default=None, max_length=64) + + def _parse_categories(raw: str | None) -> set[str] | None: if raw is None or not raw.strip(): return None @@ -39,7 +48,9 @@ def _parse_limit(raw: int | None) -> int: if raw is None: return 12 if raw < 1: - raise HTTPException(status_code=422, detail={"message": "News limit must be greater than 0."}) + raise HTTPException( + status_code=422, detail={"message": "News limit must be greater than 0."} + ) return min(raw, 100) @@ -59,18 +70,76 @@ def _parse_locale(raw: str | None) -> str: return requested +@router.post("/refresh", status_code=status.HTTP_202_ACCEPTED) +async def request_earth_news_refresh(payload: EarthNewsRefreshRequest): + requested_region = payload.region.strip().lower() if payload.region else None + if requested_region and requested_region not in REGION_ANCHORS: + raise HTTPException( + status_code=422, + detail={ + "message": "Unsupported news region.", + "invalid_region": requested_region, + "allowed_regions": list(REGION_ANCHORS.keys()), + }, + ) + region = requested_region or determine_focus_region(payload.lat, payload.lon) + from app.services.scheduler import request_earth_news_region_refresh + + try: + return request_earth_news_region_refresh(region) + except Exception as exc: + raise HTTPException( + status_code=503, + detail={ + "code": "refresh_failed", + "message": "Could not start a news refresh. Please try again.", + }, + ) from exc + + +@router.get("/refresh/{refresh_id}") +async def get_earth_news_refresh(refresh_id: UUID): + from app.services.earth_news_refresh import get_earth_news_refresh_status + + try: + result = get_earth_news_refresh_status(refresh_id.hex) + except Exception as exc: + raise HTTPException( + status_code=503, + detail={ + "code": "refresh_failed", + "message": "Refresh status is temporarily unavailable. Please retry.", + }, + ) from exc + if result is not None: + return result + return { + "refresh_id": refresh_id.hex, + "region": None, + "status": "failed", + "error": { + "code": "expired", + "message": "Refresh status expired. Submit a new refresh.", + }, + } + + @router.get("/earth-feed") async def get_earth_feed( lat: float | None = Query(None, description="Current Earth view center latitude"), lon: float | None = Query(None, description="Current Earth view center longitude"), - region: str | None = Query(None, description="Explicit Earth news region for UE/client integrations"), + region: str | None = Query( + None, description="Explicit Earth news region for UE/client integrations" + ), categories: str | None = Query(None, description="Comma-separated news category keys"), sources: str | None = Query(None, description="Comma-separated news source ids"), limit: int | None = Query(None, description="Maximum news items to return, capped at 100"), locale: str | None = Query(None, description="Display locale, zh-CN or en-US"), db: AsyncSession = Depends(get_db), ): - normalized_region = region.strip().lower() if isinstance(region, str) and region.strip() else None + normalized_region = ( + region.strip().lower() if isinstance(region, str) and region.strip() else None + ) if normalized_region is not None and normalized_region not in REGION_ANCHORS: raise HTTPException( status_code=422, diff --git a/backend/app/db/bgp_prefix_geo.py b/backend/app/db/bgp_prefix_geo.py new file mode 100644 index 00000000..78704525 --- /dev/null +++ b/backend/app/db/bgp_prefix_geo.py @@ -0,0 +1,51 @@ +"""SQL objects supporting indexed BGP prefix geography lookup.""" + +from sqlalchemy import text +from sqlalchemy.ext.asyncio import AsyncConnection + +BGP_PREFIX_GEO_FUNCTION_SQL = ( + """ + CREATE OR REPLACE FUNCTION planet_bgp_try_inet(value text) + RETURNS inet + LANGUAGE plpgsql IMMUTABLE STRICT PARALLEL SAFE + AS $$ + BEGIN + RETURN value::inet; + EXCEPTION WHEN data_exception THEN + RETURN NULL; + END; + $$ + """, + """ + CREATE OR REPLACE FUNCTION planet_bgp_try_masklen(value text) + RETURNS integer + LANGUAGE plpgsql IMMUTABLE STRICT PARALLEL SAFE + AS $$ + BEGIN + RETURN masklen(value::cidr); + EXCEPTION WHEN data_exception THEN + RETURN NULL; + END; + $$ + """, +) + +BGP_PREFIX_GEO_INDEX_NAME = "idx_bgp_prefix_geo_range_current" +BGP_PREFIX_GEO_INDEX_SQL = f""" +CREATE INDEX CONCURRENTLY IF NOT EXISTS {BGP_PREFIX_GEO_INDEX_NAME} +ON collected_data USING gist ( + planet_bgp_try_inet(metadata->>'range_start') inet_ops, + planet_bgp_try_inet(metadata->>'range_end') inet_ops +) +WHERE source IN ( + 'opengeofeed_prefix_geo', + 'iptoasn_prefix_geo', + 'nro_delegated_prefix_geo' +) + AND COALESCE(is_current, TRUE) = TRUE +""" + + +async def install_bgp_prefix_geo_functions(connection: AsyncConnection) -> None: + for statement in BGP_PREFIX_GEO_FUNCTION_SQL: + await connection.execute(text(statement)) diff --git a/backend/app/db/session.py b/backend/app/db/session.py index 57aecbb4..0cda6d28 100644 --- a/backend/app/db/session.py +++ b/backend/app/db/session.py @@ -6,6 +6,7 @@ from sqlalchemy.orm import declarative_base from app.core.config import settings from app.core.logging import get_logger +from app.db.bgp_prefix_geo import install_bgp_prefix_geo_functions logger = get_logger(__name__) @@ -219,6 +220,7 @@ async def init_db(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) + await install_bgp_prefix_geo_functions(conn) users_email_verified_existed = ( await conn.execute( text( @@ -299,8 +301,12 @@ async def init_db(): change_event_id BIGINT; change_payload JSONB; BEGIN + change_event_id := nextval( + pg_get_serial_sequence('earth_data_change_events', 'id')::regclass + ); change_payload := jsonb_build_object( 'event', 'earth.layer.changed', + 'event_id', change_event_id, 'table', change_table, 'operation', change_operation, 'source', change_source, @@ -311,6 +317,7 @@ async def init_db(): ); INSERT INTO earth_data_change_events ( + id, table_name, operation, source, @@ -318,23 +325,15 @@ async def init_db(): payload, occurred_at ) VALUES ( + change_event_id, change_table, change_operation, change_source, NULL, change_payload, NOW() - ) - RETURNING id INTO change_event_id; - - change_payload := change_payload || jsonb_build_object( - 'event_id', change_event_id ); - UPDATE earth_data_change_events - SET payload = change_payload - WHERE id = change_event_id; - PERFORM pg_notify( 'planet_earth_data_changes', change_payload::text @@ -440,6 +439,16 @@ async def init_db(): ); END LOOP; ELSIF TG_OP = 'UPDATE' THEN + IF TG_TABLE_NAME = 'earth_news_items' AND NOT EXISTS ( + SELECT 1 + FROM new_rows AS current_row + FULL JOIN old_rows AS previous_row USING (id) + WHERE (to_jsonb(current_row) - 'last_seen_at' - 'updated_at') + IS DISTINCT FROM + (to_jsonb(previous_row) - 'last_seen_at' - 'updated_at') + ) THEN + RETURN NULL; + END IF; FOR change_source IN SELECT DISTINCT COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) FROM ( diff --git a/backend/app/services/bgp_enrichment.py b/backend/app/services/bgp_enrichment.py index 2df3b1d3..06e0b5f7 100644 --- a/backend/app/services/bgp_enrichment.py +++ b/backend/app/services/bgp_enrichment.py @@ -111,15 +111,24 @@ async def _lookup_prefix_geography( result = await db.execute( text( """ + WITH candidates AS MATERIALIZED ( + SELECT source, id, metadata + FROM collected_data + WHERE source IN ( + 'opengeofeed_prefix_geo', + 'iptoasn_prefix_geo', + 'nro_delegated_prefix_geo' + ) + AND COALESCE(is_current, TRUE) = TRUE + AND planet_bgp_try_inet(metadata->>'range_start') <= CAST(:range_start AS inet) + AND planet_bgp_try_inet(metadata->>'range_end') >= CAST(:range_end AS inet) + ) SELECT metadata - FROM collected_data + FROM candidates WHERE source = :source - AND COALESCE(is_current, TRUE) = TRUE AND metadata->>'family' = :family - AND CAST(metadata->>'range_start' AS inet) <= CAST(:range_start AS inet) - AND CAST(metadata->>'range_end' AS inet) >= CAST(:range_end AS inet) ORDER BY - masklen(CAST(metadata->>'prefix' AS cidr)) DESC NULLS LAST, + planet_bgp_try_masklen(metadata->>'prefix') DESC NULLS LAST, id DESC LIMIT 1 """ @@ -146,6 +155,10 @@ async def _lookup_prefix_geography( results: dict[str, dict[str, Any]] = {} + # The GiST range predicate is selective, but PostgreSQL 15 greatly overestimates its cost. + # Avoid spending more time compiling JIT code than fetching the small candidate set. + await db.execute(text("SET LOCAL jit = off")) + for prefix in prefix_values: try: network = ipaddress.ip_network(prefix, strict=False) diff --git a/backend/app/services/earth_db_change_listener.py b/backend/app/services/earth_db_change_listener.py index 82f3f20a..2738c8b4 100644 --- a/backend/app/services/earth_db_change_listener.py +++ b/backend/app/services/earth_db_change_listener.py @@ -22,6 +22,12 @@ from app.services.earth_layer_adapters import ( get_earth_update_layers_for_source, ) from app.services.earth_layer_cache import invalidate_earth_layer_cache_for_source +from app.services.earth_outbox_maintenance import ( + configured_retention_days, + purge_consumed_events, + release_maintenance_lock, + try_maintenance_lock, +) logger = get_logger(__name__) @@ -30,6 +36,7 @@ DEFAULT_DEBOUNCE_SECONDS = 0.25 DEFAULT_MAX_WAIT_SECONDS = 1.5 DELETE_FAST_FLUSH_SECONDS = 0.05 LISTEN_KEEPALIVE_SECONDS = 5.0 +OUTBOX_RETENTION_CHECK_SECONDS = 60.0 OUTBOX_POLL_LIMIT = 5000 MAX_ENTITY_KEY_SAMPLES = 20 MAX_SEEN_EVENT_IDS = 20000 @@ -346,6 +353,7 @@ class EarthDbChangeListener: self._stop_event: asyncio.Event | None = None self._connection: asyncpg.Connection | None = None self._loop: asyncio.AbstractEventLoop | None = None + self._next_retention_check = 0.0 def start(self) -> None: if self._task and not self._task.done(): @@ -385,6 +393,7 @@ class EarthDbChangeListener: ) except asyncio.TimeoutError: await self._poll_outbox() + await self._maybe_purge_outbox() except asyncio.CancelledError: raise except Exception as exc: @@ -459,6 +468,27 @@ class EarthDbChangeListener: context={"events": len(rows), "accepted": accepted_count}, ) + async def _maybe_purge_outbox(self) -> None: + if self._connection is None or monotonic() < self._next_retention_check: + return + self._next_retention_check = monotonic() + OUTBOX_RETENTION_CHECK_SECONDS + try: + if not await try_maintenance_lock(self._connection): + return + try: + await purge_consumed_events( + self._connection, + retention_days=configured_retention_days(), + ) + finally: + await release_maintenance_lock(self._connection) + except Exception as exc: + logger.exception_event( + "Earth outbox retention failed", + event="earth.outbox.retention_failed", + context={"error": str(exc)}, + ) + def _on_notification( self, _connection: asyncpg.Connection, diff --git a/backend/app/services/earth_layer_adapters.py b/backend/app/services/earth_layer_adapters.py index e48c69c5..d8730906 100644 --- a/backend/app/services/earth_layer_adapters.py +++ b/backend/app/services/earth_layer_adapters.py @@ -99,7 +99,7 @@ EARTH_LAYER_ADAPTERS: tuple[EarthLayerAdapter, ...] = ( sources=frozenset({"media_news_archive", "earth_news_items"}), tables=frozenset({"earth_news_items"}), layers=("news",), - cache_patterns=("summary*",), + cache_patterns=(), refresh_strategy="reload", ), EarthLayerAdapter( diff --git a/backend/app/services/earth_layer_cache.py b/backend/app/services/earth_layer_cache.py index 253960e8..f99115cb 100644 --- a/backend/app/services/earth_layer_cache.py +++ b/backend/app/services/earth_layer_cache.py @@ -2,25 +2,27 @@ from __future__ import annotations import asyncio from collections.abc import Awaitable, Callable -from dataclasses import dataclass +from contextlib import suppress +from dataclasses import dataclass, replace import hashlib import json import time from typing import Any +from uuid import uuid4 -from fastapi import Response +from fastapi import HTTPException, Response from app.core.cache import _RedisClient from app.core.config import settings from app.core.logging import get_logger - logger = get_logger(__name__, service="earth_layer_cache") EARTH_LAYER_CACHE_PREFIX = "earth:layer:v1" EARTH_LAYER_LOCK_PREFIX = "earth:layer:lock:v1" DEFAULT_LOCK_TTL_SECONDS = 10 DEFAULT_LOCK_WAIT_SECONDS = 0.2 +DEFAULT_BUILD_WAIT_SECONDS = 30 DEFAULT_MAX_FEATURES = 5000 DEFAULT_MAX_BYTES = 5 * 1024 * 1024 DEFAULT_BBOX_PRECISION_DEGREES = 0.1 @@ -35,6 +37,7 @@ class EarthLayerCachePolicy: max_bytes: int = DEFAULT_MAX_BYTES lock_ttl_seconds: int = DEFAULT_LOCK_TTL_SECONDS lock_wait_seconds: float = DEFAULT_LOCK_WAIT_SECONDS + build_wait_seconds: float = DEFAULT_BUILD_WAIT_SECONDS @dataclass(frozen=True) @@ -49,6 +52,9 @@ class EarthLayerCacheResult: class EarthLayerCache: def __init__(self) -> None: self._client = None + self._inflight: dict[ + tuple[asyncio.AbstractEventLoop, str], asyncio.Future[EarthLayerCacheResult | None] + ] = {} @property def client(self): @@ -82,17 +88,62 @@ class EarthLayerCache: value = json.loads(raw) return value if isinstance(value, dict) else None - def set_json(self, key: str, payload: dict[str, Any], ttl_seconds: int) -> None: - self.client.setex(key, ttl_seconds, json.dumps(payload, ensure_ascii=False, default=str)) + def acquire_lock(self, key: str, ttl_seconds: int) -> str | None: + token = uuid4().hex + return ( + token if self.client.set(self.lock_key(key), token, nx=True, ex=ttl_seconds) else None + ) - def acquire_lock(self, key: str, ttl_seconds: int) -> bool: - return bool(self.client.set(self.lock_key(key), "1", nx=True, ex=ttl_seconds)) + def renew_lock(self, key: str, token: str, ttl_seconds: int) -> bool: + return bool( + self.client.eval( + """ + if redis.call('get', KEYS[1]) == ARGV[1] then + return redis.call('expire', KEYS[1], ARGV[2]) + end + return 0 + """, + 1, + self.lock_key(key), + token, + ttl_seconds, + ) + ) - def release_lock(self, key: str) -> None: - try: - self.client.delete(self.lock_key(key)) - except Exception: - pass + def release_lock(self, key: str, token: str) -> None: + self.client.eval( + """ + if redis.call('get', KEYS[1]) == ARGV[1] then + return redis.call('del', KEYS[1]) + end + return 0 + """, + 1, + self.lock_key(key), + token, + ) + + def publish( + self, key: str, token: str, payload: dict[str, Any], policy: EarthLayerCachePolicy + ) -> bool: + return bool( + self.client.eval( + """ + if redis.call('get', KEYS[1]) ~= ARGV[1] then return 0 end + redis.call('setex', KEYS[2], ARGV[2], ARGV[4]) + redis.call('setex', KEYS[3], ARGV[3], ARGV[4]) + return 1 + """, + 3, + self.lock_key(key), + key, + self.stale_key(key), + token, + policy.fresh_ttl_seconds, + policy.stale_ttl_seconds, + json.dumps(payload, ensure_ascii=False, default=str), + ) + ) def delete_pattern(self, pattern: str = f"{EARTH_LAYER_CACHE_PREFIX}:*") -> int: keys = list(self.client.scan_iter(match=pattern)) @@ -169,56 +220,122 @@ async def resolve_layer_payload( policy: EarthLayerCachePolicy, builder: Callable[[], Awaitable[dict[str, Any]]], ) -> EarthLayerCacheResult: - started = time.perf_counter() - try: - cached = earth_layer_cache.get_json(key) - if cached is not None: - return _result(cached, state="hit", key=key) - - lock_acquired = earth_layer_cache.acquire_lock(key, policy.lock_ttl_seconds) - if lock_acquired: - try: - payload = await _build_budgeted_payload(builder, policy) - _write_fresh_and_stale(key, payload, policy) - _log_cache_event("refresh", key, payload, started) - return _result(payload, state="refresh", key=key) - except Exception as exc: - stale = _read_stale(key) - if stale is not None: - logger.warning_event( - "Earth layer cache builder failed; returning stale payload", - event="earth_layer_cache.stale_after_builder_error", - context={"key": key, "error": str(exc)}, - ) - return _result(stale, state="stale", key=key) - raise - finally: - earth_layer_cache.release_lock(key) - + flight_key = (asyncio.get_running_loop(), key) + while flight_key in earth_layer_cache._inflight: stale = _read_stale(key) if stale is not None: return _result(stale, state="stale", key=key) + future = earth_layer_cache._inflight[flight_key] + done, _ = await asyncio.wait({future}, timeout=policy.build_wait_seconds) + if not done: + raise HTTPException(503, "Earth layer cache rebuild is still in progress") + result = future.result() + if result is not None: + state = "hit" if result.state == "refresh" else result.state + return replace(result, state=state) - await asyncio.sleep(policy.lock_wait_seconds) - cached_after_wait = earth_layer_cache.get_json(key) - if cached_after_wait is not None: - return _result(cached_after_wait, state="hit", key=key) + future = asyncio.get_running_loop().create_future() + earth_layer_cache._inflight[flight_key] = future + try: + result = await _resolve_layer_payload(key=key, policy=policy, builder=builder) + future.set_result(result) + return result + except asyncio.CancelledError: + # A waiting request can take over using its own still-open DB session. + future.set_result(None) + raise + except Exception as exc: + future.set_exception(exc) + future.exception() + raise + finally: + earth_layer_cache._inflight.pop(flight_key) - payload = await _build_budgeted_payload(builder, policy) - _log_cache_event("miss", key, payload, started) - return _result(payload, state="miss", key=key) + +async def _resolve_layer_payload( + *, + key: str, + policy: EarthLayerCachePolicy, + builder: Callable[[], Awaitable[dict[str, Any]]], +) -> EarthLayerCacheResult: + started = time.perf_counter() + try: + async with asyncio.timeout(policy.build_wait_seconds): + while True: + cached = earth_layer_cache.get_json(key) + if cached is not None: + return _result(cached, state="hit", key=key) + token = earth_layer_cache.acquire_lock(key, policy.lock_ttl_seconds) + if token is not None: + break + stale = _read_stale(key) + if stale is not None: + return _result(stale, state="stale", key=key) + await asyncio.sleep(policy.lock_wait_seconds) + except TimeoutError: + raise HTTPException(503, "Earth layer cache rebuild is still in progress") from None except Exception as exc: - try: - payload = await _build_budgeted_payload(builder, policy) - except Exception: - raise exc logger.warning_event( "Earth layer cache bypassed", event="earth_layer_cache.bypass", context={"key": key, "error": str(exc)}, ) + payload = await _build_budgeted_payload(builder, policy) return _result(payload, state="bypass", key=key) + renewal = asyncio.create_task(_renew_cache_lock(key, token, policy)) + try: + try: + payload = await _build_budgeted_payload(builder, policy) + except Exception as exc: + stale = _read_stale(key) + if stale is None: + raise + logger.warning_event( + "Earth layer cache builder failed; returning stale payload", + event="earth_layer_cache.stale_after_builder_error", + context={"key": key, "error": str(exc)}, + ) + return _result(stale, state="stale", key=key) + try: + published = earth_layer_cache.publish(key, token, payload, policy) + except Exception as exc: + logger.warning_event( + "Earth layer cache publish failed", + event="earth_layer_cache.bypass", + context={"key": key, "error": str(exc)}, + ) + published = False + state = "refresh" if published else "bypass" + _log_cache_event(state, key, payload, started) + return _result(payload, state=state, key=key) + finally: + renewal.cancel() + with suppress(asyncio.CancelledError): + await renewal + try: + earth_layer_cache.release_lock(key, token) + except Exception as exc: + logger.warning_event( + "Earth layer cache lock release failed", + event="earth_layer_cache.lock_release_failed", + context={"key": key, "error": str(exc)}, + ) + + +async def _renew_cache_lock(key: str, token: str, policy: EarthLayerCachePolicy) -> None: + try: + while True: + await asyncio.sleep(policy.lock_ttl_seconds / 3) + if not earth_layer_cache.renew_lock(key, token, policy.lock_ttl_seconds): + raise RuntimeError("Earth layer cache lock ownership lost") + except Exception as exc: + logger.warning_event( + "Earth layer cache lock renewal stopped", + event="earth_layer_cache.lock_renewal_failed", + context={"key": key, "error": str(exc)}, + ) + def apply_payload_budget(payload: dict[str, Any], policy: EarthLayerCachePolicy) -> dict[str, Any]: budgeted = _truncate_features(payload, policy.max_features, "feature_budget") @@ -286,11 +403,6 @@ async def _build_budgeted_payload( return apply_payload_budget(payload, policy) -def _write_fresh_and_stale(key: str, payload: dict[str, Any], policy: EarthLayerCachePolicy) -> None: - earth_layer_cache.set_json(key, payload, policy.fresh_ttl_seconds) - earth_layer_cache.set_json(earth_layer_cache.stale_key(key), payload, policy.stale_ttl_seconds) - - def _read_stale(key: str) -> dict[str, Any] | None: try: return earth_layer_cache.get_json(earth_layer_cache.stale_key(key)) @@ -359,14 +471,16 @@ def _payload_size(payload: dict[str, Any]) -> int: def _safe_key_part(value: Any) -> str: raw = str(value).strip().lower() - return "".join(char if char.isalnum() or char in {"-", "_", ".", ","} else "_" for char in raw)[:160] + return "".join(char if char.isalnum() or char in {"-", "_", ".", ","} else "_" for char in raw)[ + :160 + ] def _layer_from_key(key: str) -> str: prefix = f"{EARTH_LAYER_CACHE_PREFIX}:" if not key.startswith(prefix): return "unknown" - remainder = key[len(prefix):] + remainder = key[len(prefix) :] return remainder.split(":", 1)[0] diff --git a/backend/app/services/earth_news.py b/backend/app/services/earth_news.py index f3078b4a..cdf4d117 100644 --- a/backend/app/services/earth_news.py +++ b/backend/app/services/earth_news.py @@ -3,7 +3,7 @@ from __future__ import annotations import asyncio import codecs from dataclasses import dataclass, field -from datetime import UTC, datetime, timedelta +from datetime import UTC, datetime from email.utils import parsedate_to_datetime import hashlib import html @@ -1639,10 +1639,15 @@ async def record_earth_news_sources_health( await db.commit() -async def get_configured_sources_for_region(db: AsyncSession | None, region: str) -> list[NewsFeedSource]: +async def get_configured_sources_for_region( + db: AsyncSession | None, + region: str, + *, + config_payload: dict[str, Any] | None = None, +) -> list[NewsFeedSource]: if db is None: return get_sources_for_region(region) - payload = await get_earth_news_sources_payload(db) + payload = config_payload or await get_earth_news_sources_payload(db) sources = [ source for raw in payload.get("sources", []) @@ -2731,7 +2736,6 @@ async def get_earth_news_payload( del provider_client active_region = region if region in REGION_ANCHORS else determine_focus_region(lat, lon) has_settings_db = db is not None and callable(getattr(db, "execute", None)) - source_config_payload = await get_earth_news_sources_payload(db) if has_settings_db else None sources = ( await get_configured_sources_for_region(db, active_region) if has_settings_db @@ -2750,39 +2754,7 @@ async def get_earth_news_payload( locale=locale, ) - from app.services.earth_news_store import ( - get_earth_news_feed_coverage, - get_earth_news_freshness, - list_earth_news_cruise_items, - list_earth_news_items, - upsert_earth_news_items, - ) - - errors: list[str] = [] - item_count, newest_at = await get_earth_news_freshness(db, active_region=active_region) - should_supplement = _needs_rss_supplement(item_count=item_count, newest_at=newest_at) - if not should_supplement and callable(getattr(db, "execute", None)): - expected_feed_keys = _expected_feed_keys(sources, active_region=active_region) - if expected_feed_keys: - covered_feed_keys = await get_earth_news_feed_coverage( - db, - active_region=active_region, - recent_after=datetime.now(UTC) - timedelta(seconds=RSS_SUPPLEMENT_MAX_AGE_SECONDS), - ) - should_supplement = bool(expected_feed_keys - covered_feed_keys) - if should_supplement: - if source_config_payload is None: - fetched_items, errors, health_by_source = await _fetch_rss_items_for_sources(sources, active_region=active_region) - else: - fetched_items, errors, health_by_source = await _fetch_rss_items_for_sources( - sources, - active_region=active_region, - config_payload=source_config_payload, - ) - await record_earth_news_sources_health(db, health_by_source) - ranked_fetched_items = _rank_and_trim_items(fetched_items, active_region=active_region) - await _enqueue_unverified_locations(ranked_fetched_items) - await upsert_earth_news_items(db, ranked_fetched_items) + from app.services.earth_news_store import list_earth_news_cruise_items, list_earth_news_items items = await _call_store_list_items( list_earth_news_items, @@ -2792,7 +2764,7 @@ async def get_earth_news_payload( categories=categories, source_ids=source_ids, ) - if not source_ids: + if items and not source_ids: ready_sources = { _news_item_source_id(item) for item in items @@ -2833,10 +2805,6 @@ async def get_earth_news_payload( ) else: cruise_items = items - enqueue_candidates = {item.id: item for item in [*items, *cruise_items] if item.id} - await _enqueue_unverified_locations(list(enqueue_candidates.values())) - stale = bool(errors and items) - return _build_payload( lat=lat, lon=lon, @@ -2844,8 +2812,8 @@ async def get_earth_news_payload( items=items, cruise_items=cruise_items, sources=sources, - errors=errors, - stale=stale, + errors=[], + stale=False, categories=categories, source_ids=source_ids, limit=limit, diff --git a/backend/app/services/earth_news_refresh.py b/backend/app/services/earth_news_refresh.py new file mode 100644 index 00000000..5b1cb0f9 --- /dev/null +++ b/backend/app/services/earth_news_refresh.py @@ -0,0 +1,480 @@ +"""Periodic RSS supplementation for the read-only Earth news feed.""" + +from __future__ import annotations + +import asyncio +from contextlib import suppress +from dataclasses import replace +from datetime import UTC, datetime, timedelta +from hashlib import sha256 +import json +from typing import Any +from uuid import uuid4 + +from app.core.cache import _RedisClient +from app.core.logging import get_logger +from app.db.session import async_session_factory +from app.services import earth_news +from app.services.earth_news_store import ( + get_earth_news_feed_coverage, + get_earth_news_freshness, + upsert_earth_news_items, +) + +logger = get_logger(__name__, service="earth_news") + +REFRESH_INTERVAL_SECONDS = 10 * 60 +REFRESH_LOCK_TTL_SECONDS = 120 +REFRESH_LOCK_RENEW_SECONDS = 30 +SOURCE_FAILURE_COOLDOWN_SECONDS = 30 * 60 +REFRESH_LOCK_PREFIX = "earth:news:rss-refresh:v1" +SOURCE_COOLDOWN_PREFIX = "earth:news:rss-cooldown:v1" +REFRESH_STATUS_PREFIX = "earth:news:rss-refresh-status:v1" +REFRESH_ACTIVE_PREFIX = "earth:news:rss-refresh-active:v1" +REFRESH_STATUS_TTL_SECONDS = 10 * 60 +REFRESH_ACTIVE_TTL_SECONDS = 120 +REFRESH_STATUS_HEARTBEAT_SECONDS = 30 + + +def _refresh_status_key(refresh_id: str) -> str: + return f"{REFRESH_STATUS_PREFIX}:{refresh_id}" + + +def _refresh_active_key(region: str) -> str: + return f"{REFRESH_ACTIVE_PREFIX}:{region}" + + +def create_earth_news_refresh_status(region: str) -> tuple[dict[str, Any], bool]: + """Create one per-region active refresh status, or return the current one.""" + refresh_id = uuid4().hex + status = {"refresh_id": refresh_id, "region": region, "status": "pending"} + script = """ + local active_id = redis.call('get', KEYS[1]) + if active_id then + local active_status = redis.call('get', ARGV[5] .. active_id) + if active_status then + local decoded = cjson.decode(active_status) + if decoded.status == 'pending' or decoded.status == 'running' then + return {active_id, active_status, 0} + end + end + redis.call('del', KEYS[1]) + end + redis.call('set', KEYS[1], ARGV[1], 'EX', ARGV[3]) + redis.call('set', KEYS[2], ARGV[2], 'EX', ARGV[4]) + return {ARGV[1], ARGV[2], 1} + """ + raw = _RedisClient.get_client().eval( + script, + 2, + _refresh_active_key(region), + _refresh_status_key(refresh_id), + refresh_id, + json.dumps(status, separators=(",", ":")), + REFRESH_ACTIVE_TTL_SECONDS, + REFRESH_STATUS_TTL_SECONDS, + f"{REFRESH_STATUS_PREFIX}:", + ) + _, encoded, created = raw + payload = json.loads(encoded) + return payload, bool(int(created)) + + +def set_earth_news_refresh_status( + refresh_id: str, + region: str, + status: str, + *, + error: dict[str, str] | None = None, +) -> dict[str, Any]: + payload: dict[str, Any] = { + "refresh_id": refresh_id, + "region": region, + "status": status, + } + if error: + payload["error"] = error + script = """ + if redis.call('get', KEYS[1]) ~= ARGV[2] then return 0 end + redis.call('set', KEYS[2], ARGV[1], 'EX', ARGV[3]) + if ARGV[4] == 'succeeded' or ARGV[4] == 'failed' then + redis.call('del', KEYS[1]) + else + redis.call('expire', KEYS[1], ARGV[5]) + end + return 1 + """ + _RedisClient.get_client().eval( + script, + 2, + _refresh_active_key(region), + _refresh_status_key(refresh_id), + json.dumps(payload, separators=(",", ":")), + refresh_id, + REFRESH_STATUS_TTL_SECONDS, + status, + REFRESH_ACTIVE_TTL_SECONDS, + ) + return payload + + +def touch_earth_news_refresh_status(refresh_id: str, region: str) -> bool: + script = """ + if redis.call('get', KEYS[1]) ~= ARGV[1] then return 0 end + redis.call('expire', KEYS[1], ARGV[2]) + redis.call('expire', KEYS[2], ARGV[3]) + return 1 + """ + return bool( + _RedisClient.get_client().eval( + script, + 2, + _refresh_active_key(region), + _refresh_status_key(refresh_id), + refresh_id, + REFRESH_ACTIVE_TTL_SECONDS, + REFRESH_STATUS_TTL_SECONDS, + ) + ) + + +def get_earth_news_refresh_status(refresh_id: str) -> dict[str, Any] | None: + raw = _RedisClient.get_client().get(_refresh_status_key(refresh_id)) + if not raw: + return None + value = json.loads(raw) + if not isinstance(value, dict): + return None + if value.get("status") in {"pending", "running"}: + region = str(value.get("region") or "") + active_id = _RedisClient.get_client().get(_refresh_active_key(region)) if region else None + if active_id != refresh_id: + return { + **value, + "status": "failed", + "error": { + "code": "expired", + "message": "Refresh status expired. Submit a new refresh.", + }, + } + return value + + +def _lock_key(region: str) -> str: + return f"{REFRESH_LOCK_PREFIX}:{region}" + + +def _cooldown_key(region: str, source_id: str, feed_id: str) -> str: + identity = f"{region}\0{source_id}\0{feed_id}".encode("utf-8") + return f"{SOURCE_COOLDOWN_PREFIX}:{sha256(identity).hexdigest()}" + + +def _source_failure_cooldown_seconds(source: earth_news.NewsFeedSource | None) -> int: + if source is None: + return SOURCE_FAILURE_COOLDOWN_SECONDS + configured_minutes = source.health_policy.get("cooldown_minutes") + try: + return max(60, int(float(configured_minutes) * 60)) + except TypeError, ValueError: + return SOURCE_FAILURE_COOLDOWN_SECONDS + + +def _select_feeds( + sources: list[earth_news.NewsFeedSource], + *, + active_region: str, + required_keys: set[tuple[str, str]], + redis_client: Any | None, +) -> tuple[list[earth_news.NewsFeedSource], set[tuple[str, str]]]: + selected_sources: list[earth_news.NewsFeedSource] = [] + cooling_keys: set[tuple[str, str]] = set() + for source in sources: + selected_feeds = [] + source_cooling = False + if redis_client is not None: + try: + source_cooling = bool( + redis_client.exists(_cooldown_key(active_region, source.id, "__source__")) + ) + except Exception as exc: + logger.warning_event( + "Earth news source cooldown lookup failed", + event="earth_news.rss.cooldown_lookup_failed", + context={"region": active_region, "source_id": source.id, "error": str(exc)}, + ) + for feed in earth_news._source_feeds(source): + feed_key = (source.id, feed.id) + if feed_key not in required_keys: + continue + if source_cooling: + cooling_keys.add(feed_key) + continue + if redis_client is not None: + try: + if redis_client.exists(_cooldown_key(active_region, *feed_key)): + cooling_keys.add(feed_key) + continue + except Exception as exc: + logger.warning_event( + "Earth news source cooldown lookup failed", + event="earth_news.rss.cooldown_lookup_failed", + context={ + "region": active_region, + "source_id": source.id, + "error": str(exc), + }, + ) + selected_feeds.append(feed) + if selected_feeds: + selected_sources.append( + replace( + source, + feed_url=selected_feeds[0].url, + feed_urls=tuple(feed.url for feed in selected_feeds), + feeds=tuple(selected_feeds), + ) + ) + return selected_sources, cooling_keys + + +def _record_failed_feed_cooldowns( + redis_client: Any | None, + *, + active_region: str, + health_by_source: dict[str, dict[str, Any]], + sources: list[earth_news.NewsFeedSource], +) -> None: + if redis_client is None: + return + cooldown_by_source = {source.id: source for source in sources} + for source_id, health in health_by_source.items(): + feed_results = health.get("feed_results") + if isinstance(feed_results, list) and feed_results: + failed_feed_ids = [ + str(result.get("feed_id") or "") + for result in feed_results + if isinstance(result, dict) and not result.get("ok") and result.get("feed_id") + ] + else: + failed_feed_ids = [str(health.get("feed_id") or "__source__")] + if health.get("ok"): + failed_feed_ids = [] + for feed_id in failed_feed_ids: + try: + redis_client.set( + _cooldown_key(active_region, source_id, feed_id), + "1", + ex=_source_failure_cooldown_seconds(cooldown_by_source.get(source_id)), + ) + except Exception as exc: + logger.warning_event( + "Earth news source failure cooldown write failed", + event="earth_news.rss.cooldown_write_failed", + context={"region": active_region, "source_id": source_id, "error": str(exc)}, + ) + + +async def _renew_lock(redis_client: Any, key: str, token: str, lease_lost: asyncio.Event) -> None: + renew_script = """ + if redis.call('get', KEYS[1]) == ARGV[1] then + return redis.call('expire', KEYS[1], ARGV[2]) + end + return 0 + """ + try: + while True: + await asyncio.sleep(REFRESH_LOCK_RENEW_SECONDS) + if not redis_client.eval(renew_script, 1, key, token, REFRESH_LOCK_TTL_SECONDS): + lease_lost.set() + return + except asyncio.CancelledError: + raise + except Exception as exc: + lease_lost.set() + logger.warning_event( + "Earth news refresh lock renewal failed", + event="earth_news.rss.refresh_lock_renewal_failed", + context={"error": str(exc)}, + ) + + +async def refresh_earth_news_region(active_region: str, *, force: bool = False) -> dict[str, Any]: + """Fetch only stale or uncovered feeds for one region, outside the request path.""" + if active_region not in earth_news.REGION_ANCHORS: + raise ValueError(f"Unsupported Earth news region: {active_region}") + + lock_key = _lock_key(active_region) + token = uuid4().hex + redis_client = None + lock_acquired = False + lock_available = False + try: + redis_client = _RedisClient.get_client() + lock_acquired = bool( + redis_client.set(lock_key, token, nx=True, ex=REFRESH_LOCK_TTL_SECONDS) + ) + lock_available = True + except Exception as exc: + logger.warning_event( + "Earth news refresh coordination unavailable", + event="earth_news.rss.refresh_lock_unavailable", + context={"region": active_region, "error": str(exc)}, + ) + + if not lock_available or not lock_acquired: + state = "busy" if lock_available else "coordination_unavailable" + return {"state": state, "fetched": 0, "upserted": 0} + + lease_lost = asyncio.Event() + renewal: asyncio.Task[None] | None = None + if lock_acquired and redis_client is not None: + renewal = asyncio.create_task(_renew_lock(redis_client, lock_key, token, lease_lost)) + + try: + async with async_session_factory() as db: + source_config = await earth_news.get_earth_news_sources_payload(db) + sources = await earth_news.get_configured_sources_for_region( + db, active_region, config_payload=source_config + ) + if not sources: + return { + "state": "failed", + "error_code": "source_unavailable", + "fetched": 0, + "upserted": 0, + } + + item_count, newest_at = await get_earth_news_freshness(db, active_region=active_region) + expected_keys = earth_news._expected_feed_keys(sources, active_region=active_region) + if not expected_keys: + return { + "state": "failed", + "error_code": "source_unavailable", + "fetched": 0, + "upserted": 0, + } + + now = datetime.now(UTC) + needs_full_refresh = force or earth_news._needs_rss_supplement( + item_count=item_count, newest_at=newest_at + ) + covered_keys = await get_earth_news_feed_coverage( + db, + active_region=active_region, + recent_after=now - timedelta(seconds=earth_news.RSS_SUPPLEMENT_MAX_AGE_SECONDS), + ) + required_keys = expected_keys if needs_full_refresh else expected_keys - covered_keys + if not required_keys: + return { + "state": "completed", + "successful_sources": 0, + "failed_sources": 0, + "fetched": 0, + "upserted": 0, + } + + selected_sources, cooling_keys = _select_feeds( + sources, + active_region=active_region, + required_keys=required_keys, + redis_client=redis_client, + ) + if cooling_keys: + logger.info_event( + "Skipping failed Earth news feeds during cooldown", + event="earth_news.rss.cooldown_active", + context={"region": active_region, "feed_count": len(cooling_keys)}, + ) + if not selected_sources: + return { + "state": "failed", + "error_code": "source_unavailable", + "fetched": 0, + "upserted": 0, + } + + fetched_items, _errors, health_by_source = ( + await earth_news._fetch_rss_items_for_sources( + selected_sources, + active_region=active_region, + config_payload=source_config, + ) + ) + if lease_lost.is_set(): + await db.rollback() + return {"state": "busy", "fetched": 0, "upserted": 0} + _record_failed_feed_cooldowns( + redis_client, + active_region=active_region, + health_by_source=health_by_source, + sources=selected_sources, + ) + await earth_news.record_earth_news_sources_health(db, health_by_source) + if lease_lost.is_set(): + await db.rollback() + return {"state": "busy", "fetched": 0, "upserted": 0} + ranked_items = earth_news._rank_and_trim_items( + fetched_items, active_region=active_region + ) + await earth_news._enqueue_unverified_locations(ranked_items) + upserted = await upsert_earth_news_items(db, ranked_items) + if lease_lost.is_set(): + await db.rollback() + return {"state": "busy", "fetched": len(fetched_items), "upserted": 0} + await db.commit() + successful_sources = sum(bool(health.get("ok")) for health in health_by_source.values()) + failed_sources = max(0, len(selected_sources) - successful_sources) + state = "completed" if successful_sources else "failed" + failed_statuses = { + str(health.get("status") or "") + for health in health_by_source.values() + if not health.get("ok") + } + error_code = None + if not successful_sources: + error_code = "timeout" if failed_statuses == {"timeout"} else "source_unavailable" + return { + "state": state, + "error_code": error_code, + "successful_sources": successful_sources, + "failed_sources": failed_sources, + "fetched": len(fetched_items), + "upserted": upserted, + } + except Exception as exc: + logger.warning_event( + "Earth news periodic RSS refresh failed", + event="earth_news.rss.refresh_failed", + context={"region": active_region, "error": str(exc)}, + ) + raise + finally: + if renewal is not None: + renewal.cancel() + with suppress(asyncio.CancelledError): + await renewal + if lock_acquired and redis_client is not None: + release_script = """ + if redis.call('get', KEYS[1]) == ARGV[1] then + return redis.call('del', KEYS[1]) + end + return 0 + """ + try: + redis_client.eval(release_script, 1, lock_key, token) + except Exception as exc: + logger.warning_event( + "Earth news refresh lock release failed", + event="earth_news.rss.refresh_lock_release_failed", + context={"region": active_region, "error": str(exc)}, + ) + + +async def refresh_earth_news_all_regions() -> None: + for active_region in earth_news.REGION_ANCHORS: + try: + await refresh_earth_news_region(active_region) + except asyncio.CancelledError: + raise + except Exception: + continue diff --git a/backend/app/services/earth_news_store.py b/backend/app/services/earth_news_store.py index fa8ad4d2..91fccbee 100644 --- a/backend/app/services/earth_news_store.py +++ b/backend/app/services/earth_news_store.py @@ -278,22 +278,25 @@ async def get_earth_news_feed_coverage( active_region: str, recent_after: datetime | None = None, ) -> set[tuple[str, str]]: - query = select( - EarthNewsItem.id, - EarthNewsItem.location_meta.op("->")("news_meta").op("->>")("source_id"), - EarthNewsItem.location_meta.op("->")("news_meta").op("->>")("feed_id"), + news_meta = EarthNewsItem.location_meta.op("->")("news_meta") + source_id = func.coalesce( + func.nullif(news_meta.op("->>")("source_id"), ""), + func.split_part(EarthNewsItem.id, ":", 1), ) + feed_id = func.nullif(news_meta.op("->>")("feed_id"), "") + query = select( + source_id, + feed_id, + ).where(source_id != "", feed_id.is_not(None)).distinct() if active_region != "global": query = query.where(EarthNewsItem.region.in_({"global", active_region})) if recent_after is not None: query = query.where(func.coalesce(EarthNewsItem.published_at, EarthNewsItem.last_seen_at) >= recent_after) result = await db.execute(query) coverage: set[tuple[str, str]] = set() - for item_id, source_id, feed_id in result.all(): + for source_id, feed_id in result.all(): normalized_source_id = str(source_id or "").strip() normalized_feed_id = str(feed_id or "").strip() - if not normalized_source_id and isinstance(item_id, str) and ":" in item_id: - normalized_source_id = item_id.split(":", 1)[0] if normalized_source_id and normalized_feed_id: coverage.add((normalized_source_id, normalized_feed_id)) return coverage @@ -340,30 +343,49 @@ async def upsert_earth_news_items(db: AsyncSession, items: list[ParsedNewsItem]) changed += 1 continue - record.title = item.title - record.summary = item.summary - record.url = item.url - record.source = item.source - record.feed_name = item.feed_name - record.region = item.feed_region - record.homepage_url = item.homepage_url - record.published_at = item.published_at + visible_changed = False + for field_name, value in ( + ("title", item.title), + ("summary", item.summary), + ("url", item.url), + ("source", item.source), + ("feed_name", item.feed_name), + ("region", item.feed_region), + ("homepage_url", item.homepage_url), + ("published_at", item.published_at), + ): + if getattr(record, field_name) != value: + setattr(record, field_name, value) + visible_changed = True record.last_seen_at = now location_meta = dict(record.location_meta or {}) - location_meta["news_meta"] = _news_meta_patch(item) - record.location_meta = location_meta + news_meta = _news_meta_patch(item) + if location_meta.get("news_meta") != news_meta: + location_meta["news_meta"] = news_meta + record.location_meta = location_meta + visible_changed = True if item.localizations: merged_localizations = { **dict(record.localizations or {}), **dict(item.localizations or {}), } - record.content_language = item.content_language - record.localizations = merged_localizations + if record.content_language != item.content_language: + record.content_language = item.content_language + visible_changed = True + if dict(record.localizations or {}) != merged_localizations: + record.localizations = merged_localizations + visible_changed = True if item.enrichment_status != "pending" or item.enrichment_error or item.enriched_at: - record.enrichment_status = item.enrichment_status - record.enrichment_error = item.enrichment_error - record.enriched_at = item.enriched_at - changed += 1 + for field_name, value in ( + ("enrichment_status", item.enrichment_status), + ("enrichment_error", item.enrichment_error), + ("enriched_at", item.enriched_at), + ): + if getattr(record, field_name) != value: + setattr(record, field_name, value) + visible_changed = True + if visible_changed: + changed += 1 await db.flush() return changed diff --git a/backend/app/services/earth_outbox_maintenance.py b/backend/app/services/earth_outbox_maintenance.py new file mode 100644 index 00000000..d3d3655f --- /dev/null +++ b/backend/app/services/earth_outbox_maintenance.py @@ -0,0 +1,184 @@ +"""Bounded retention for consumed Earth change events.""" + +from __future__ import annotations + +import asyncio +import os +from datetime import UTC, datetime, timedelta +from typing import AsyncContextManager, Protocol + +from app.core.logging import get_logger + +logger = get_logger(__name__) + +INDEX_NAME = "idx_earth_data_change_events_consumed_retention" +DEFAULT_RETENTION_DAYS = 1 +DEFAULT_BATCH_SIZE = 1000 +DEFAULT_PAUSE_SECONDS = 0.1 +MAINTENANCE_LOCK_KEY = (17001613, 1) + +DELETE_BATCH_SQL = """ +WITH doomed AS ( + SELECT id + FROM earth_data_change_events + WHERE consumed_at IS NOT NULL AND consumed_at < $1 + ORDER BY consumed_at, id + LIMIT $2 + FOR UPDATE SKIP LOCKED +), deleted AS ( + DELETE FROM earth_data_change_events AS events + USING doomed + WHERE events.id = doomed.id + RETURNING events.id +) +SELECT count(*) FROM deleted +""" + + +class OutboxConnection(Protocol): + async def fetchval(self, query: str, *args: object) -> object: ... + + async def fetchrow(self, query: str, *args: object) -> object: ... + + async def execute(self, query: str, *args: object) -> object: ... + + def transaction(self) -> AsyncContextManager[object]: ... + + +def configured_retention_days() -> int: + raw = os.getenv("PLANET_EARTH_OUTBOX_RETENTION_DAYS", str(DEFAULT_RETENTION_DAYS)) + try: + days = int(raw) + if 1 <= days <= 3650: + return days + except ValueError: + pass + logger.warning_event( + "Invalid Earth outbox retention; using default", + event="earth.outbox.retention_invalid", + context={"value": raw}, + ) + return DEFAULT_RETENTION_DAYS + + +async def try_maintenance_lock(conn: OutboxConnection) -> bool: + return bool(await conn.fetchval("SELECT pg_try_advisory_lock($1, $2)", *MAINTENANCE_LOCK_KEY)) + + +async def release_maintenance_lock(conn: OutboxConnection) -> None: + await conn.fetchval("SELECT pg_advisory_unlock($1, $2)", *MAINTENANCE_LOCK_KEY) + + +async def retention_index_state(conn: OutboxConnection) -> str: + row = await conn.fetchrow( + """ + SELECT indexes.indisvalid, indexes.indisready + FROM pg_index AS indexes + JOIN pg_class AS index_table ON index_table.oid = indexes.indexrelid + WHERE indexes.indrelid = 'earth_data_change_events'::regclass + AND index_table.relname = $1 + """, + INDEX_NAME, + ) + if row is None: + return "missing" + return "ready" if row["indisvalid"] and row["indisready"] else "invalid" + + +async def ensure_retention_index(conn: OutboxConnection) -> None: + """Call on an autocommit connection, never inside app init_db's transaction.""" + state = await retention_index_state(conn) + if state == "invalid": + await conn.execute(f"DROP INDEX CONCURRENTLY IF EXISTS {INDEX_NAME}") + if state != "ready": + await conn.execute( + f"CREATE INDEX CONCURRENTLY IF NOT EXISTS {INDEX_NAME} " + "ON earth_data_change_events (consumed_at, id) WHERE consumed_at IS NOT NULL" + ) + if await retention_index_state(conn) != "ready": + raise RuntimeError("Earth outbox retention index is not valid and ready") + + +async def purge_consumed_events( + conn: OutboxConnection, + *, + retention_days: int, + batch_size: int = DEFAULT_BATCH_SIZE, + max_batches: int = 1, + pause_seconds: float = DEFAULT_PAUSE_SECONDS, +) -> int: + if not 1 <= retention_days <= 3650: + raise ValueError("retention_days must be between 1 and 3650") + if batch_size < 1 or max_batches < 1 or pause_seconds < 0: + raise ValueError("batch_size/max_batches must be positive and pause_seconds non-negative") + if await retention_index_state(conn) != "ready": + logger.warning_event( + "Skipping Earth outbox retention because its index is unavailable", + event="earth.outbox.retention_index_unavailable", + ) + return 0 + + cutoff = datetime.now(UTC) - timedelta(days=retention_days) + deleted_total = 0 + for batch_number in range(max_batches): + deleted = int(await conn.fetchval(DELETE_BATCH_SQL, cutoff, batch_size) or 0) + deleted_total += deleted + if deleted < batch_size: + break + if batch_number + 1 < max_batches and pause_seconds: + await asyncio.sleep(pause_seconds) + if deleted_total: + logger.info_event( + "Purged consumed Earth outbox events", + event="earth.outbox.retention_purged", + context={"deleted": deleted_total, "retention_days": retention_days}, + ) + return deleted_total + + +async def compact_consumed_events( + conn: OutboxConnection, + *, + retention_days: int, + lock_timeout_seconds: int = 10, + statement_timeout_seconds: int = 900, +) -> tuple[int, int]: + """One-time atomic rewrite; blocks table access until the transaction commits.""" + if not 1 <= retention_days <= 3650: + raise ValueError("retention_days must be between 1 and 3650") + if lock_timeout_seconds < 1 or statement_timeout_seconds < 1: + raise ValueError("timeouts must be positive") + cutoff = datetime.now(UTC) - timedelta(days=retention_days) + async with conn.transaction(): + await conn.fetchval( + "SELECT set_config('lock_timeout', $1, true)", f"{lock_timeout_seconds}s" + ) + await conn.fetchval( + "SELECT set_config('statement_timeout', $1, true)", f"{statement_timeout_seconds}s" + ) + await conn.execute("LOCK TABLE earth_data_change_events IN ACCESS EXCLUSIVE MODE") + await conn.execute( + """ + CREATE TEMP TABLE earth_outbox_retained ON COMMIT DROP AS + SELECT * FROM earth_data_change_events + WHERE consumed_at IS NULL OR consumed_at >= $1 + """, + cutoff, + ) + retained = await conn.fetchrow(""" + SELECT count(*) AS total, count(*) FILTER (WHERE consumed_at IS NULL) AS pending + FROM earth_outbox_retained + """) + if retained is None: + raise RuntimeError("Unable to verify retained Earth outbox rows") + await conn.execute("TRUNCATE TABLE earth_data_change_events CONTINUE IDENTITY RESTRICT") + await conn.execute( + "INSERT INTO earth_data_change_events SELECT * FROM earth_outbox_retained" + ) + restored = await conn.fetchrow(""" + SELECT count(*) AS total, count(*) FILTER (WHERE consumed_at IS NULL) AS pending + FROM earth_data_change_events + """) + if restored is None or dict(retained) != dict(restored): + raise RuntimeError("Earth outbox compact verification failed; transaction rolled back") + return int(retained["total"]), int(retained["pending"]) diff --git a/backend/app/services/scheduler.py b/backend/app/services/scheduler.py index 056ad827..abddd811 100644 --- a/backend/app/services/scheduler.py +++ b/backend/app/services/scheduler.py @@ -2,9 +2,11 @@ import asyncio from datetime import UTC, datetime, timedelta +import time from typing import Any, Dict, Optional from apscheduler.schedulers.asyncio import AsyncIOScheduler +from apscheduler.triggers.date import DateTrigger from apscheduler.triggers.interval import IntervalTrigger from sqlalchemy import select @@ -14,19 +16,44 @@ from app.db.session import async_session_factory from app.core.time import to_iso8601_utc from app.models.datasource import DataSource from app.models.task import CollectionTask -from app.services.business_logs import emit_business_log, emit_business_log_background, exception_context +from app.services.business_logs import ( + emit_business_log, + emit_business_log_background, + exception_context, +) from app.services.collectors.registry import collector_registry from app.services.datasource_connectivity import ( build_builtin_connectivity_checksum, get_builtin_effective_candidate, save_connectivity_success, ) +from app.services.earth_news_refresh import ( + REFRESH_INTERVAL_SECONDS as EARTH_NEWS_REFRESH_INTERVAL_SECONDS, + create_earth_news_refresh_status, + refresh_earth_news_all_regions, + refresh_earth_news_region, + set_earth_news_refresh_status, + touch_earth_news_refresh_status, + REFRESH_STATUS_HEARTBEAT_SECONDS as EARTH_NEWS_STATUS_HEARTBEAT_SECONDS, +) +from app.services.earth_news import REGION_ANCHORS logger = get_logger(__name__) scheduler = AsyncIOScheduler() RUNNING_TASK_GUARD_TIMEOUT_MINUTES = 90 RUNNING_COLLECTOR_TASKS: dict[str, asyncio.Task[Any]] = {} +EARTH_NEWS_REFRESH_JOB_ID = "earth_news_rss_refresh" +_pending_earth_news_refreshes: dict[str, dict[str, Any]] = {} +_running_earth_news_refreshes: set[str] = set() +_rerun_earth_news_refreshes: dict[str, dict[str, Any]] = {} +EARTH_NEWS_REFRESH_WAIT_SECONDS = 300 +EARTH_NEWS_REFRESH_POLL_SECONDS = 1 +EARTH_NEWS_REFRESH_PUBLIC_ERRORS = { + "source_unavailable": "No news source could be refreshed for this region. Please retry.", + "timeout": "News sources timed out. Please try again.", + "refresh_failed": "Could not refresh news. Please try again.", +} def _collector_task_name(collector_name: str) -> str: @@ -86,7 +113,10 @@ async def _apply_datasource_schedule(datasource: DataSource, session) -> None: logger.info_event( "Scheduled collector", event="collector.schedule.updated", - context={"collector_name": datasource.source, "frequency_minutes": datasource.frequency_minutes}, + context={ + "collector_name": datasource.source, + "frequency_minutes": datasource.frequency_minutes, + }, ) else: logger.info_event( @@ -133,7 +163,11 @@ async def run_collector_task(collector_name: str): category="collector", service="scheduler", module=__name__, - context={"collector_name": collector_name, "datasource_id": datasource.id, "status": "skipped"}, + context={ + "collector_name": collector_name, + "datasource_id": datasource.id, + "status": "skipped", + }, ) return @@ -153,9 +187,8 @@ async def run_collector_task(collector_name: str): if started_at is not None and started_at.tzinfo is None: started_at = started_at.replace(tzinfo=UTC) - is_stale = ( - started_at is not None - and (now - started_at) > timedelta(minutes=RUNNING_TASK_GUARD_TIMEOUT_MINUTES) + is_stale = started_at is not None and (now - started_at) > timedelta( + minutes=RUNNING_TASK_GUARD_TIMEOUT_MINUTES ) if not is_stale: logger.warning_event( @@ -189,9 +222,7 @@ async def run_collector_task(collector_name: str): existing_running.phase = "failed" existing_running.completed_at = now existing_running.error_message = ( - f"{existing_error}\n{stale_reason}".strip() - if existing_error - else stale_reason + f"{existing_error}\n{stale_reason}".strip() if existing_error else stale_reason ) await db.commit() logger.warning_event( @@ -231,7 +262,11 @@ async def run_collector_task(collector_name: str): category="collector", service="scheduler", module=__name__, - context={"collector_name": collector_name, "datasource_id": datasource_id, "status": "running"}, + context={ + "collector_name": collector_name, + "datasource_id": datasource_id, + "status": "running", + }, ) task_result = await collector.run(db) datasource = await db.get(DataSource, datasource_id) @@ -265,7 +300,11 @@ async def run_collector_task(collector_name: str): logger.info_event( "Collector completed", event="collector.run.completed", - context={"collector_name": collector_name, "datasource_id": datasource_id, "result": task_result}, + context={ + "collector_name": collector_name, + "datasource_id": datasource_id, + "result": task_result, + }, ) await emit_business_log( logger, @@ -300,7 +339,11 @@ async def run_collector_task(collector_name: str): level="warning", service="scheduler", module=__name__, - context={"collector_name": collector_name, "datasource_id": datasource.id, "status": "cancelled"}, + context={ + "collector_name": collector_name, + "datasource_id": datasource.id, + "status": "cancelled", + }, ) raise except Exception as exc: @@ -312,7 +355,11 @@ async def run_collector_task(collector_name: str): logger.exception_event( "Collector failed", event="collector.run.failed", - context={"collector_name": collector_name, "datasource_id": datasource.id, "error": str(exc)}, + context={ + "collector_name": collector_name, + "datasource_id": datasource.id, + "error": str(exc), + }, ) await emit_business_log( logger, @@ -324,7 +371,11 @@ async def run_collector_task(collector_name: str): module=__name__, context=exception_context( exc, - {"collector_name": collector_name, "datasource_id": datasource.id, "status": "failed"}, + { + "collector_name": collector_name, + "datasource_id": datasource.id, + "status": "failed", + }, ), ) @@ -349,7 +400,9 @@ async def cleanup_stale_running_tasks(max_age_hours: int = 2) -> int: task.completed_at = datetime.now(UTC) existing_error = (task.error_message or "").strip() cleanup_error = "Marked failed automatically after stale running task cleanup" - task.error_message = f"{existing_error}\n{cleanup_error}".strip() if existing_error else cleanup_error + task.error_message = ( + f"{existing_error}\n{cleanup_error}".strip() if existing_error else cleanup_error + ) if stale_tasks: await db.commit() @@ -365,6 +418,17 @@ async def cleanup_stale_running_tasks(max_age_hours: int = 2) -> int: def start_scheduler() -> None: """Start the scheduler.""" if not scheduler.running: + scheduler.add_job( + refresh_earth_news_all_regions, + trigger=IntervalTrigger(seconds=EARTH_NEWS_REFRESH_INTERVAL_SECONDS), + id=EARTH_NEWS_REFRESH_JOB_ID, + name="Earth news RSS refresh", + replace_existing=True, + next_run_time=datetime.now(UTC), + max_instances=1, + coalesce=True, + misfire_grace_time=60, + ) scheduler.start() logger.info_event("Scheduler started", event="scheduler.started") @@ -376,6 +440,205 @@ def stop_scheduler() -> None: logger.info_event("Scheduler stopped", event="scheduler.stopped") +def schedule_earth_news_region_refresh( + region: str, *, force: bool = False, refresh_id: str | None = None +) -> bool: + """Queue one immediate, per-region RSS refresh and merge duplicate requests.""" + normalized_region = str(region or "").strip().lower() + if normalized_region not in REGION_ANCHORS: + raise ValueError(f"Unsupported Earth news region: {region}") + + if normalized_region in _running_earth_news_refreshes: + rerun = _rerun_earth_news_refreshes.setdefault( + normalized_region, {"force": False, "refresh_id": None} + ) + rerun["force"] = rerun["force"] or force + rerun["refresh_id"] = refresh_id or rerun["refresh_id"] + return False + if normalized_region in _pending_earth_news_refreshes: + pending = _pending_earth_news_refreshes[normalized_region] + pending["force"] = pending["force"] or force + pending["refresh_id"] = refresh_id or pending["refresh_id"] + return False + + _pending_earth_news_refreshes[normalized_region] = { + "force": force, + "refresh_id": refresh_id, + } + job_id = _earth_news_region_refresh_job_id(normalized_region) + try: + scheduler.add_job( + _run_earth_news_region_refresh, + trigger=DateTrigger(run_date=datetime.now(UTC)), + id=job_id, + name=f"Earth news RSS refresh: {normalized_region}", + kwargs={"region": normalized_region}, + replace_existing=False, + max_instances=1, + coalesce=True, + misfire_grace_time=60, + ) + except Exception: + _pending_earth_news_refreshes.pop(normalized_region, None) + raise + return True + + +def request_earth_news_region_refresh(region: str) -> dict[str, Any]: + normalized_region = str(region or "").strip().lower() + if normalized_region not in REGION_ANCHORS: + raise ValueError(f"Unsupported Earth news region: {region}") + status, created = create_earth_news_refresh_status(normalized_region) + if created: + try: + schedule_earth_news_region_refresh( + normalized_region, + force=True, + refresh_id=status["refresh_id"], + ) + except Exception: + return set_earth_news_refresh_status( + status["refresh_id"], + normalized_region, + "failed", + error={ + "code": "refresh_failed", + "message": EARTH_NEWS_REFRESH_PUBLIC_ERRORS["refresh_failed"], + }, + ) + return status + + +def schedule_earth_news_refresh_for_all_regions(*, force: bool = False) -> None: + for region in REGION_ANCHORS: + schedule_earth_news_region_refresh(region, force=force) + + +def _earth_news_region_refresh_job_id(region: str) -> str: + return f"{EARTH_NEWS_REFRESH_JOB_ID}:{region}" + + +async def _run_earth_news_region_refresh(region: str) -> None: + request = _pending_earth_news_refreshes.pop(region, {"force": False, "refresh_id": None}) + force = bool(request["force"]) + refresh_id = request["refresh_id"] + _running_earth_news_refreshes.add(region) + status_heartbeat: asyncio.Task[None] | None = None + try: + if refresh_id: + set_earth_news_refresh_status(refresh_id, region, "running") + if not touch_earth_news_refresh_status(refresh_id, region): + return + status_heartbeat = asyncio.create_task( + _earth_news_refresh_status_heartbeat(refresh_id, region) + ) + deadline = time.monotonic() + EARTH_NEWS_REFRESH_WAIT_SECONDS + while True: + result = await refresh_earth_news_region(region, force=force) + if result["state"] != "busy": + break + if time.monotonic() >= deadline: + set_earth_news_refresh_status( + refresh_id, + region, + "failed", + error={ + "code": "refresh_failed", + "message": EARTH_NEWS_REFRESH_PUBLIC_ERRORS["refresh_failed"], + }, + ) + return + await asyncio.sleep(EARTH_NEWS_REFRESH_POLL_SECONDS) + if result["state"] == "coordination_unavailable": + error_code = "refresh_failed" + elif result["state"] == "failed": + error_code = result.get("error_code") or "source_unavailable" + elif result["state"] == "completed" and result.get("successful_sources", 0) > 0: + set_earth_news_refresh_status(refresh_id, region, "succeeded") + return + else: + error_code = "source_unavailable" + set_earth_news_refresh_status( + refresh_id, + region, + "failed", + error={ + "code": error_code, + "message": EARTH_NEWS_REFRESH_PUBLIC_ERRORS.get( + error_code, EARTH_NEWS_REFRESH_PUBLIC_ERRORS["source_unavailable"] + ), + }, + ) + else: + await refresh_earth_news_region(region, force=force) + except asyncio.CancelledError: + if refresh_id: + set_earth_news_refresh_status( + refresh_id, + region, + "failed", + error={ + "code": "refresh_failed", + "message": EARTH_NEWS_REFRESH_PUBLIC_ERRORS["refresh_failed"], + }, + ) + raise + except Exception as exc: + logger.warning_event( + "Earth news tracked refresh failed", + event="earth_news.rss.tracked_refresh_failed", + context={"region": region, "error": str(exc)}, + ) + if refresh_id: + try: + set_earth_news_refresh_status( + refresh_id, + region, + "failed", + error={ + "code": "refresh_failed", + "message": EARTH_NEWS_REFRESH_PUBLIC_ERRORS["refresh_failed"], + }, + ) + except Exception as status_exc: + logger.warning_event( + "Earth news refresh status update failed", + event="earth_news.rss.refresh_status_update_failed", + context={"region": region, "error": str(status_exc)}, + ) + finally: + if status_heartbeat is not None: + status_heartbeat.cancel() + try: + await status_heartbeat + except asyncio.CancelledError: + pass + _running_earth_news_refreshes.discard(region) + rerun = _rerun_earth_news_refreshes.pop(region, None) + if rerun is not None and scheduler.running: + schedule_earth_news_region_refresh( + region, + force=rerun["force"], + refresh_id=rerun["refresh_id"], + ) + + +async def _earth_news_refresh_status_heartbeat(refresh_id: str, region: str) -> None: + try: + while True: + await asyncio.sleep(EARTH_NEWS_STATUS_HEARTBEAT_SECONDS) + if not touch_earth_news_refresh_status(refresh_id, region): + return + except asyncio.CancelledError: + raise + except Exception as exc: + logger.warning_event( + "Earth news refresh status heartbeat failed", + event="earth_news.rss.refresh_status_heartbeat_failed", + context={"region": region, "error": str(exc)}, + ) + + async def sync_scheduler_with_datasources() -> None: """Synchronize scheduler jobs with datasource table.""" async with async_session_factory() as db: @@ -384,7 +647,10 @@ async def sync_scheduler_with_datasources() -> None: configured_sources = {datasource.source for datasource in datasources} for job in list(scheduler.get_jobs()): - if job.id not in configured_sources: + is_earth_news_refresh = job.id == EARTH_NEWS_REFRESH_JOB_ID or job.id.startswith( + f"{EARTH_NEWS_REFRESH_JOB_ID}:" + ) + if job.id not in configured_sources and not is_earth_news_refresh: scheduler.remove_job(job.id) for datasource in datasources: @@ -461,7 +727,9 @@ def run_collector_now(collector_name: str) -> bool: return False try: - task = asyncio.create_task(run_collector_task(collector_name), name=_collector_task_name(collector_name)) + task = asyncio.create_task( + run_collector_task(collector_name), name=_collector_task_name(collector_name) + ) RUNNING_COLLECTOR_TASKS[collector_name] = task def _cleanup_task(done_task: asyncio.Task[Any]) -> None: diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 3f12b53a..b00e3f29 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -8,6 +8,37 @@ from unittest.mock import AsyncMock, MagicMock from sqlalchemy.ext.asyncio import AsyncSession +@pytest.fixture(autouse=True) +def persisted_test_logs(monkeypatch): + """Keep application log persistence in memory, including business-log calls.""" + from app.models.system_log import ObservabilityEventGroup + from app.services import persistent_logs + + entries = [] + groups = {} + + class LogSession: + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, traceback): + return False + + def add(self, item): + entries.append(item) + if isinstance(item, ObservabilityEventGroup): + groups[item.fingerprint] = item + + async def get(self, model, key): + return groups.get(key) if model is ObservabilityEventGroup else None + + async def commit(self): + return None + + monkeypatch.setattr(persistent_logs, "async_session_factory", LogSession) + return entries + + @pytest.fixture(autouse=True) def bgp_collector_location_cache(): """Mirror app startup seeding for tests that call sync BGP helpers.""" diff --git a/backend/tests/test_bgp.py b/backend/tests/test_bgp.py index f76dc7f6..50260b94 100644 --- a/backend/tests/test_bgp.py +++ b/backend/tests/test_bgp.py @@ -1,5 +1,6 @@ """Tests for BGP observability helpers.""" +import ipaddress from datetime import UTC, datetime, timedelta from types import SimpleNamespace @@ -21,13 +22,20 @@ from app.services.collectors.bgp_common import ( create_bgp_anomalies_for_batch, save_bgp_observations_for_batch, ) -from app.services.bgp_enrichment import enrich_bgp_events_for_batch, extract_bgp_network_fields +from app.services.bgp_enrichment import ( + enrich_bgp_events_for_batch, + extract_bgp_network_fields, + lookup_prefix_geography, +) from app.services.bgp_incidents import ( create_bgp_incidents_for_anomalies, infer_related_infrastructure, ) from app.services.bgp_collectors import build_bgp_collector_coverage -from app.api.v1.visualization import convert_bgp_incidents_to_geojson, build_incident_geography_hints +from app.api.v1.visualization import ( + convert_bgp_incidents_to_geojson, + build_incident_geography_hints, +) from app.models.bgp_anomaly import BGPAnomaly from app.models.collected_data import CollectedData from app.models.bgp_incident import BGPIncident @@ -58,8 +66,7 @@ class _FakeResult: def all(self): if self._rows and all(isinstance(row, BGPObservation) for row in self._rows): return [ - (row.prefix, row.origin_asn, row.collector, row.collector_geo) - for row in self._rows + (row.prefix, row.origin_asn, row.collector, row.collector_geo) for row in self._rows ] return self._rows @@ -93,6 +100,8 @@ class _FakeAsyncSession: self.commits = 0 async def execute(self, _stmt, _params=None): + if str(_stmt).lstrip().startswith("SET LOCAL jit"): + return _FakeResult([]) if not self._results: return _FakeResult([]) return _FakeResult(self._results.pop(0)) @@ -107,6 +116,49 @@ class _FakeAsyncSession: self.commits += 1 +class _StrictFakeAsyncSession(_FakeAsyncSession): + async def execute(self, stmt, params=None): + if not str(stmt).lstrip().startswith("SET LOCAL jit") and not self._results: + raise AssertionError(f"Unexpected BGP query: {stmt}") + return await super().execute(stmt, params) + + +@pytest.mark.asyncio +async def test_prefix_geography_keeps_source_priority_and_ipv6_range_parameters(): + calls = [] + + class GeoSession: + async def execute(self, _stmt, params=None): + if str(_stmt).lstrip().startswith("SET LOCAL jit"): + return _FakeResult([]) + calls.append(dict(params)) + if params["source"] == "nro_delegated_prefix_geo": + return _FakeResult( + [ + { + "metadata": { + "country_code": "GB", + "prefix": "2001:db8::/32", + } + } + ] + ) + return _FakeResult([]) + + network = ipaddress.ip_network("2001:db8:1::/48") + result = await lookup_prefix_geography(GeoSession(), [str(network), "invalid-prefix"]) + + assert result[str(network)]["source"] == "nro_delegated_stats" + assert [call["source"] for call in calls] == [ + "opengeofeed_prefix_geo", + "iptoasn_prefix_geo", + "nro_delegated_prefix_geo", + ] + assert all(call["family"] == "ipv6" for call in calls) + assert all(call["range_start"] == str(network.network_address) for call in calls) + assert all(call["range_end"] == str(network.broadcast_address) for call in calls) + + def test_normalize_bgp_event_from_live_payload(): event = normalize_bgp_event( { @@ -449,7 +501,12 @@ def test_detect_route_leak_anomalies_creates_candidate_for_divergent_long_paths( "prefix": "203.0.113.0/24", "origin_asn": 64496, "as_path": [64500, 64496], - "collector_location": {"country": "NL", "city": "Amsterdam", "latitude": 52.3, "longitude": 4.9}, + "collector_location": { + "country": "NL", + "city": "Amsterdam", + "latitude": 52.3, + "longitude": 4.9, + }, "enrichment": {"prefix_scope": {"regions": [{"country": "NL"}]}}, } }, @@ -460,7 +517,12 @@ def test_detect_route_leak_anomalies_creates_candidate_for_divergent_long_paths( "prefix": "203.0.113.0/24", "origin_asn": 64496, "as_path": [64510, 64520, 64530, 64540, 64496], - "collector_location": {"country": "GB", "city": "London", "latitude": 51.5, "longitude": -0.1}, + "collector_location": { + "country": "GB", + "city": "London", + "latitude": 51.5, + "longitude": -0.1, + }, "enrichment": {"prefix_scope": {"regions": [{"country": "GB"}]}}, } }, @@ -481,7 +543,9 @@ def test_detect_route_leak_anomalies_creates_candidate_for_divergent_long_paths( def test_detect_path_flap_anomalies_creates_signal_for_repeated_state_changes(): base_timestamp = datetime(2026, 3, 27, 0, 0, tzinfo=UTC) events = [] - for index, event_type in enumerate(["announcement", "withdrawal", "announcement", "withdrawal"]): + for index, event_type in enumerate( + ["announcement", "withdrawal", "announcement", "withdrawal"] + ): events.append( { "metadata": { @@ -491,7 +555,12 @@ def test_detect_path_flap_anomalies_creates_signal_for_repeated_state_changes(): "prefix": "198.51.100.0/24", "origin_asn": 64512, "as_path": [64500 + index, 64512] if event_type == "announcement" else [], - "collector_location": {"country": "NL", "city": "Amsterdam", "latitude": 52.3, "longitude": 4.9}, + "collector_location": { + "country": "NL", + "city": "Amsterdam", + "latitude": 52.3, + "longitude": 4.9, + }, "enrichment": {"prefix_scope": {"regions": [{"country": "NL"}]}}, } } @@ -920,7 +989,9 @@ async def test_create_bgp_incidents_for_anomalies_refreshes_existing_incident(): with patch( "app.services.bgp_incidents.infer_related_infrastructure", - new=AsyncMock(return_value={"related_cables": [{"landing_point": "NYC"}], "related_ixps": []}), + new=AsyncMock( + return_value={"related_cables": [{"landing_point": "NYC"}], "related_ixps": []} + ), ): created = await create_bgp_incidents_for_anomalies( db, @@ -1132,13 +1203,17 @@ async def test_create_bgp_anomalies_for_batch_calls_incident_aggregation(): source="ris_live_bgp", extra_data={"prefix": "203.0.113.0/24", "origin_asn": 64496}, ) - db = _FakeAsyncSession([ - [], - [], - [], - [previous_record], - [], - ]) + db = _StrictFakeAsyncSession( + [ + [], # Historical BGP observations + [], # OpenGeoFeed prefix geography + [], # IPtoASN prefix geography + [], # NRO delegated prefix geography + [], # PeeringDB ASN profiles + [previous_record], # Prior collected snapshot for origin-change detection + [], # Existing anomaly entity keys + ] + ) events = [ { "reference_date": "2026-03-30T10:00:00Z", @@ -1178,6 +1253,7 @@ async def test_create_bgp_anomalies_for_batch_calls_incident_aggregation(): assert anomaly.anomaly_type == "origin_change" assert anomaly.prefix == "203.0.113.0/24" incident_mock.assert_awaited_once() + assert not db._results @pytest.mark.asyncio @@ -1197,14 +1273,18 @@ async def test_create_bgp_anomalies_for_batch_skips_existing_entity_keys(): origin_asn=64496, new_origin_asn=64497, ) - db = _FakeAsyncSession([ - [], - [], - [], - [previous_record], - [existing_key], - [existing_anomaly], - ]) + db = _StrictFakeAsyncSession( + [ + [], # Historical BGP observations + [], # OpenGeoFeed prefix geography + [], # IPtoASN prefix geography + [], # NRO delegated prefix geography + [], # PeeringDB ASN profiles + [previous_record], # Prior collected snapshot for origin-change detection + [existing_key], + [existing_anomaly], + ] + ) events = [ { "reference_date": "2026-03-30T10:00:00Z", @@ -1235,6 +1315,7 @@ async def test_create_bgp_anomalies_for_batch_skips_existing_entity_keys(): assert created == 0 assert len(db.added) == 0 incident_mock.assert_awaited_once() + assert not db._results async def _bgp_test_client(db_session): @@ -1242,7 +1323,9 @@ async def _bgp_test_client(db_session): yield db_session def override_get_current_user(): - return User(id=1, username="testuser", email="test@example.com", password_hash="x", role="admin") + return User( + id=1, username="testuser", email="test@example.com", password_hash="x", role="admin" + ) app.dependency_overrides[get_db] = override_get_db app.dependency_overrides[get_current_user] = override_get_current_user @@ -1264,7 +1347,7 @@ async def test_bgp_events_api_lists_observations(): origin_asn=64496, observed_at=datetime(2026, 3, 30, 10, 0, tzinfo=UTC), ) - db = _FakeAsyncSession([[observation]]) + db = _StrictFakeAsyncSession([[1], [observation]]) client = await _bgp_test_client(db) try: @@ -1278,6 +1361,7 @@ async def test_bgp_events_api_lists_observations(): assert payload["total"] == 1 assert payload["data"][0]["collector"] == "rrc00" assert payload["data"][0]["prefix"] == "203.0.113.0/24" + assert not db._results @pytest.mark.asyncio @@ -1376,7 +1460,18 @@ async def test_bgp_event_summary_api_returns_aggregates(): event_type="withdrawal", observed_at=datetime(2026, 3, 30, 10, 5, tzinfo=UTC), ) - db = _FakeAsyncSession([[observation_one, observation_two]]) + observations = [observation_one, observation_two] + db = _StrictFakeAsyncSession( + [ + [len(observations)], + [len({record.collector for record in observations})], + [len({record.prefix for record in observations})], + [ + (event_type, sum(record.event_type == event_type for record in observations)) + for event_type in sorted({record.event_type for record in observations}) + ], + ] + ) client = await _bgp_test_client(db) try: @@ -1392,6 +1487,7 @@ async def test_bgp_event_summary_api_returns_aggregates(): assert payload["prefix_count"] == 2 assert payload["by_type"]["announcement"] == 1 assert payload["by_type"]["withdrawal"] == 1 + assert not db._results @pytest.mark.asyncio diff --git a/backend/tests/test_bgp_prefix_geo.py b/backend/tests/test_bgp_prefix_geo.py new file mode 100644 index 00000000..388c396e --- /dev/null +++ b/backend/tests/test_bgp_prefix_geo.py @@ -0,0 +1,22 @@ +from unittest.mock import AsyncMock + +import pytest + +from app.db.bgp_prefix_geo import ( + BGP_PREFIX_GEO_FUNCTION_SQL, + BGP_PREFIX_GEO_INDEX_SQL, + install_bgp_prefix_geo_functions, +) + + +@pytest.mark.asyncio +async def test_fresh_database_installs_lookup_functions_without_large_index(): + connection = AsyncMock() + + await install_bgp_prefix_geo_functions(connection) + + statements = [str(call.args[0]) for call in connection.execute.call_args_list] + assert len(statements) == len(BGP_PREFIX_GEO_FUNCTION_SQL) == 2 + assert all("CREATE OR REPLACE FUNCTION" in statement for statement in statements) + assert all("CREATE INDEX" not in statement for statement in statements) + assert "CREATE INDEX CONCURRENTLY" in BGP_PREFIX_GEO_INDEX_SQL diff --git a/backend/tests/test_earth_layer_adapters.py b/backend/tests/test_earth_layer_adapters.py new file mode 100644 index 00000000..3d0d8cd5 --- /dev/null +++ b/backend/tests/test_earth_layer_adapters.py @@ -0,0 +1,15 @@ +from app.services.earth_layer_adapters import ( + get_earth_cache_patterns_for_source, + get_earth_update_layers_for_change, +) + + +def test_news_changes_do_not_invalidate_earth_summary_cache(): + assert get_earth_update_layers_for_change("earth_news_items", "earth_news_items") == ["news"] + assert get_earth_cache_patterns_for_source("earth_news_items") == [] + assert get_earth_cache_patterns_for_source("media_news_archive") == [] + + +def test_counted_layers_still_invalidate_earth_summary_cache(): + for source in ("aisstream_vessels", "arcgis_cables", "celestrak_tle", "top500", "ris_live_bgp"): + assert "summary*" in get_earth_cache_patterns_for_source(source) diff --git a/backend/tests/test_earth_layer_cache.py b/backend/tests/test_earth_layer_cache.py index 71528be9..0b972856 100644 --- a/backend/tests/test_earth_layer_cache.py +++ b/backend/tests/test_earth_layer_cache.py @@ -1,9 +1,11 @@ from __future__ import annotations +import asyncio import json +import httpx import pytest -from fastapi import Response +from fastapi import FastAPI, HTTPException, Response from app.api.v1 import visualization from app.services.earth_layer_cache import ( @@ -49,6 +51,19 @@ class FakeRedis: deleted += 1 if self.store.pop(key, None) is not None else 0 return deleted + def eval(self, script: str, numkeys: int, *args): + self._maybe_fail() + keys, values = args[:numkeys], args[numkeys:] + if self.store.get(keys[0]) != values[0]: + return 0 + if numkeys == 3: + self.setex(keys[1], values[1], values[3]) + self.setex(keys[2], values[2], values[3]) + return 1 + if "'expire'" in script: + return 1 + return self.delete(keys[0]) + def scan_iter(self, match: str): self._maybe_fail() prefix = match.rstrip("*") @@ -120,7 +135,9 @@ async def test_resolve_layer_payload_writes_fresh_and_stale(fake_cache_client): @pytest.mark.asyncio async def test_resolve_layer_payload_returns_stale_when_builder_fails(fake_cache_client): key = earth_layer_cache.key("bgp-incidents", status="active") - fake_cache_client.store[f"{key}:stale"] = json.dumps({"type": "FeatureCollection", "features": []}) + fake_cache_client.store[f"{key}:stale"] = json.dumps( + {"type": "FeatureCollection", "features": []} + ) async def builder(): raise RuntimeError("db exploded") @@ -165,6 +182,7 @@ async def test_resolve_layer_payload_bypasses_redis_failure(): previous = earth_layer_cache._client earth_layer_cache._client = FakeRedis(fail=True) try: + async def builder(): return {"type": "FeatureCollection", "features": [{"id": "safe"}]} @@ -192,9 +210,13 @@ async def test_visualization_endpoint_sets_cache_headers(fake_cache_client, monk monkeypatch.setattr(visualization, "_build_satellites_geojson", fake_build_satellites_geojson) first_response = Response() - first = await visualization.get_satellites_geojson(limit=25, db=object(), response=first_response) + first = await visualization.get_satellites_geojson( + limit=25, db=object(), response=first_response + ) second_response = Response() - second = await visualization.get_satellites_geojson(limit=25, db=object(), response=second_response) + second = await visualization.get_satellites_geojson( + limit=25, db=object(), response=second_response + ) assert first == second assert calls == 1 @@ -252,3 +274,284 @@ async def test_vessel_snapshot_uses_short_cache(fake_cache_client, monkeypatch): assert calls == 1 assert first_response.headers["X-Planet-Cache"] == "refresh" assert second_response.headers["X-Planet-Cache"] == "hit" + + +@pytest.mark.asyncio +async def test_concurrent_summary_requests_share_one_slow_build(monkeypatch): + started = asyncio.Event() + finish = asyncio.Event() + calls = 0 + + async def build_summary(db): + nonlocal calls + calls += 1 + started.set() + await finish.wait() + return {"stats": {"vessel_count": 42}} + + monkeypatch.setattr(visualization, "_build_visualization_geo_summary", build_summary) + app = FastAPI() + app.include_router(visualization.router, prefix="/api/v1/visualization") + app.dependency_overrides[visualization.get_db] = lambda: object() + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://test" + ) as client: + requests = [ + asyncio.create_task(client.get("/api/v1/visualization/geo/summary")) for _ in range(6) + ] + await asyncio.wait_for(started.wait(), 1) + # Keep the build open beyond the old 200 ms fallback to duplicate SQL. + await asyncio.sleep(0.25) + assert calls == 1 + finish.set() + results = await asyncio.gather(*requests) + assert all(response.status_code == 200 for response in results) + assert all(response.json() == {"stats": {"vessel_count": 42}} for response in results) + assert sorted(response.headers["X-Planet-Cache"] for response in results) == [ + "hit", + "hit", + "hit", + "hit", + "hit", + "refresh", + ] + assert not earth_layer_cache._inflight + + +@pytest.mark.asyncio +@pytest.mark.parametrize("error_type", [RuntimeError, TimeoutError]) +async def test_shared_builder_error_is_not_retried(error_type): + started = asyncio.Event() + finish = asyncio.Event() + calls = 0 + + async def builder(): + nonlocal calls + calls += 1 + started.set() + await finish.wait() + raise error_type("db failed") + + requests = [ + asyncio.create_task( + resolve_layer_payload( + key="shared-error", policy=EarthLayerCachePolicy(60, 120), builder=builder + ) + ) + for _ in range(4) + ] + await started.wait() + await asyncio.sleep(0) + finish.set() + results = await asyncio.gather(*requests, return_exceptions=True) + assert calls == 1 + assert all(isinstance(result, error_type) for result in results) + assert not earth_layer_cache._inflight + + +@pytest.mark.asyncio +async def test_concurrent_redis_failure_shares_bypass_result(fake_cache_client): + fake_cache_client.fail = True + started = asyncio.Event() + finish = asyncio.Event() + calls = 0 + + async def builder(): + nonlocal calls + calls += 1 + started.set() + await finish.wait() + return {"count": 42} + + requests = [ + asyncio.create_task( + resolve_layer_payload( + key="shared-bypass", policy=EarthLayerCachePolicy(60, 120), builder=builder + ) + ) + for _ in range(4) + ] + await started.wait() + await asyncio.sleep(0) + finish.set() + results = await asyncio.gather(*requests) + assert calls == 1 + assert all(result.state == "bypass" and result.payload == {"count": 42} for result in results) + + +@pytest.mark.asyncio +async def test_cancelled_waiter_does_not_cancel_owner(): + started = asyncio.Event() + finish = asyncio.Event() + policy = EarthLayerCachePolicy(60, 120) + + async def builder(): + started.set() + await finish.wait() + return {"count": 1} + + owner = asyncio.create_task( + resolve_layer_payload(key="cancel-waiter", policy=policy, builder=builder) + ) + await started.wait() + waiter = asyncio.create_task( + resolve_layer_payload(key="cancel-waiter", policy=policy, builder=builder) + ) + await asyncio.sleep(0) + waiter.cancel() + with pytest.raises(asyncio.CancelledError): + await waiter + finish.set() + assert (await owner).payload == {"count": 1} + assert not earth_layer_cache._inflight + + +@pytest.mark.asyncio +async def test_cancelled_owner_allows_waiter_to_use_its_own_builder(): + started = asyncio.Event() + policy = EarthLayerCachePolicy(60, 120) + + async def owner_builder(): + started.set() + await asyncio.Event().wait() + + async def waiter_builder(): + return {"count": 2} + + owner = asyncio.create_task( + resolve_layer_payload(key="cancel-owner", policy=policy, builder=owner_builder) + ) + await started.wait() + waiter = asyncio.create_task( + resolve_layer_payload(key="cancel-owner", policy=policy, builder=waiter_builder) + ) + await asyncio.sleep(0) + owner.cancel() + with pytest.raises(asyncio.CancelledError): + await owner + assert (await asyncio.wait_for(waiter, 1)).payload == {"count": 2} + assert not earth_layer_cache._inflight + + +@pytest.mark.asyncio +async def test_cross_process_lock_waits_for_payload_instead_of_building(fake_cache_client): + key = "remote-owner" + fake_cache_client.store[earth_layer_cache.lock_key(key)] = "another-owner" + policy = EarthLayerCachePolicy(60, 120, lock_wait_seconds=0.005) + calls = 0 + + async def builder(): + nonlocal calls + calls += 1 + return {"count": -1} + + waiter = asyncio.create_task(resolve_layer_payload(key=key, policy=policy, builder=builder)) + await asyncio.sleep(0.03) + assert calls == 0 + fake_cache_client.store[key] = json.dumps({"count": 3}) + assert (await asyncio.wait_for(waiter, 1)).payload == {"count": 3} + assert calls == 0 + + +@pytest.mark.asyncio +async def test_wait_timeout_does_not_bypass_other_owner(fake_cache_client): + key = "remote-timeout" + fake_cache_client.store[earth_layer_cache.lock_key(key)] = "another-owner" + calls = 0 + + async def builder(): + nonlocal calls + calls += 1 + return {} + + with pytest.raises(HTTPException) as error: + await resolve_layer_payload( + key=key, + policy=EarthLayerCachePolicy(60, 120, lock_wait_seconds=0.005, build_wait_seconds=0.02), + builder=builder, + ) + assert error.value.status_code == 503 + assert calls == 0 + assert not earth_layer_cache._inflight + + +@pytest.mark.asyncio +async def test_lost_owner_cannot_publish_or_release_new_lock(fake_cache_client): + key = "lock-replaced" + policy = EarthLayerCachePolicy(60, 120) + + async def builder(): + fake_cache_client.store[earth_layer_cache.lock_key(key)] = "new-owner" + fake_cache_client.store[key] = json.dumps({"count": 99}) + return {"count": 1} + + result = await resolve_layer_payload(key=key, policy=policy, builder=builder) + assert result.payload == {"count": 1} + assert result.state == "bypass" + assert fake_cache_client.store[earth_layer_cache.lock_key(key)] == "new-owner" + assert json.loads(fake_cache_client.store[key]) == {"count": 99} + + +@pytest.mark.asyncio +async def test_redis_publish_failure_returns_built_payload_without_retry(fake_cache_client): + calls = 0 + + async def builder(): + nonlocal calls + calls += 1 + fake_cache_client.fail = True + return {"count": 7} + + result = await resolve_layer_payload( + key="publish-error", policy=EarthLayerCachePolicy(60, 120), builder=builder + ) + assert result.state == "bypass" + assert result.payload == {"count": 7} + assert calls == 1 + + +@pytest.mark.asyncio +async def test_local_wait_timeout_leaves_owner_running(): + started = asyncio.Event() + finish = asyncio.Event() + policy = EarthLayerCachePolicy(60, 120, build_wait_seconds=0.02) + + async def builder(): + started.set() + await finish.wait() + return {"count": 1} + + owner = asyncio.create_task( + resolve_layer_payload(key="local-timeout", policy=policy, builder=builder) + ) + await started.wait() + with pytest.raises(HTTPException) as error: + await resolve_layer_payload(key="local-timeout", policy=policy, builder=builder) + assert error.value.status_code == 503 + assert not owner.done() + finish.set() + assert (await owner).payload == {"count": 1} + assert not earth_layer_cache._inflight + + +@pytest.mark.asyncio +async def test_different_keys_can_build_concurrently(): + started = set() + both_started = asyncio.Event() + + async def build(key): + started.add(key) + if len(started) == 2: + both_started.set() + await asyncio.wait_for(both_started.wait(), 1) + return {"key": key} + + results = await asyncio.gather( + *( + resolve_layer_payload( + key=key, policy=EarthLayerCachePolicy(60, 120), builder=lambda key=key: build(key) + ) + for key in ("one", "two") + ) + ) + assert {result.payload["key"] for result in results} == {"one", "two"} diff --git a/backend/tests/test_earth_news.py b/backend/tests/test_earth_news.py index 8bbfc868..69abd2e8 100644 --- a/backend/tests/test_earth_news.py +++ b/backend/tests/test_earth_news.py @@ -3,6 +3,7 @@ from types import SimpleNamespace import pytest +from app.api.v1.news import get_earth_feed from app.services.earth_news import ( NewsFeedEndpoint, NewsFeedSource, @@ -1201,7 +1202,6 @@ async def test_earth_news_payload_passes_region_and_category_filters_to_store(mo db=FakeDb(), ) - assert captured["freshness_region"] == "europe" assert captured["items_region"] == "europe" assert captured["items_categories"] == {"business", "ecommerce"} assert captured["items_source_ids"][0] is None @@ -1237,71 +1237,41 @@ async def test_news_source_test_treats_type_reference_as_non_fetching(): @pytest.mark.asyncio -async def test_earth_news_payload_initializes_empty_database_from_rss(monkeypatch): +async def test_earth_news_feed_get_does_not_fetch_write_or_queue_rss(monkeypatch): db = object() - source = NewsFeedSource( - id="test-feed", - name="Test Feed", - region="global", - homepage_url="https://example.com", - feed_url="https://example.com/rss.xml", + read_calls = 0 + async def fail_side_effect(*_args, **_kwargs): + raise AssertionError("RSS feed reads must not fetch, persist, or enqueue work") + + async def empty_news_items(*_args, **_kwargs): + nonlocal read_calls + read_calls += 1 + return [] + + monkeypatch.setattr("app.services.earth_news._fetch_rss_items_for_sources", fail_side_effect) + monkeypatch.setattr("app.services.earth_news._enqueue_unverified_locations", fail_side_effect) + monkeypatch.setattr("app.services.earth_news_store.upsert_earth_news_items", fail_side_effect) + monkeypatch.setattr( + "app.services.earth_news_store.list_earth_news_items", empty_news_items ) - item = ParsedNewsItem( - id="test-feed:init", - title="Initial RSS story", - summary="Initial summary", - url="https://example.com/init", - source="Test Feed", - feed_name="Test Feed", - feed_region="global", - homepage_url="https://example.com", - published_at=datetime(2026, 5, 15, 3, 0, tzinfo=UTC), + + payload = await get_earth_feed( + lat=None, + lon=None, + region=None, + categories=None, + sources=None, + limit=None, + locale=None, + db=db, ) - item.location_patch = { - "latitude": 20.0, - "longitude": 0.0, - "location_label": "全球", - "location_source": "region_anchor", - "verified": False, - "location_meta": {"target": None, "anchor": {"region": "global"}}, - } - upserted = [] - enqueued = [] - async def fake_get_earth_news_freshness(_db, *, active_region): - return 0, None - - async def fake_fetch_rss_items_for_sources(_sources, **_kwargs): - return [item], [], {"test-feed": {"source_id": "test-feed", "ok": True, "status": "ok", "count": 1}} - - async def fake_upsert_earth_news_items(_db, items): - upserted.extend(items) - return len(items) - - async def fake_list_earth_news_items(_db, *, active_region, limit, categories=None): - return [item] - - async def fake_enqueue_target_location_job(payload, **_kwargs): - enqueued.append(payload) - return True - - monkeypatch.setattr("app.services.earth_news.get_sources_for_region", lambda _region: [source]) - monkeypatch.setattr("app.services.earth_news_store.get_earth_news_freshness", fake_get_earth_news_freshness) - monkeypatch.setattr("app.services.earth_news._fetch_rss_items_for_sources", fake_fetch_rss_items_for_sources) - monkeypatch.setattr("app.services.earth_news_store.upsert_earth_news_items", fake_upsert_earth_news_items) - monkeypatch.setattr("app.services.earth_news_store.list_earth_news_items", fake_list_earth_news_items) - monkeypatch.setattr("app.services.earth_news_queue.enqueue_target_location_job", fake_enqueue_target_location_job) - - payload = await get_earth_news_payload(db=db) - - assert upserted[0].id == "test-feed:init" - assert payload["items"][0]["id"] == "test-feed:init" - assert payload["items"][0]["verified"] is False - assert enqueued[0]["id"] == "test-feed:init" + assert payload["items"] == [] + assert read_calls == 1 @pytest.mark.asyncio -async def test_earth_news_payload_supplements_stale_database_items(monkeypatch): +async def test_earth_news_payload_does_not_supplement_stale_database_items(monkeypatch): db = object() old_item = ParsedNewsItem( id="db:old", @@ -1314,41 +1284,17 @@ async def test_earth_news_payload_supplements_stale_database_items(monkeypatch): homepage_url="https://example.com", published_at=datetime(2026, 5, 14, 3, 0, tzinfo=UTC), ) - old_item.location_patch = { - "latitude": 20.0, - "longitude": 0.0, - "location_label": "全球", - "location_source": "region_anchor", - "verified": False, - "location_meta": {"target": None, "anchor": {"region": "global"}}, - } - fetched = [] + async def fail_fetch(*_args, **_kwargs): + raise AssertionError("stale RSS supplementation belongs to the background worker") - async def fake_get_earth_news_freshness(_db, *, active_region): - return 12, datetime(2026, 5, 14, 3, 0, tzinfo=UTC) - - async def fake_fetch_rss_items_for_sources(_sources, **_kwargs): - fetched.append(True) - return [old_item], [], {"stored": {"source_id": "stored", "ok": True, "status": "ok", "count": 1}} - - async def fake_upsert_earth_news_items(_db, items): - return len(items) - - async def fake_list_earth_news_items(_db, *, active_region, limit, categories=None): + async def fake_list_earth_news_items(_db, *, active_region, limit, categories=None, source_ids=None): return [old_item] - async def fake_enqueue_target_location_job(_payload, **_kwargs): - return True - - monkeypatch.setattr("app.services.earth_news_store.get_earth_news_freshness", fake_get_earth_news_freshness) - monkeypatch.setattr("app.services.earth_news._fetch_rss_items_for_sources", fake_fetch_rss_items_for_sources) - monkeypatch.setattr("app.services.earth_news_store.upsert_earth_news_items", fake_upsert_earth_news_items) + monkeypatch.setattr("app.services.earth_news._fetch_rss_items_for_sources", fail_fetch) monkeypatch.setattr("app.services.earth_news_store.list_earth_news_items", fake_list_earth_news_items) - monkeypatch.setattr("app.services.earth_news_queue.enqueue_target_location_job", fake_enqueue_target_location_job) - payload = await get_earth_news_payload(db=db) + payload = await get_earth_news_payload(db=db, source_ids={"stored"}) - assert fetched == [True] assert payload["items"][0]["id"] == "db:old" diff --git a/backend/tests/test_earth_news_refresh.py b/backend/tests/test_earth_news_refresh.py new file mode 100644 index 00000000..47d3429a --- /dev/null +++ b/backend/tests/test_earth_news_refresh.py @@ -0,0 +1,525 @@ +from contextlib import asynccontextmanager +from datetime import UTC, datetime +import json + +import pytest + +from app.services.earth_news import NewsFeedEndpoint, NewsFeedSource +from app.services import earth_news_refresh +from app.services.scheduler import ( + EARTH_NEWS_REFRESH_JOB_ID, + _earth_news_region_refresh_job_id, + schedule_earth_news_region_refresh, + start_scheduler, + sync_scheduler_with_datasources, +) + + +class FakeRedis: + def __init__(self) -> None: + self.values: dict[str, str] = {} + + def set(self, key: str, value: str, *, nx: bool = False, ex: int | None = None) -> bool: + del ex + if nx and key in self.values: + return False + self.values[key] = value + return True + + def exists(self, key: str) -> bool: + return key in self.values + + def eval(self, script: str, _key_count: int, key: str, token: str, *_args: object) -> int: + if self.values.get(key) != token: + return 0 + if "redis.call('del'" in script: + del self.values[key] + return 1 + + +class FakeStatusRedis: + def __init__(self) -> None: + self.values: dict[str, str] = {} + self.expirations: dict[str, int] = {} + + def get(self, key: str): + return self.values.get(key) + + def eval(self, script: str, key_count: int, *args): + keys = args[:key_count] + values = args[key_count:] + if "local active_id" in script: + active_key, status_key = keys + refresh_id, encoded, active_ttl, status_ttl, status_prefix = values + active_id = self.values.get(active_key) + if active_id: + active_status = self.values.get(f"{status_prefix}{active_id}") + if active_status: + status = json.loads(active_status)["status"] + if status in {"pending", "running"}: + return [active_id, active_status, 0] + self.values.pop(active_key, None) + self.values[active_key] = refresh_id + self.values[status_key] = encoded + self.expirations[active_key] = int(active_ttl) + self.expirations[status_key] = int(status_ttl) + return [refresh_id, encoded, 1] + + active_key, status_key = keys + encoded, refresh_id, status_ttl, status, active_ttl = values + if self.values.get(active_key) != refresh_id: + return 0 + self.values[status_key] = encoded + self.expirations[status_key] = int(status_ttl) + if status in {"succeeded", "failed"}: + self.values.pop(active_key, None) + else: + self.expirations[active_key] = int(active_ttl) + return 1 + + +class FakeSession: + def __init__(self) -> None: + self.commits = 0 + self.rollbacks = 0 + + async def commit(self) -> None: + self.commits += 1 + + async def rollback(self) -> None: + self.rollbacks += 1 + + +@pytest.mark.asyncio +async def test_region_refresh_fetches_only_missing_feed_coverage(monkeypatch): + redis_client = FakeRedis() + db = FakeSession() + feeds = ( + NewsFeedEndpoint("feed-a", "Feed A", "https://example.com/a.xml", region="global"), + NewsFeedEndpoint("feed-b", "Feed B", "https://example.com/b.xml", region="global"), + ) + source = NewsFeedSource( + id="source-a", + name="Source A", + region="global", + feed_url=feeds[0].url, + homepage_url="https://example.com", + feeds=feeds, + ) + fetched_source_feeds: list[list[str]] = [] + + @asynccontextmanager + async def fake_session_factory(): + yield db + + async def fake_get_sources_payload(_db): + return {"sources": []} + + async def fake_get_sources_for_region(_db, _region, *, config_payload=None): + assert config_payload == {"sources": []} + return [source] + + async def fake_freshness(_db, *, active_region): + assert active_region == "global" + return 12, datetime.now(UTC) + + async def fake_coverage(_db, *, active_region, recent_after): + assert active_region == "global" + assert recent_after is not None + return {("source-a", "feed-a")} + + async def fake_fetch(sources, **_kwargs): + fetched_source_feeds.extend([[feed.id for feed in item.feeds] for item in sources]) + return [], [], {"source-a": {"source_id": "source-a", "ok": True, "feed_results": []}} + + async def fake_record_health(_db, _health): + return None + + async def fake_enqueue(_items): + return None + + async def fake_upsert(_db, items): + assert items == [] + return 0 + + monkeypatch.setattr(earth_news_refresh, "async_session_factory", fake_session_factory) + monkeypatch.setattr(earth_news_refresh._RedisClient, "get_client", lambda: redis_client) + monkeypatch.setattr( + "app.services.earth_news.get_earth_news_sources_payload", fake_get_sources_payload + ) + monkeypatch.setattr( + "app.services.earth_news.get_configured_sources_for_region", fake_get_sources_for_region + ) + monkeypatch.setattr(earth_news_refresh, "get_earth_news_freshness", fake_freshness) + monkeypatch.setattr(earth_news_refresh, "get_earth_news_feed_coverage", fake_coverage) + monkeypatch.setattr("app.services.earth_news._fetch_rss_items_for_sources", fake_fetch) + monkeypatch.setattr( + "app.services.earth_news.record_earth_news_sources_health", fake_record_health + ) + monkeypatch.setattr("app.services.earth_news._enqueue_unverified_locations", fake_enqueue) + monkeypatch.setattr(earth_news_refresh, "upsert_earth_news_items", fake_upsert) + + result = await earth_news_refresh.refresh_earth_news_region("global") + + assert result["state"] == "completed" + assert result["successful_sources"] == 1 + assert fetched_source_feeds == [["feed-b"]] + assert db.commits == 1 + assert earth_news_refresh._lock_key("global") not in redis_client.values + + +@pytest.mark.asyncio +async def test_region_refresh_reports_failure_when_all_sources_time_out(monkeypatch): + redis_client = FakeRedis() + db = FakeSession() + feed = NewsFeedEndpoint("feed-a", "Feed A", "https://example.com/a.xml", region="global") + source = NewsFeedSource( + id="source-a", + name="Source A", + region="global", + feed_url=feed.url, + homepage_url="https://example.com", + feeds=(feed,), + ) + + @asynccontextmanager + async def fake_session_factory(): + yield db + + async def fake_get_sources_payload(_db): + return {"sources": []} + + async def fake_get_sources_for_region(_db, _region, *, config_payload=None): + return [source] + + async def fake_freshness(_db, *, active_region): + return 12, datetime.now(UTC) + + async def fake_coverage(_db, *, active_region, recent_after): + return set() + + async def fake_fetch(*_args, **_kwargs): + return ( + [], + ["private upstream details"], + { + "source-a": { + "source_id": "source-a", + "ok": False, + "status": "timeout", + "feed_results": [{"feed_id": "feed-a", "ok": False, "status": "timeout"}], + } + }, + ) + + async def fake_noop(*_args, **_kwargs): + return None + + async def fake_upsert(_db, _items): + return 0 + + monkeypatch.setattr(earth_news_refresh, "async_session_factory", fake_session_factory) + monkeypatch.setattr(earth_news_refresh._RedisClient, "get_client", lambda: redis_client) + monkeypatch.setattr( + "app.services.earth_news.get_earth_news_sources_payload", fake_get_sources_payload + ) + monkeypatch.setattr( + "app.services.earth_news.get_configured_sources_for_region", fake_get_sources_for_region + ) + monkeypatch.setattr(earth_news_refresh, "get_earth_news_freshness", fake_freshness) + monkeypatch.setattr(earth_news_refresh, "get_earth_news_feed_coverage", fake_coverage) + monkeypatch.setattr("app.services.earth_news._fetch_rss_items_for_sources", fake_fetch) + monkeypatch.setattr("app.services.earth_news.record_earth_news_sources_health", fake_noop) + monkeypatch.setattr("app.services.earth_news._enqueue_unverified_locations", fake_noop) + monkeypatch.setattr(earth_news_refresh, "upsert_earth_news_items", fake_upsert) + + result = await earth_news_refresh.refresh_earth_news_region("global", force=True) + + assert result["state"] == "failed" + assert result["error_code"] == "timeout" + assert db.commits == 1 + + +@pytest.mark.asyncio +async def test_database_commit_failure_sets_refresh_failed_status(monkeypatch): + class CommitFailureSession(FakeSession): + async def commit(self) -> None: + raise RuntimeError("database commit failed with sensitive context") + + redis_client = FakeRedis() + db = CommitFailureSession() + feed = NewsFeedEndpoint("feed-a", "Feed A", "https://example.com/a.xml", region="europe") + source = NewsFeedSource( + id="source-a", + name="Source A", + region="europe", + feed_url=feed.url, + homepage_url="https://example.com", + feeds=(feed,), + ) + scheduler_module = __import__("app.services.scheduler", fromlist=["scheduler"]) + statuses = [] + + @asynccontextmanager + async def fake_session_factory(): + yield db + + async def fake_get_sources_payload(_db): + return {"sources": []} + + async def fake_get_sources_for_region(_db, _region, *, config_payload=None): + return [source] + + async def fake_freshness(_db, *, active_region): + return 12, datetime.now(UTC) + + async def fake_coverage(_db, *, active_region, recent_after): + return set() + + async def fake_fetch(*_args, **_kwargs): + return [], [], {"source-a": {"source_id": "source-a", "ok": True, "feed_results": []}} + + async def fake_noop(*_args, **_kwargs): + return None + + async def fake_upsert(_db, _items): + return 1 + + monkeypatch.setattr(earth_news_refresh, "async_session_factory", fake_session_factory) + monkeypatch.setattr(earth_news_refresh._RedisClient, "get_client", lambda: redis_client) + monkeypatch.setattr( + "app.services.earth_news.get_earth_news_sources_payload", fake_get_sources_payload + ) + monkeypatch.setattr( + "app.services.earth_news.get_configured_sources_for_region", fake_get_sources_for_region + ) + monkeypatch.setattr(earth_news_refresh, "get_earth_news_freshness", fake_freshness) + monkeypatch.setattr(earth_news_refresh, "get_earth_news_feed_coverage", fake_coverage) + monkeypatch.setattr("app.services.earth_news._fetch_rss_items_for_sources", fake_fetch) + monkeypatch.setattr("app.services.earth_news.record_earth_news_sources_health", fake_noop) + monkeypatch.setattr("app.services.earth_news._enqueue_unverified_locations", fake_noop) + monkeypatch.setattr(earth_news_refresh, "upsert_earth_news_items", fake_upsert) + monkeypatch.setattr(scheduler_module, "touch_earth_news_refresh_status", lambda *_args: True) + monkeypatch.setattr( + scheduler_module, + "set_earth_news_refresh_status", + lambda refresh_id, region, status, *, error=None: statuses.append( + {"refresh_id": refresh_id, "region": region, "status": status, "error": error} + ), + ) + scheduler_module._pending_earth_news_refreshes["europe"] = { + "force": True, + "refresh_id": "refresh-commit-failure", + } + + await scheduler_module._run_earth_news_region_refresh("europe") + + assert [entry["status"] for entry in statuses] == ["running", "failed"] + assert statuses[-1]["error"]["code"] == "refresh_failed" + assert "sensitive context" not in repr(statuses) + assert not redis_client.values + + +@pytest.mark.asyncio +async def test_region_refresh_skips_when_cross_process_lock_is_held(monkeypatch): + redis_client = FakeRedis() + redis_client.values[earth_news_refresh._lock_key("global")] = "other-owner" + + def fail_session_factory(): + raise AssertionError("a locked refresh must not open a database session") + + monkeypatch.setattr(earth_news_refresh, "async_session_factory", fail_session_factory) + monkeypatch.setattr(earth_news_refresh._RedisClient, "get_client", lambda: redis_client) + + result = await earth_news_refresh.refresh_earth_news_region("global") + + assert result["state"] == "busy" + + +def test_failed_feed_enters_cooldown_without_blocking_other_sources(): + redis_client = FakeRedis() + source = NewsFeedSource( + id="source-a", + name="Source A", + region="global", + feed_url="https://example.com/a.xml", + homepage_url="https://example.com", + feeds=(NewsFeedEndpoint("feed-a", "Feed A", "https://example.com/a.xml"),), + ) + health = { + "source-a": { + "ok": False, + "feed_results": [{"feed_id": "feed-a", "ok": False}], + } + } + + earth_news_refresh._record_failed_feed_cooldowns( + redis_client, + active_region="global", + health_by_source=health, + sources=[source], + ) + selected, cooling = earth_news_refresh._select_feeds( + [source], + active_region="global", + required_keys={("source-a", "feed-a")}, + redis_client=redis_client, + ) + + assert selected == [] + assert cooling == {("source-a", "feed-a")} + + +@pytest.mark.asyncio +async def test_region_refresh_skips_when_redis_coordination_is_unavailable(monkeypatch): + def fail_redis_client(): + raise RuntimeError("redis unavailable") + + def fail_session_factory(): + raise AssertionError("uncoordinated processes must not start duplicate RSS fetches") + + monkeypatch.setattr(earth_news_refresh._RedisClient, "get_client", fail_redis_client) + monkeypatch.setattr(earth_news_refresh, "async_session_factory", fail_session_factory) + + result = await earth_news_refresh.refresh_earth_news_region("global") + + assert result["state"] == "coordination_unavailable" + + +def test_refresh_status_deduplicates_active_region_and_bounds_completed_results(monkeypatch): + redis_client = FakeStatusRedis() + monkeypatch.setattr(earth_news_refresh._RedisClient, "get_client", lambda: redis_client) + + first, created = earth_news_refresh.create_earth_news_refresh_status("global") + duplicate, duplicate_created = earth_news_refresh.create_earth_news_refresh_status("global") + assert created is True + assert duplicate_created is False + assert duplicate == first + + earth_news_refresh.set_earth_news_refresh_status(first["refresh_id"], "global", "running") + running, running_created = earth_news_refresh.create_earth_news_refresh_status("global") + assert running_created is False + assert running["status"] == "running" + + completed = earth_news_refresh.set_earth_news_refresh_status( + first["refresh_id"], "global", "succeeded" + ) + assert completed["status"] == "succeeded" + assert earth_news_refresh.get_earth_news_refresh_status(first["refresh_id"]) == completed + + second, second_created = earth_news_refresh.create_earth_news_refresh_status("global") + assert second_created is True + assert second["refresh_id"] != first["refresh_id"] + assert earth_news_refresh.get_earth_news_refresh_status(first["refresh_id"]) == completed + assert redis_client.expirations[earth_news_refresh._refresh_active_key("global")] == 120 + assert ( + redis_client.expirations[earth_news_refresh._refresh_status_key(second["refresh_id"])] + == 600 + ) + status_keys = [ + key + for key in redis_client.values + if key.startswith(earth_news_refresh.REFRESH_STATUS_PREFIX) + ] + assert len(status_keys) == 2 + + pending, pending_created = earth_news_refresh.create_earth_news_refresh_status("europe") + assert pending_created is True + redis_client.values.pop(earth_news_refresh._refresh_active_key("europe"), None) + expired = earth_news_refresh.get_earth_news_refresh_status(pending["refresh_id"]) + assert expired["status"] == "failed" + assert expired["error"]["code"] == "expired" + + +@pytest.mark.asyncio +async def test_earth_news_refresh_scheduler_job_survives_datasource_sync(monkeypatch): + class FakeJob: + def __init__(self, job_id: str) -> None: + self.id = job_id + + class FakeScheduler: + def __init__(self) -> None: + self.running = False + self.jobs = { + "obsolete": FakeJob("obsolete"), + _earth_news_region_refresh_job_id("global"): FakeJob( + _earth_news_region_refresh_job_id("global") + ), + } + self.added: dict[str, object] = {} + + def add_job(self, _func, **kwargs): + self.added.update(kwargs) + self.jobs[kwargs["id"]] = FakeJob(kwargs["id"]) + + def start(self) -> None: + self.running = True + + def get_jobs(self): + return list(self.jobs.values()) + + def remove_job(self, job_id: str) -> None: + self.jobs.pop(job_id, None) + + class FakeResult: + def scalars(self): + return self + + def all(self): + return [] + + class FakeDb: + async def execute(self, _query): + return FakeResult() + + fake_scheduler = FakeScheduler() + + @asynccontextmanager + async def fake_session_factory(): + yield FakeDb() + + monkeypatch.setattr("app.services.scheduler.scheduler", fake_scheduler) + monkeypatch.setattr("app.services.scheduler.async_session_factory", fake_session_factory) + + start_scheduler() + await sync_scheduler_with_datasources() + + assert fake_scheduler.added["id"] == EARTH_NEWS_REFRESH_JOB_ID + assert fake_scheduler.added["next_run_time"] <= datetime.now(UTC) + assert EARTH_NEWS_REFRESH_JOB_ID in fake_scheduler.jobs + assert _earth_news_region_refresh_job_id("global") in fake_scheduler.jobs + assert "obsolete" not in fake_scheduler.jobs + + +@pytest.mark.asyncio +async def test_region_refresh_requests_are_merged_and_force_is_preserved(monkeypatch): + class FakeScheduler: + running = True + + def __init__(self) -> None: + self.jobs: dict[str, tuple[object, dict[str, object]]] = {} + + def add_job(self, func, **kwargs): + self.jobs[kwargs["id"]] = (func, kwargs) + + scheduler_module = __import__("app.services.scheduler", fromlist=["scheduler"]) + fake_scheduler = FakeScheduler() + monkeypatch.setattr(scheduler_module, "scheduler", fake_scheduler) + captured: list[tuple[str, bool]] = [] + + async def fake_refresh(region: str, *, force: bool = False): + captured.append((region, force)) + return {"locked": False, "fetched": 0, "upserted": 0} + + monkeypatch.setattr(scheduler_module, "refresh_earth_news_region", fake_refresh) + + assert schedule_earth_news_region_refresh("global") is True + assert schedule_earth_news_region_refresh("global", force=True) is False + assert len(fake_scheduler.jobs) == 1 + + job_id = _earth_news_region_refresh_job_id("global") + func, kwargs = fake_scheduler.jobs.pop(job_id) + await func(**kwargs["kwargs"]) + + assert captured == [("global", True)] + assert job_id not in fake_scheduler.jobs diff --git a/backend/tests/test_earth_outbox_maintenance.py b/backend/tests/test_earth_outbox_maintenance.py new file mode 100644 index 00000000..0fb037d2 --- /dev/null +++ b/backend/tests/test_earth_outbox_maintenance.py @@ -0,0 +1,140 @@ +from __future__ import annotations + +from datetime import UTC, datetime + +import pytest + +from app.services import earth_db_change_listener as listener_module +from app.services.earth_db_change_listener import EarthDbChangeDispatcher, EarthDbChangeListener +from app.services.earth_outbox_maintenance import ( + DELETE_BATCH_SQL, + compact_consumed_events, + ensure_retention_index, + purge_consumed_events, +) + + +class FakeConnection: + def __init__(self, *, index_state: str = "ready", batch_counts: list[int] | None = None): + self.index_state = index_state + self.batch_counts = list(batch_counts or []) + self.calls: list[tuple[str, tuple[object, ...]]] = [] + self.retained = {"total": 13, "pending": 3} + self.restored = dict(self.retained) + self.rolled_back = False + + async def fetchrow(self, query: str, *args: object): + self.calls.append((query, args)) + if "pg_index" in query: + if self.index_state == "missing": + return None + return {"indisvalid": self.index_state == "ready", "indisready": True} + if "FROM earth_outbox_retained" in query: + return self.retained + return self.restored + + async def fetchval(self, query: str, *args: object): + self.calls.append((query, args)) + if query == DELETE_BATCH_SQL: + return self.batch_counts.pop(0) + return True + + async def execute(self, query: str, *args: object): + self.calls.append((query, args)) + if "CREATE INDEX CONCURRENTLY" in query: + self.index_state = "ready" + return "OK" + + def transaction(self): + connection = self + + class Transaction: + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, _exc, _traceback): + connection.rolled_back = exc_type is not None + + return Transaction() + + +@pytest.mark.asyncio +async def test_retention_skips_without_index(): + conn = FakeConnection(index_state="missing") + assert await purge_consumed_events(conn, retention_days=1) == 0 + assert not any(query == DELETE_BATCH_SQL for query, _ in conn.calls) + + +@pytest.mark.asyncio +async def test_retention_batches_only_consumed_old_rows(): + conn = FakeConnection(batch_counts=[1000, 19]) + deleted = await purge_consumed_events( + conn, retention_days=1, batch_size=1000, max_batches=10, pause_seconds=0 + ) + assert deleted == 1019 + calls = [args for query, args in conn.calls if query == DELETE_BATCH_SQL] + assert len(calls) == 2 + assert all(isinstance(args[0], datetime) and args[0].tzinfo is UTC for args in calls) + assert "consumed_at IS NOT NULL AND consumed_at < $1" in DELETE_BATCH_SQL + assert "FOR UPDATE SKIP LOCKED" in DELETE_BATCH_SQL + + +@pytest.mark.asyncio +async def test_index_creation_is_concurrent_and_repairs_invalid_index(): + conn = FakeConnection(index_state="invalid") + await ensure_retention_index(conn) + statements = [query for query, _ in conn.calls] + assert any("DROP INDEX CONCURRENTLY" in query for query in statements) + assert any("CREATE INDEX CONCURRENTLY" in query for query in statements) + + +@pytest.mark.asyncio +async def test_compact_retains_pending_and_recent_consumed_in_one_transaction(): + conn = FakeConnection() + assert await compact_consumed_events(conn, retention_days=1) == (13, 3) + statements = [query for query, _ in conn.calls] + assert next(i for i, query in enumerate(statements) if query.startswith("LOCK TABLE")) < next( + i for i, query in enumerate(statements) if query.startswith("TRUNCATE TABLE") + ) + assert any("consumed_at IS NULL OR consumed_at >= $1" in query for query in statements) + assert "TRUNCATE TABLE earth_data_change_events CONTINUE IDENTITY RESTRICT" in statements + assert not conn.rolled_back + + +@pytest.mark.asyncio +async def test_compact_verification_failure_rolls_back(): + conn = FakeConnection() + conn.restored = {"total": 12, "pending": 2} + with pytest.raises(RuntimeError, match="verification failed"): + await compact_consumed_events(conn, retention_days=1) + assert conn.rolled_back + + +@pytest.mark.asyncio +async def test_listener_runs_retention_at_most_once_per_interval(monkeypatch): + calls: list[str] = [] + + async def acquire(_conn): + calls.append("acquire") + return True + + async def purge(_conn, *, retention_days): + assert retention_days == 1 + calls.append("purge") + + async def release(_conn): + calls.append("release") + + monkeypatch.setattr(listener_module, "monotonic", lambda: 100.0) + monkeypatch.setattr(listener_module, "try_maintenance_lock", acquire) + monkeypatch.setattr(listener_module, "purge_consumed_events", purge) + monkeypatch.setattr(listener_module, "release_maintenance_lock", release) + monkeypatch.setattr(listener_module, "configured_retention_days", lambda: 1) + dispatcher = EarthDbChangeDispatcher(broadcast_earth_update=lambda _: None) + listener = EarthDbChangeListener(dsn="postgresql://example/db", dispatcher=dispatcher) + listener._connection = FakeConnection() + + await listener._maybe_purge_outbox() + await listener._maybe_purge_outbox() + + assert calls == ["acquire", "purge", "release"] diff --git a/backend/tests/test_logging.py b/backend/tests/test_logging.py index 9573f4e8..be0bcf1b 100644 --- a/backend/tests/test_logging.py +++ b/backend/tests/test_logging.py @@ -10,7 +10,7 @@ from app.core.logging import PlanetContextFilter, PlanetFormatter, get_logger from app.core.request_context import set_request_id from app.services import business_logs from app.services import persistent_logs -from app.models.system_log import ObservabilityEvent, ObservabilityEventGroup +from app.models.system_log import ObservabilityEvent, ObservabilityEventGroup, SystemLog def _capture_output(callback): @@ -100,6 +100,23 @@ def test_business_context_redacts_nested_sensitive_values(): assert context["nested"]["safe"] == "visible" +@pytest.mark.asyncio +async def test_business_log_preserves_events_in_isolated_store(persisted_test_logs): + await business_logs.emit_business_log( + get_logger("tests.persistence"), + event="test.business.completed", + message="Business action completed", + category="test", + context={"api_key": "test-secret", "record_count": 2}, + ) + + logs = [entry for entry in persisted_test_logs if isinstance(entry, SystemLog)] + assert len(logs) == 1 + assert logs[0].event == "test.business.completed" + assert logs[0].context == {"api_key": "[REDACTED]", "record_count": 2} + assert any(isinstance(entry, ObservabilityEventGroup) for entry in persisted_test_logs) + + def test_observability_fingerprint_normalizes_hls_fragments(): first = persistent_logs.build_observability_fingerprint( source="earth-client", diff --git a/backend/tests/test_news_refresh_api.py b/backend/tests/test_news_refresh_api.py new file mode 100644 index 00000000..a034f6b8 --- /dev/null +++ b/backend/tests/test_news_refresh_api.py @@ -0,0 +1,142 @@ +from types import SimpleNamespace +from uuid import UUID +import importlib + +import pytest +from fastapi import HTTPException + +from app.api.v1 import earth, news + + +@pytest.mark.asyncio +async def test_post_news_refresh_only_schedules_background_region_check(monkeypatch): + scheduled = [] + + def request(region: str): + scheduled.append(region) + return {"refresh_id": "refresh-europe", "region": region, "status": "pending"} + + async def fail_network_refresh(*_args, **_kwargs): + raise AssertionError("the POST handler must not perform RSS requests") + + monkeypatch.setattr("app.services.scheduler.request_earth_news_region_refresh", request) + monkeypatch.setattr("app.services.scheduler.refresh_earth_news_region", fail_network_refresh) + + response = await news.request_earth_news_refresh( + news.EarthNewsRefreshRequest(region="Europe", lat=48.8, lon=2.3) + ) + + assert response == {"refresh_id": "refresh-europe", "region": "europe", "status": "pending"} + assert scheduled == ["europe"] + refresh_route = next(route for route in news.router.routes if route.path == "/refresh") + assert refresh_route.status_code == 202 + + +@pytest.mark.asyncio +async def test_post_news_refresh_infers_region_and_rejects_unknown_region(monkeypatch): + scheduled = [] + monkeypatch.setattr( + "app.services.scheduler.request_earth_news_region_refresh", + lambda region: scheduled.append(region) + or {"refresh_id": "refresh-americas", "region": region, "status": "pending"}, + ) + + response = await news.request_earth_news_refresh( + news.EarthNewsRefreshRequest(lat=40.7, lon=-74.0) + ) + + assert response["region"] == "americas" + assert response["status"] == "pending" + assert scheduled == ["americas"] + with pytest.raises(HTTPException) as error: + await news.request_earth_news_refresh(news.EarthNewsRefreshRequest(region="unknown")) + assert error.value.status_code == 422 + + +@pytest.mark.asyncio +async def test_get_news_refresh_returns_status_and_expired_shape(monkeypatch): + current = {"refresh_id": "abc", "region": "global", "status": "running"} + monkeypatch.setattr( + "app.services.earth_news_refresh.get_earth_news_refresh_status", + lambda _refresh_id: current, + ) + + response = await news.get_earth_news_refresh(UUID("00000000-0000-0000-0000-000000000abc")) + + assert response is current + assert response["status"] == "running" + monkeypatch.setattr( + "app.services.earth_news_refresh.get_earth_news_refresh_status", lambda _id: None + ) + expired = await news.get_earth_news_refresh(UUID("00000000-0000-0000-0000-000000000abc")) + assert expired == { + "refresh_id": UUID("00000000-0000-0000-0000-000000000abc").hex, + "region": None, + "status": "failed", + "error": { + "code": "expired", + "message": "Refresh status expired. Submit a new refresh.", + }, + } + + +@pytest.mark.asyncio +async def test_database_failure_sets_terminal_failed_status_without_leaking_error(monkeypatch): + scheduler = importlib.import_module("app.services.scheduler") + statuses = [] + + async def fail_refresh(_region, *, force=False): + raise RuntimeError("postgres://private-token@host/database: commit failed") + + monkeypatch.setattr(scheduler, "refresh_earth_news_region", fail_refresh) + monkeypatch.setattr(scheduler, "touch_earth_news_refresh_status", lambda *_args: True) + monkeypatch.setattr( + scheduler, + "set_earth_news_refresh_status", + lambda refresh_id, region, state, *, error=None: statuses.append( + {"refresh_id": refresh_id, "region": region, "status": state, "error": error} + ), + ) + scheduler._pending_earth_news_refreshes["europe"] = { + "force": True, + "refresh_id": "refresh-db-failure", + } + + await scheduler._run_earth_news_region_refresh("europe") + + assert [item["status"] for item in statuses] == ["running", "failed"] + assert statuses[-1]["error"] == { + "code": "refresh_failed", + "message": "Could not refresh news. Please try again.", + } + assert "private-token" not in repr(statuses) + + +@pytest.mark.asyncio +async def test_news_source_save_and_reset_schedule_immediate_refresh(monkeypatch): + scheduled = [] + monkeypatch.setattr( + earth, + "save_earth_news_sources_payload", + lambda _db, _payload: _async_result({"status": "updated"}), + ) + monkeypatch.setattr( + earth, + "reset_earth_news_sources_payload", + lambda _db: _async_result({"status": "reset"}), + ) + monkeypatch.setattr( + "app.services.scheduler.schedule_earth_news_refresh_for_all_regions", + lambda *, force=False: scheduled.append(force), + ) + + await earth.update_earth_news_sources( + SimpleNamespace(model_dump=lambda: {}), _current_user=None, db=object() + ) + await earth.reset_earth_news_sources(_current_user=None, db=object()) + + assert scheduled == [True, True] + + +async def _async_result(value): + return value diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 746963c4..b08c2116 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,6 +8,22 @@ This project follows the repository versioning rule: - `improvement` -> `+0.0.1`(bugfix + 小功能混合) - `bugfix` -> `+0.0.1` +## [0.76.19] — 2026-11-09 + +Released: 2026-11-09 + +### Highlights +- 改善 Earth 桌面与移动端卡片、新闻刷新和数据更新链路,降低重复抓取、缓存重建与历史事件维护的开销。 + +### Added / Fixed / Improved +- 统一区域卡片的展开与胶囊展示、悬停和拖拽跟随,分别应用算力/新闻卡片展开上限;提供细线/粗线引导线及移动端交互改进,修复语言切换后状态提示标题残留。 +- 新闻 GET 只读取已保存内容,RSS 补抓改为独立调度;手动刷新提供可追踪状态、超时和重试,完成展示后才提示成功。 +- 图层缓存按 key 合并并发构建,续租与发布校验锁持有者;纯新闻变更不再触发 summary 缓存重建。 +- BGP 前缀归属使用容错转换和可独立部署的 GiST 索引;Outbox 单次写入事件,跳过纯时间戳变更,并提供有界保留与维护脚本。 +- 卫星粒子以球体遮挡判断替代点精灵深度裁切;同步中英文文档,补充回归并隔离前端验证构建产物。 + +--- + ## [0.76.18] — 2026-10-02 Released: 2026-10-02 diff --git a/docs/HARNESS.md b/docs/HARNESS.md index 347f24f5..a03d43d8 100644 --- a/docs/HARNESS.md +++ b/docs/HARNESS.md @@ -94,8 +94,8 @@ elevated restart; report that separately when it has not been exercised. | Doctor | `scripts/harness/doctor.sh` | Checks required files, required tools, optional delivery tools, and forbidden frontend lockfiles. | | Security | `scripts/harness/security-check.sh` | Checks that environment/private-key files are not tracked and scans for high-confidence committed secret tokens. | | Backend Rules | `scripts/harness/backend-rules-check.sh` | Checks backend app Python for direct `print()`, `breakpoint()`, and `pdb.set_trace()` debug calls so service code uses structured logging. | -| Frontend Rules | `scripts/harness/frontend-rules-check.sh` | Checks Bun-only scripts, admin route manifest coherence, literal internal route links, admin search route targets, frontend debug output, native button safety, icon-button accessibility, no nested Cards, no AntD/Space layout primitives, ConnectionTestInput usage, admin/docs shell height-chain sizing, same-category style owner warnings, viewport-scaled font sizes, zero letter spacing, and high-signal UI rule warnings. | -| Docs Consistency | `scripts/harness/docs-consistency-check.sh` | Checks frontend Docs metadata against backend Gatekeeper metadata, public Docs registration, full technical-doc bilingual file pairs, public doc links, readable link titles, language-scoped technical links, README/project-context admin stack drift, supported credential collector contracts, manual console route coverage against the actual admin manifest, documented UI route drift, documented `?section=` deep-link validity against the actual admin section config in technical docs and active plan docs, and the harness rules-coverage notes. | +| Frontend Rules | `scripts/harness/frontend-rules-check.sh` | Checks Bun-only scripts, admin route manifest coherence, literal internal route links, admin search route targets, frontend debug output, native button safety, icon-button accessibility, no nested Cards, no AntD/Space layout primitives, ConnectionTestInput usage, admin/docs shell height-chain sizing, viewport-scaled font sizes, zero letter spacing, and high-signal UI rule warnings. | +| Docs Consistency | `scripts/harness/docs-consistency-check.sh` | Checks frontend Docs metadata against backend Gatekeeper metadata, public Docs registration, full technical-doc bilingual file pairs, public doc links, readable link titles, language-scoped technical links, README/project-context admin stack drift, supported credential collector contracts, manual console route coverage against the actual admin manifest, documented UI route drift, and documented `?section=` deep-link validity against the actual admin section config in technical docs and active plan docs. | | Quick | `scripts/harness/quick-check.sh` | Runs doctor, whitespace diff check, shell syntax checks, isolated Docker bootstrap/proxy and startup tests, error-catalog consistency tests, security scan, backend/frontend/doc consistency checks, and CI backend smoke tests. | | Full | `scripts/harness/validate.sh` | Runs quick check, frontend Bun install/build, Playwright route smoke, optional Helm checks, and opt-in Docker image smoke builds. | @@ -161,11 +161,6 @@ PLANET_HARNESS_FRONTEND_SMOKE_PORT=4174 scripts/harness/validate.sh chips, pills, tags, status labels, small buttons, cards, panels, and toolbar controls should reuse the shared component, shared token, or established CSS owner for that area instead of introducing a page-local lookalike. -- `scripts/harness/frontend-rules-check.sh` warns when semantic - `badge` / `chip` / `pill` / `tag` / `status` selectors appear outside the - approved React and Earth CSS owner files. A warning means the reviewer should - either move the style into the shared owner or document why this is a genuinely - new visual family. ### Earth I18n Harness Rules @@ -219,6 +214,12 @@ required tool is not visible there, `scripts/harness/lib.sh` asks the user's login interactive shell (`$SHELL`, then `zsh`, then `bash`) for the command path. This avoids hardcoding a dotfile while still covering agent environments that do not inherit the user's normal shell setup. +Validation adds the resolved Bun directory to its process `PATH` so package +scripts can invoke Bun as well. `test_tool_resolution.py` exercises this through +the validation entry point with an isolated login-shell tool path. +The validation build and preview share a temporary output directory that is +removed after the run. This gives the smoke a consistent build while local +development tools may rebuild `frontend/dist`. Required for full local stack operation: @@ -267,8 +268,7 @@ modify the host Docker environment. No automatic hooks are installed in this phase. Manual reminders: -- Run `scripts/harness/quick-check.sh` before handing off small changes. -- Run `scripts/harness/validate.sh` before larger cross-subsystem changes. +- Choose the verification scope using the [validation guidance in the agent guide](../AGENTS.md#validation). - Run `scripts/harness/security-check.sh` after touching config, auth, credentials, docs examples, or generated fixtures. - Run `scripts/harness/backend-rules-check.sh` after backend service edits to @@ -290,7 +290,7 @@ No automatic hooks are installed in this phase. Manual reminders: 2. Check `CODEMAP.md` for entry points and ownership boundaries. 3. Inspect existing tests and docs before editing. 4. Make the smallest behavior-preserving or feature-scoped change. -5. Run `scripts/harness/quick-check.sh` or a narrower documented command. +5. Run the checks for the affected behavior and any gates required for that area. 6. Update relevant docs when behavior, workflow, or operations change. 7. For rendered frontend changes, verify the affected route with Playwright or the full harness smoke, because `bun run build` alone does not prove page @@ -301,8 +301,6 @@ No automatic hooks are installed in this phase. Manual reminders: 1. Reproduce with a focused test or command. 2. Patch the owning module, not a caller-side workaround. 3. Run the focused regression test. -4. Run `scripts/harness/quick-check.sh` when the change is safe to validate - locally. ### Documentation Change diff --git a/docs/documentation-coverage-rules.md b/docs/documentation-coverage-rules.md index afdefd95..3ee73fec 100644 --- a/docs/documentation-coverage-rules.md +++ b/docs/documentation-coverage-rules.md @@ -14,6 +14,7 @@ If the same action has both a UI and a CLI path (e.g. user creation), describe t ## Scope Rules +- Focus documentation changes on the primary document that owns the affected behavior. Do not trigger speculative updates across secondary or architectural docs unless the underlying contract or operator-facing workflow actually changed. - User-visible workflow changes must update `docs/technical/zh/manual.md` and usually `docs/technical/zh/quickstart.md`. - If an English counterpart exists for user-facing docs such as `manual.md` or `quickstart.md`, update `docs/technical/en/...` enough that it does not contradict the Chinese source. - Control console page responsibility changes must update `docs/technical/zh/frontend-admin-frontend-context.md`. @@ -23,6 +24,7 @@ If the same action has both a UI and a CLI path (e.g. user creation), describe t - Collector, datasource, credential, settings, connectivity, scheduler, or API changes must update the relevant backend docs, especially `docs/technical/zh/backend-collectors.md` and any datasource/settings-specific doc. - When a change turns an old plan assumption into current behavior, update the relevant `docs/plans/*.md` with a status note instead of leaving contradictory instructions. - Search docs for stale terms introduced by the change, for example old tab names, old route responsibilities, obsolete auth assumptions, or renamed UI labels. +- Internal bug fixes or optimizations that preserve existing APIs and workflows do not require updating user manuals or creating new documentation. ## Public Docs Rules @@ -42,86 +44,17 @@ If the same action has both a UI and a CLI path (e.g. user creation), describe t ## Recommended Checks -Run the checks that match the affected docs. - -### Duplicate Bilingual Docs +Always run the centralized harness documentation gate: ```bash -python - <<'PY' -from pathlib import Path -same = [] -for en in sorted(Path("docs/technical/en").glob("*.md")): - zh = Path("docs/technical/zh") / en.name - if zh.exists() and en.read_text() == zh.read_text(): - same.append(en.name) -if same: - raise SystemExit("identical en/zh docs: " + ", ".join(same)) -print("no identical en/zh docs") -PY +scripts/harness/docs-consistency-check.sh ``` -### Language-Less Technical Links - -```bash -rg -n "/home/ray/dev/linkong/planet/docs/technical/(?!zh|en)" docs/technical/zh --pcre2 -``` - -This should return no matches. - -### Public Docs Registry - -```bash -python - <<'PY' -import re -from pathlib import Path - -metadata = Path("frontend/src/pages/Docs/docs-content.ts").read_text() -known = set(re.findall(r"'([^']+\.md)':\s*\{", metadata)) -known.add("README.md") - -missing = [] -for readme in [Path("docs/technical/zh/README.md"), Path("docs/technical/en/README.md")]: - if not readme.exists(): - continue - for href in re.findall(r"\]\(([^)]+\.md)\)", readme.read_text()): - path = Path(href) - if "docs/technical/" not in href: - continue - filename = path.name - if filename not in known: - missing.append(f"{readme}: {filename}") - -if missing: - raise SystemExit("docs README links missing DOCS_METADATA: " + ", ".join(missing)) -print("docs README links are whitelisted") -PY -``` - -### Public Bilingual Pairs - -```bash -python - <<'PY' -import re -from pathlib import Path - -metadata = Path("frontend/src/pages/Docs/docs-content.ts").read_text() -filenames = sorted(set(re.findall(r"'([^']+\.md)':\s*\{", metadata)) - {"README.md"}) -missing = [] -for filename in filenames: - for lang in ("zh", "en"): - path = Path("docs/technical") / lang / filename - if not path.exists(): - missing.append(str(path)) -if missing: - raise SystemExit("missing bilingual docs: " + ", ".join(missing)) -print("public docs have zh/en file pairs") -PY -``` - -### Raw Filename Link Titles - -```bash -rg -n "\[[^]]+\.md\]\(" docs/technical/zh docs/technical/en -``` - -This should return no matches for polished public docs. +This single command automatically covers: +1. Public docs whitelist and `DOCS_METADATA` synchronization (`frontend/src/pages/Docs/docs-content.ts` vs backend Gatekeeper) +2. Technical doc bilingual file pairs and identical duplicate-content detection +3. Public doc link validity and human-readable link titles (no raw `.md` filenames) +4. Language-scoped internal links (`docs/technical/zh/` links pointing to `docs/technical/zh/`) +5. Supported credential collector contracts and UI guide registration +6. Manual console route coverage against actual admin manifests +7. Documented `?section=` deep-link validity and UI route drift in active docs diff --git a/docs/harness-audit.md b/docs/harness-audit.md index e1f592e9..74a76c2a 100644 --- a/docs/harness-audit.md +++ b/docs/harness-audit.md @@ -28,8 +28,7 @@ compatibility note, not a replacement for existing rules or architecture docs. | `AGENTS.md` | Present | Single authoritative agent behavior guide. It references `rules.md`, `project_context.md`, harness validation, and high-risk areas. | | `rules.md` | Present | Mandatory modular rules. Always load `core`, `security`, and `workflow`; load topic modules as needed. | | `project_context.md` | Present | Static context. Some roadmap-era stack details are older than the current README/docs. | -| `.claude/commands/*.md` | Present | Existing command docs for cleanup, docs, goal-driven, and release workflows. | -| `.codex/skills/*.md` | Present | Existing local skills for cleanup, docs, goal-driven, and release. | +| `.codex/skills/*/SKILL.md` | Present | Local workflows for cleanup, docs, goal-driven work, and release. | ## Existing CI Gates @@ -57,8 +56,7 @@ The repository uses `.gitea/workflows/`, not `.github/workflows/`. ## Release And Deploy Process -- Release workflow is documented in `.codex/skills/release/SKILL.md` and - `.claude/commands/release.md`. +- Release workflow is documented in `.codex/skills/release/SKILL.md`. - Version-bearing files include `VERSION`, `frontend/package.json`, `pyproject.toml`, `uv.lock`, `docs/CHANGELOG.md`, and `docs/version-history.md`. @@ -102,7 +100,6 @@ The repository uses `.gitea/workflows/`, not `.github/workflows/`. | Admin/docs shell layouts can reintroduce brittle viewport sizing after a responsive fix. | Changed the admin and Docs route shells to use the existing `html/body/#root` 100% height chain, and added a frontend rules failure for exact `100vh` / `100vw` shell sizing in those CSS files. | | Compact workspaces can drift back into card-in-card layouts or implicit AntD `Space` wrappers. | Added frontend rules failures for nested `Card` components, AntD imports, and `` layout primitives in active frontend source. | | Connection-test controls can drift back into detached toolbar buttons. | Added a shared `ConnectionTestInput` suffix pattern for AI Provider and WebSearch Base URL fields, disabled WebSearch configuration/test controls when the tool is off, and made the frontend rules check fail detached AI/WebSearch connection-test buttons. | -| Same-category UI styles can fragment into page-local lookalikes. | Added same-category style owner warnings for semantic `badge`, `chip`, `pill`, `tag`, and `status` CSS selectors outside the approved shared React and Earth CSS owner files. | | Visual fixes can go wrong when agents guess from missing screenshot paths. | Documented screenshots and images as primary visual evidence: if the path is not available, agents must search alternate attachment/local locations or report the blocker instead of inferring image content. | | Public docs can reference stale admin section URLs. | Added docs consistency validation for documented `?section=` links and rendered smoke coverage for documented AI / collector deep links. | | Active plan docs can preserve old admin deep-link assumptions after the technical docs are corrected. | Extended docs consistency checks to active `docs/plans/*.md` files for stale admin tab-query terms and actual `?section=` validity; corrected the docs audience split plan to current section routes. | @@ -137,7 +134,7 @@ index is the routing layer; this table is the coverage/evidence layer. | `docs` | User manuals must match real console routes and deep links. | `docs-consistency-check.sh` compares manual console tables with `frontend/src/admin/routes/manifest.tsx` and validates documented `?section=` links from actual `AdminRoutes.tsx` plus `PlainResourcePages.tsx` section config. | Screenshots and UI-copy nuance are not exhaustively validated. | | `uiux` | Admin pages are compact single-screen workspaces with explicit overflow ownership. | `frontend-rules-check.sh` fails missing admin shell height-chain declarations (`.admin-theme-root`, `.admin`, `.admin__sider`, `.admin__nav-scroll`, `.admin__account`, `.admin__content`, `.admin__content-inner`), warns on suspicious `overflow: hidden`, and blocks exact `100vh` / `100vw` shell sizing in admin/Docs CSS. `frontend-smoke.mjs` checks every admin route at desktop/mobile and verifies `.admin` equals viewport height, `#root`/document/body have no vertical overflow, and desktop sidebar account/preferences stay in the first viewport. Zoom passes still cover 125% / 150% rendering. | Visual density, hierarchy, and whether a scroll owner feels ergonomic remain manual QA. | | `uiux` | Controls use expected patterns and accessible icon buttons. | `frontend-rules-check.sh` blocks icon `Button` without `aria-label` and `title`, native ` + - @@ -648,7 +664,15 @@ close -
输入关键词以搜索当前地球对象
+
+ + + + + + +
+
输入关键词或轻点上方分类快速探索地球对象
支持搜索海缆、登陆点、卫星、算力中心、BGP 事件与观测站。
@@ -661,33 +685,48 @@
+
+ + 海缆系统 +
— - 海缆系统
+
+ + 登陆点 +
— - 登陆点
+
+ + 在轨卫星 +
— - 在轨卫星
+
+ + 算力中心 +
— - 算力中心
+
+ + BGP 事件 +
— - BGP 事件
-
+
-
BGP 状态
+
实时态势监控
暂无观测数据
AISStream 未连接
@@ -722,12 +761,12 @@
-
+
正在准备全球态势新闻...
- +
@@ -740,7 +779,10 @@ TV 移动端新闻直播和频道切换 - +
暂无可播放直播源,请先在系统配置中添加频道。