mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-02 01:48:08 +09:00
## Why Two alert-channel noise sources surfaced during the flacfetch download incident. Neither was a real production problem, but both page — so we fix the **monitor's signal quality** rather than mute them. ### 1. Transient encoding-worker capacity retries `[job:…] Encoding worker start failed, aborting retries: VM … 503 — SERVICE UNAVAILABLE` is a transient GCP zonal-capacity event. `render_video_worker` catches `EncodingWorkerStartError` and **parks the job for auto-retry** (`_park_job_for_capacity_retry`) — the job is *not* lost, and a genuine give-up fails the job via a separate ERROR. Added a `known_issues` suppression **scoped to the transient signal only** (503 / `SERVICE UNAVAILABLE` or a capacity code: `ZONE_RESOURCE_POOL_EXHAUSTED` / `STOCKOUT` / `QUOTA_EXCEEDED`). A non-transient `EncodingWorkerStartError` (other/unknown code) shares the prefix but **still pages**. ### 2. One incident → N alerts (normalizer gap) The same failure produced *two* alerts (same job, two preview-render IDs). `preview_<jobid>_<renderid>` is underscore-joined, and the generic hex normalizer is `\b`-anchored (`_` is a word char), so every preview render hashed to a distinct "new pattern." Added a normalizer rule that collapses `preview_<hex>_<hex>` → `preview_<ID>`. ### 3. Bot/crawler browser crashes `NotFoundError: removeChild` on `/en/r/` came from **bingbot** running headless Chrome — a React DOM-reconciliation error no real user hits (0 real-user occurrences in 7d). Reports from bot/crawler user-agents are now dropped at the `/client-errors` ingestion edge (still `202` so the client won't retry), instead of being persisted/alerted. ## Tests - `known_issues`: transient 503 **and** capacity-code variants suppressed; non-transient start failure + genuine job failure still alert. - `normalizer`: preview-ID collapse; two renders of one job → same hash. - `is_bot_user_agent`: crawler matrix true, real-browser/empty/None false. - API: a bingbot report is accepted (`202`, `is_new=false`) but **not upserted**. `133 passed`. Local CodeRabbit review completed and its two findings (scope the capacity regex; sanitize the logged bot URL) were addressed; a confirming re-review was blocked by the free-tier rate limit, so leaving the bot review on. ## Notes The actual outage in this incident (daily E2E download failure) was a **flacfetch** bug, fixed + deployed separately (flacfetch #36). This PR only removes the alert noise those investigations surfaced. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **Bug Fixes** - Bot and crawler error reports are acknowledged without being persisted or triggering alerts. - Transient encoding-worker capacity failures are filtered as retryable infrastructure noise. - Preview render job identifiers are normalized consistently for improved error grouping. - **Maintenance** - Updated the application version to 0.192.2. - Expanded validation for bot detection, error filtering, and preview error normalization. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
158 lines
5.5 KiB
Python
158 lines
5.5 KiB
Python
"""Frontend error ingestion helpers.
|
|
|
|
Converts an inbound browser crash report into a ``PatternData`` suitable for
|
|
the shared ``ErrorPatternsAdapter``. The adapter + existing error-monitor
|
|
Cloud Run Job handle all alerting / Discord plumbing.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
from dataclasses import dataclass
|
|
from datetime import datetime, timezone
|
|
from urllib.parse import urlsplit, urlunsplit
|
|
|
|
from backend.services.error_monitor.firestore_adapter import PatternData
|
|
from backend.services.error_monitor.normalizer import (
|
|
compute_pattern_hash,
|
|
normalize_message,
|
|
)
|
|
|
|
MAX_SAMPLE_MESSAGE_CHARS = 4000
|
|
MAX_URL_CHARS = 512
|
|
|
|
# Crawlers/bots execute our JS (e.g. bingbot/Googlebot run headless Chrome) and
|
|
# trip React DOM-reconciliation errors that no real user ever sees. Their reports
|
|
# are pure alert-channel noise, so we drop them at ingestion. Matches the common
|
|
# crawler tokens plus the generic bot/crawler/spider/headless markers that
|
|
# well-behaved automated agents put in their UA string.
|
|
_BOT_UA_RE = re.compile(
|
|
# Generic markers. The bot forms are anchored so we never match the "bot"
|
|
# inside ordinary words like "robot": a standalone "bot" token (\bbot\b does
|
|
# not match inside "robot" — no word boundary there) or the crawler
|
|
# "<name>bot/<version>" convention, with "robot/" explicitly excluded.
|
|
r"\bbot\b|(?<!ro)bot/|spider|crawler|crawl\b|slurp|bingpreview|headless|"
|
|
# Explicit crawler names (some don't use the "/version" convention).
|
|
r"googlebot|bingbot|applebot|yandex|baiduspider|duckduckbot|"
|
|
r"ahrefs|semrush|petalbot|facebookexternalhit|"
|
|
r"chrome-lighthouse|google page speed|python-requests|curl/|wget/",
|
|
re.IGNORECASE,
|
|
)
|
|
|
|
|
|
def is_bot_user_agent(user_agent: str | None) -> bool:
|
|
"""Return True if the UA looks like a crawler/bot/automated agent.
|
|
|
|
Conservative: only matches explicit bot markers, so a real browser UA (which
|
|
never contains these tokens) is never misclassified.
|
|
"""
|
|
if not user_agent:
|
|
return False
|
|
return bool(_BOT_UA_RE.search(user_agent))
|
|
|
|
|
|
@dataclass
|
|
class FrontendErrorReport:
|
|
"""In-memory representation of an inbound crash report."""
|
|
|
|
message: str
|
|
stack: str | None
|
|
url: str
|
|
user_agent: str
|
|
release: str
|
|
user_email: str | None
|
|
viewport: dict | None
|
|
locale: str
|
|
extra: dict | None
|
|
|
|
|
|
def sanitize_url(url: str) -> str:
|
|
"""Strip query and fragment from a URL; cap length; tolerate junk."""
|
|
if not url:
|
|
return ""
|
|
try:
|
|
parts = urlsplit(url)
|
|
if not parts.scheme:
|
|
return url[:MAX_URL_CHARS]
|
|
cleaned = urlunsplit((parts.scheme, parts.netloc, parts.path, "", ""))
|
|
return cleaned[:MAX_URL_CHARS]
|
|
except ValueError:
|
|
return url[:MAX_URL_CHARS]
|
|
|
|
|
|
def _stack_for_hashing(report: FrontendErrorReport) -> str:
|
|
"""Pick the most stable signal we have for pattern dedup.
|
|
|
|
Prefer the stack (stable across invocations) over the message (sometimes
|
|
has interpolated values). Falls back to message if no stack.
|
|
"""
|
|
if report.stack:
|
|
return report.stack
|
|
return report.message
|
|
|
|
|
|
def build_pattern_data(
|
|
report: FrontendErrorReport, now: datetime | None = None
|
|
) -> PatternData:
|
|
"""Convert an inbound report to a PatternData ready for upsert."""
|
|
if now is None:
|
|
now = datetime.now(tz=timezone.utc)
|
|
|
|
raw = _stack_for_hashing(report)
|
|
normalized = normalize_message(raw)
|
|
pattern_id = compute_pattern_hash("frontend", normalized)
|
|
|
|
# sample_message is human-readable context. Keep the error message plus a
|
|
# trimmed stack + sanitized URL so the Discord alert is self-contained.
|
|
sample_parts: list[str] = []
|
|
if report.message:
|
|
sample_parts.append(report.message.strip())
|
|
if report.stack and report.stack.strip() != (report.message or "").strip():
|
|
sample_parts.append(report.stack.strip())
|
|
clean_url = sanitize_url(report.url)
|
|
if clean_url:
|
|
sample_parts.append(f"URL: {clean_url}")
|
|
if report.user_agent:
|
|
sample_parts.append(f"UA: {report.user_agent[:200]}")
|
|
if report.release:
|
|
sample_parts.append(f"Build: {report.release}")
|
|
sample_message = "\n".join(sample_parts)[:MAX_SAMPLE_MESSAGE_CHARS]
|
|
|
|
return PatternData(
|
|
pattern_id=pattern_id,
|
|
service="frontend",
|
|
resource_type="browser",
|
|
normalized_message=normalized,
|
|
sample_message=sample_message,
|
|
count=1,
|
|
timestamp=now,
|
|
)
|
|
|
|
|
|
class RateLimiter:
|
|
"""In-memory sliding-window limiter. One instance per process is enough —
|
|
this runs inside Cloud Run which scales to multiple instances, so the
|
|
effective limit is (per_ip_per_minute * num_instances). That's fine for our
|
|
threat model (non-malicious browsers reporting their own crashes).
|
|
"""
|
|
|
|
def __init__(self, max_per_minute: int = 60) -> None:
|
|
self._max = max_per_minute
|
|
self._hits: dict[str, list[float]] = {}
|
|
|
|
def allow(self, ip: str, now_ts: float) -> bool:
|
|
cutoff = now_ts - 60.0
|
|
hits = [t for t in self._hits.get(ip, []) if t >= cutoff]
|
|
if len(hits) >= self._max:
|
|
self._hits[ip] = hits
|
|
return False
|
|
hits.append(now_ts)
|
|
self._hits[ip] = hits
|
|
# simple cleanup: if the map gets huge, drop stale keys
|
|
if len(self._hits) > 10_000:
|
|
self._hits = {
|
|
k: [t for t in v if t >= cutoff]
|
|
for k, v in self._hits.items()
|
|
if any(t >= cutoff for t in v)
|
|
}
|
|
return True
|