Add ingestion logging and validation error handling with unit tests
This commit is contained in:
1 parent
b4c923ac4e
commit
f588db6434
4 files changed
+241
-2
No files matched your search
+92
-2
@@ -14,6 +14,8 @@ from zoneinfo import ZoneInfo
|
||||
|
||||
import httpx
|
||||
from fastapi import FastAPI, Header, HTTPException, Query, Request, status
|
||||
from fastapi.exception_handlers import request_validation_exception_handler
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import HTMLResponse
|
||||
from pydantic import BaseModel, Field, HttpUrl
|
||||
|
||||
@@ -30,6 +32,8 @@ MAX_VISITS_PER_REQUEST = int(os.getenv("MAX_VISITS_PER_REQUEST", "100"))
|
||||
PAGE_SIZE_CHOICES = (25, 50, 100, 250)
|
||||
DEFAULT_PAGE_SIZE = 50
|
||||
LOCAL_TIMEZONE = ZoneInfo("Europe/Ljubljana")
|
||||
INGESTION_LOG_FILENAME = "history-collector.log"
|
||||
_FILE_HANDLER_MARKER = "_history_collector_file_handler"
|
||||
|
||||
class Visit(BaseModel):
|
||||
url: HttpUrl
|
||||
@@ -43,6 +47,74 @@ class VisitBatch(BaseModel):
|
||||
|
||||
app = FastAPI(title="Local History Collector", docs_url=None, redoc_url=None)
|
||||
|
||||
_VALIDATION_LOCATION_FIELDS = frozenset(
|
||||
{"body", "device_id", "visits", "url", "title", "visit_time", "transition"}
|
||||
)
|
||||
|
||||
def local_timestamp(value: datetime | None = None) -> str:
|
||||
return (value or datetime.now(timezone.utc)).astimezone(LOCAL_TIMEZONE).isoformat(timespec="seconds")
|
||||
|
||||
class LocalLogFormatter(logging.Formatter):
|
||||
def formatTime(self, record, datefmt=None):
|
||||
return local_timestamp(datetime.fromtimestamp(record.created, timezone.utc))
|
||||
|
||||
def ingestion_log_path() -> Path:
|
||||
return DATA_DIR / INGESTION_LOG_FILENAME
|
||||
|
||||
def configure_file_logging() -> None:
|
||||
log_path = ingestion_log_path()
|
||||
log_path.resolve().parent.mkdir(parents=True, exist_ok=True)
|
||||
for handler in list(logger.handlers):
|
||||
if not getattr(handler, _FILE_HANDLER_MARKER, False):
|
||||
continue
|
||||
if Path(handler.baseFilename).resolve() == log_path.resolve():
|
||||
return
|
||||
logger.removeHandler(handler)
|
||||
handler.close()
|
||||
|
||||
handler = logging.FileHandler(log_path, mode="a", encoding="utf-8")
|
||||
try:
|
||||
os.chmod(log_path, 0o600)
|
||||
except OSError:
|
||||
handler.close()
|
||||
raise
|
||||
handler.setLevel(logging.INFO)
|
||||
handler.setFormatter(LocalLogFormatter("%(asctime)s %(levelname)s %(message)s"))
|
||||
setattr(handler, _FILE_HANDLER_MARKER, True)
|
||||
logger.addHandler(handler)
|
||||
|
||||
def validation_error_summary(exc: RequestValidationError) -> str:
|
||||
summaries = []
|
||||
errors = exc.errors()
|
||||
for error in errors[:20]:
|
||||
location = []
|
||||
for part in error.get("loc", ()):
|
||||
if isinstance(part, int):
|
||||
location.append(f"index_{part}")
|
||||
elif isinstance(part, str) and part in _VALIDATION_LOCATION_FIELDS:
|
||||
location.append(part)
|
||||
else:
|
||||
location.append("field")
|
||||
error_type = error.get("type")
|
||||
if not isinstance(error_type, str) or not error_type:
|
||||
error_type = "unknown"
|
||||
error_type = "".join(char if char.isalnum() or char in "._-" else "_" for char in error_type)[:80]
|
||||
summaries.append(f"{'.'.join(location) or 'unknown'}:{error_type or 'unknown'}")
|
||||
if len(errors) > 20:
|
||||
summaries.append(f"...+{len(errors) - 20}_more")
|
||||
return ",".join(summaries) or "unknown"
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def log_visit_validation_error(request: Request, exc: RequestValidationError):
|
||||
if request.url.path == "/v1/visits":
|
||||
logger.warning(
|
||||
"visit_ingestion_rejected ingestion_timestamp=%s timezone=Europe/Ljubljana status=422 "
|
||||
"reason=request_validation_failed validation=%s",
|
||||
local_timestamp(),
|
||||
validation_error_summary(exc),
|
||||
)
|
||||
return await request_validation_exception_handler(request, exc)
|
||||
|
||||
def domain_from_url(url: str) -> str:
|
||||
return (urlparse(url).hostname or "").lower()
|
||||
|
||||
@@ -69,6 +141,11 @@ def connect():
|
||||
|
||||
@app.on_event("startup")
|
||||
def startup():
|
||||
try:
|
||||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
configure_file_logging()
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"Unable to configure application log file at {ingestion_log_path()}: {exc}") from exc
|
||||
if len(API_TOKEN) < 24:
|
||||
raise RuntimeError("API_TOKEN must contain at least 24 characters")
|
||||
if len(VIEWER_PASSWORD) < 12:
|
||||
@@ -78,6 +155,10 @@ def startup():
|
||||
|
||||
def require_token(authorization: str | None):
|
||||
if not hmac.compare_digest(authorization or "", f"Bearer {API_TOKEN}"):
|
||||
logger.warning(
|
||||
"visit_ingestion_rejected ingestion_timestamp=%s timezone=Europe/Ljubljana status=401 reason=invalid_api_token",
|
||||
local_timestamp(),
|
||||
)
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid API token")
|
||||
|
||||
def require_viewer(request: Request):
|
||||
@@ -131,8 +212,17 @@ def healthz():
|
||||
@app.post("/v1/visits", status_code=status.HTTP_202_ACCEPTED)
|
||||
async def receive_visits(batch: VisitBatch, authorization: Annotated[str | None, Header()] = None):
|
||||
require_token(authorization)
|
||||
stored = save_batch(batch)
|
||||
ingestion_timestamp = datetime.now(timezone.utc).astimezone(LOCAL_TIMEZONE).isoformat(timespec="seconds")
|
||||
try:
|
||||
stored = save_batch(batch)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"visit_batch_save_failed ingestion_timestamp=%s timezone=Europe/Ljubljana status=500 "
|
||||
"reason=database_save_failed validated_visits=%d",
|
||||
local_timestamp(),
|
||||
len(batch.visits),
|
||||
)
|
||||
raise
|
||||
ingestion_timestamp = local_timestamp()
|
||||
logger.info(
|
||||
"visit_batch_ingested ingestion_timestamp=%s timezone=Europe/Ljubljana device_id=%s accepted=%d stored=%d",
|
||||
ingestion_timestamp,
|
||||
|
||||
Reference in new issue
Block a user