feat: integrate error hub (errors.bitreport.pt) for runtime error reporting
- Add forwarder/error_reporter.py: Python client for v1/ingest/events with cooldown-based dedup, best-effort delivery, and env-driven config - Add FastAPI global exception handler to report unhandled 500s - Report sync failures and forward failures from sync_service.py - Report scheduler job failures from worker/scheduler.py with cooldown - Report startup failures (ensure_admin_user) from app.py - Report worker crashes from cli.py entry point - Add error hub env vars to config.py (pydantic-settings) - Update .env.example with ERROR_REPORTING_TOKEN and related vars - Exclude IMAP/SMTP connection test errors per BIT-26136 scope note - Uses project_slug=bizdocs-forwarder, gitea_repo=BitReport.pt/forwarder Co-Authored-By: Paperclip <[email protected]>
This commit is contained in:
1 parent
f6b276511a
commit
0c63ae7fbd
7 files changed
+282
-4
No files matched your search
@@ -20,3 +20,12 @@ SYNC_INTERVAL_MINUTES=15
|
||||
DEPLOY_WEBHOOK_SECRET=change_me_random_64_chars
|
||||
# On CT 243 production, set absolute path to clone:
|
||||
# FORWARDER_REPO_DIR=/opt/forwarder
|
||||
|
||||
# Error hub (errors.bitreport.pt)
|
||||
ERROR_REPORTING_TOKEN=
|
||||
ERROR_REPORTING_ENDPOINT=https://errors.bitreport.pt
|
||||
ERROR_MONITORING_PROJECT_NAME=BizDocs Forwarder
|
||||
ERROR_MONITORING_PROJECT_SLUG=bizdocs-forwarder
|
||||
ERROR_MONITORING_GITEA_REPO=BitReport.pt/forwarder
|
||||
ERROR_MONITORING_PAPERCLIP_PROJECT_ID=
|
||||
ERROR_MONITORING_ENV=production
|
||||
@@ -1,11 +1,14 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import traceback
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from forwarder import __version__
|
||||
from forwarder.api.routes import accounts, connection, health, messages, stats, sync_runs
|
||||
from forwarder.error_reporter import report_error
|
||||
from forwarder.services.auth_service import ensure_admin_user
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -18,9 +21,25 @@ def create_app() -> FastAPI:
|
||||
description="Multi-account IMAP to BizDocs email forwarder",
|
||||
)
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def _unhandled_exception_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
logger.exception("Unhandled exception on %s %s", request.method, request.url.path)
|
||||
report_error(
|
||||
exc,
|
||||
severity="error",
|
||||
url=str(request.url),
|
||||
endpoint=f"{request.method} {request.url.path}",
|
||||
context_data={"request_method": request.method, "request_path": request.url.path},
|
||||
)
|
||||
return JSONResponse(status_code=500, content={"detail": "Internal server error"})
|
||||
|
||||
@app.on_event("startup")
|
||||
def on_startup() -> None:
|
||||
ensure_admin_user()
|
||||
try:
|
||||
ensure_admin_user()
|
||||
except Exception as exc:
|
||||
report_error(exc, severity="critical", endpoint="startup:ensure_admin_user")
|
||||
raise
|
||||
logger.info("BizDocs Forwarder API started")
|
||||
|
||||
app.include_router(health.router, prefix="/api")
|
||||
|
||||
@@ -5,6 +5,7 @@ import logging
|
||||
import sys
|
||||
|
||||
from forwarder.config import get_settings
|
||||
from forwarder.error_reporter import report_error
|
||||
from forwarder.services.auth_service import ensure_admin_user
|
||||
from forwarder.worker.scheduler import run_worker
|
||||
|
||||
@@ -35,7 +36,11 @@ def main() -> None:
|
||||
logging.getLogger(__name__).info(
|
||||
"Starting worker (default interval: %s min)", default_interval
|
||||
)
|
||||
run_worker(default_interval=default_interval)
|
||||
try:
|
||||
run_worker(default_interval=default_interval)
|
||||
except Exception as exc:
|
||||
report_error(exc, severity="critical", endpoint="cli:worker")
|
||||
raise
|
||||
return
|
||||
|
||||
parser.print_help()
|
||||
|
||||
@@ -21,6 +21,15 @@ class Settings(BaseSettings):
|
||||
api_host: str = "0.0.0.0"
|
||||
api_port: int = 8000
|
||||
|
||||
error_reporting_enabled: bool = True
|
||||
error_reporting_token: str = ""
|
||||
error_reporting_endpoint: str = "https://errors.bitreport.pt"
|
||||
error_monitoring_project_name: str = "BizDocs Forwarder"
|
||||
error_monitoring_project_slug: str = "bizdocs-forwarder"
|
||||
error_monitoring_gitea_repo: str = "BitReport.pt/forwarder"
|
||||
error_monitoring_paperclip_project_id: str = ""
|
||||
error_monitoring_env: str = "production"
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
"""Error hub client for BizDocs Forwarder.
|
||||
|
||||
Posts runtime exceptions to errors.bitreport.pt so failures enter the
|
||||
Paperclip ERRSIG triage flow. Aligned with the v1/ingest/events contract
|
||||
used by errorReporter.mjs and paperclip_exception_reporter.py.
|
||||
|
||||
Best-effort: never raises, never blocks the caller.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_DEFAULT_ENDPOINT = "https://errors.bitreport.pt"
|
||||
_DEFAULT_PROJECT_SLUG = "bizdocs-forwarder"
|
||||
_DEFAULT_GITEA_REPO = "BitReport.pt/forwarder"
|
||||
_DEFAULT_PROJECT_NAME = "BizDocs Forwarder"
|
||||
_COOLDLOCK = threading.Lock()
|
||||
_COOLDOWNS: dict[str, float] = {}
|
||||
|
||||
|
||||
def _env(name: str, default: str = "") -> str:
|
||||
return os.environ.get(name, "").strip() or default
|
||||
|
||||
|
||||
def _env_flag(name: str, default: bool) -> bool:
|
||||
raw = os.environ.get(name, "").strip().lower()
|
||||
if raw == "":
|
||||
return default
|
||||
return raw in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
class ErrorHubConfig:
|
||||
"""Lazy singleton for error hub configuration from env vars."""
|
||||
|
||||
_instance: ErrorHubConfig | None = None
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.endpoint = _env("ERROR_REPORTING_ENDPOINT", _DEFAULT_ENDPOINT).rstrip("/")
|
||||
self.token = _env("ERROR_REPORTING_TOKEN")
|
||||
self.project_name = _env("ERROR_MONITORING_PROJECT_NAME", _DEFAULT_PROJECT_NAME)
|
||||
self.project_slug = _env("ERROR_MONITORING_PROJECT_SLUG", _DEFAULT_PROJECT_SLUG)
|
||||
self.gitea_repo = _env("ERROR_MONITORING_GITEA_REPO", _DEFAULT_GITEA_REPO)
|
||||
self.paperclip_project_id = _env("ERROR_MONITORING_PAPERCLIP_PROJECT_ID")
|
||||
self.environment = _env("ERROR_MONITORING_ENV", "production")
|
||||
self.timeout_sec = 5.0
|
||||
self.enabled = _env_flag("ERROR_REPORTING_ENABLED", True)
|
||||
|
||||
@classmethod
|
||||
def get(cls) -> ErrorHubConfig:
|
||||
if cls._instance is None:
|
||||
cls._instance = cls()
|
||||
return cls._instance
|
||||
|
||||
@classmethod
|
||||
def reset(cls) -> None:
|
||||
cls._instance = None
|
||||
|
||||
@property
|
||||
def configured(self) -> bool:
|
||||
return bool(self.token)
|
||||
|
||||
|
||||
def _build_event(
|
||||
message: str,
|
||||
stacktrace: str,
|
||||
*,
|
||||
error_type: str = "Exception",
|
||||
severity: str = "error",
|
||||
context_data: Mapping[str, Any] | None = None,
|
||||
file_path: str = "",
|
||||
line_number: int = 0,
|
||||
url: str = "",
|
||||
endpoint: str = "",
|
||||
) -> dict[str, Any]:
|
||||
cfg = ErrorHubConfig.get()
|
||||
ctx: dict[str, Any] = {
|
||||
"project_name": cfg.project_name,
|
||||
"project_slug": cfg.project_slug,
|
||||
"environment": cfg.environment,
|
||||
"error_type": error_type,
|
||||
"gitea_repo": cfg.gitea_repo,
|
||||
}
|
||||
if file_path:
|
||||
ctx["file_path"] = file_path
|
||||
if line_number:
|
||||
ctx["line_number"] = line_number
|
||||
if url:
|
||||
ctx["url"] = url
|
||||
if endpoint:
|
||||
ctx["endpoint"] = endpoint
|
||||
if cfg.paperclip_project_id:
|
||||
ctx["paperclip_project_id"] = cfg.paperclip_project_id
|
||||
if context_data:
|
||||
for k, v in context_data.items():
|
||||
if k not in ctx:
|
||||
ctx[k] = v if not isinstance(v, (dict, list)) else json.dumps(v, default=str)
|
||||
|
||||
return {
|
||||
"schema_version": 1,
|
||||
"occurred_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
"level": severity,
|
||||
"message": message[:2000],
|
||||
"stacktrace": stacktrace[:12000],
|
||||
"context": ctx,
|
||||
}
|
||||
|
||||
|
||||
def _post_event(event: dict[str, Any]) -> bool:
|
||||
cfg = ErrorHubConfig.get()
|
||||
if not cfg.configured or not cfg.enabled:
|
||||
if not cfg.configured:
|
||||
logger.debug("[ERROR_HUB_NOT_CONFIGURED] token missing, skipping report")
|
||||
return False
|
||||
|
||||
url = f"{cfg.endpoint}/v1/ingest/events"
|
||||
payload = json.dumps({"events": [event]}, ensure_ascii=False).encode("utf-8")
|
||||
headers = {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"User-Agent": "BizDocs-Forwarder-ErrorReporter/1.0",
|
||||
"Authorization": f"Bearer {cfg.token}",
|
||||
}
|
||||
req = urllib.request.Request(url, method="POST", data=payload, headers=headers)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=cfg.timeout_sec) as resp:
|
||||
return resp.status // 100 == 2
|
||||
except urllib.error.HTTPError as exc:
|
||||
logger.error(
|
||||
"[ERROR_HUB_INGEST_FAILED] status=%s url=%s", exc.code, url
|
||||
)
|
||||
return False
|
||||
except Exception:
|
||||
logger.error("[ERROR_HUB_INGEST_FAILED] connection error to %s", url, exc_info=False)
|
||||
return False
|
||||
|
||||
|
||||
def report_error(
|
||||
error: BaseException | str,
|
||||
*,
|
||||
severity: str = "error",
|
||||
context_data: Mapping[str, Any] | None = None,
|
||||
url: str = "",
|
||||
endpoint: str = "",
|
||||
file_path: str = "",
|
||||
line_number: int = 0,
|
||||
) -> bool:
|
||||
"""Report an error to the error hub. Best-effort, never raises."""
|
||||
if isinstance(error, str):
|
||||
message = error[:2000]
|
||||
error_type = "Exception"
|
||||
stacktrace = traceback.format_stack()[-3:-1]
|
||||
stacktrace_text = "".join(stacktrace) if stacktrace else message
|
||||
else:
|
||||
message = f"{type(error).__name__}: {error}"[:2000]
|
||||
error_type = type(error).__name__
|
||||
stacktrace_text = "".join(
|
||||
traceback.format_exception(type(error), error, error.__traceback__)
|
||||
)[:12000]
|
||||
|
||||
event = _build_event(
|
||||
message=message,
|
||||
stacktrace=stacktrace_text,
|
||||
error_type=error_type,
|
||||
severity=severity,
|
||||
context_data=context_data,
|
||||
file_path=file_path,
|
||||
line_number=line_number,
|
||||
url=url,
|
||||
endpoint=endpoint,
|
||||
)
|
||||
return _post_event(event)
|
||||
|
||||
|
||||
def report_error_with_cooldown(
|
||||
key: str,
|
||||
cooldown_seconds: float,
|
||||
error: BaseException | str,
|
||||
*,
|
||||
severity: str = "error",
|
||||
context_data: Mapping[str, Any] | None = None,
|
||||
url: str = "",
|
||||
endpoint: str = "",
|
||||
) -> bool:
|
||||
"""Report an error but suppress duplicates within *cooldown_seconds*."""
|
||||
now = time.monotonic()
|
||||
with _COOLDLOCK:
|
||||
last = _COOLDOWNS.get(key, 0.0)
|
||||
if now - last < cooldown_seconds:
|
||||
return False
|
||||
_COOLDOWNS[key] = now
|
||||
|
||||
return report_error(
|
||||
error,
|
||||
severity=severity,
|
||||
context_data=context_data,
|
||||
url=url,
|
||||
endpoint=endpoint,
|
||||
)
|
||||
@@ -30,6 +30,7 @@ from forwarder.email.parsing import (
|
||||
has_matching_attachment,
|
||||
)
|
||||
from forwarder.email.smtp_client import SmtpConfig, create_smtp_client, forward_email_as_eml
|
||||
from forwarder.error_reporter import report_error, report_error_with_cooldown
|
||||
from forwarder.services.account_service import get_account
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -282,6 +283,16 @@ def sync_account(
|
||||
except Exception as exc:
|
||||
error_text = str(exc)
|
||||
logger.error("Forward failed for %s: %s", subject, error_text)
|
||||
report_error(
|
||||
exc,
|
||||
context_data={
|
||||
"account_id": account_id,
|
||||
"subject": subject,
|
||||
"folder": folder,
|
||||
"uid": uid_str,
|
||||
},
|
||||
endpoint="sync:forward_email",
|
||||
)
|
||||
message_row = _upsert_message(
|
||||
db,
|
||||
account_id=account_id,
|
||||
@@ -308,6 +319,14 @@ def sync_account(
|
||||
sync_run.status = SyncRunStatus.failed
|
||||
sync_run.error_message = str(exc)
|
||||
logger.exception("Sync failed for account %s", account_id)
|
||||
report_error_with_cooldown(
|
||||
f"sync_account:{account_id}",
|
||||
300.0,
|
||||
exc,
|
||||
severity="error",
|
||||
context_data={"account_id": account_id},
|
||||
endpoint="sync:account",
|
||||
)
|
||||
finally:
|
||||
if imap is not None:
|
||||
try:
|
||||
|
||||
@@ -7,6 +7,7 @@ from apscheduler.triggers.interval import IntervalTrigger
|
||||
|
||||
from forwarder.db.models import Account
|
||||
from forwarder.db.session import get_session_factory
|
||||
from forwarder.error_reporter import report_error_with_cooldown
|
||||
from forwarder.services.sync_service import sync_account
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -17,8 +18,16 @@ def _sync_job(account_id: int) -> None:
|
||||
try:
|
||||
logger.info("Scheduled sync starting for account %s", account_id)
|
||||
sync_account(db, account_id, dry_run=False)
|
||||
except Exception:
|
||||
except Exception as exc:
|
||||
logger.exception("Scheduled sync failed for account %s", account_id)
|
||||
report_error_with_cooldown(
|
||||
f"scheduler:sync_account:{account_id}",
|
||||
300.0,
|
||||
exc,
|
||||
severity="error",
|
||||
context_data={"account_id": account_id},
|
||||
endpoint="scheduler:sync_job",
|
||||
)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
Reference in new issue
Block a user