Add ingestion logging and validation error handling with unit tests

This commit is contained in:
komelt committed 2026-10-15 17:53:57 +02:00
1 parent b4c923ac4e
commit f588db6434
4 files changed
+241 -2

No files matched your search

+2
View File
@@ -16,6 +16,8 @@ curl http://127.0.0.1:8080/healthz
Privzeto posluša samo na `127.0.0.1:8080`. Za dostop iz drugih naprav uporabi VPN (Tailscale/WireGuard) ali HTTPS reverse proxy. Ne odpiraj porta neposredno v internet.
Aplikacijski dnevniki sprejemanja se dodatno pripisujejo v `/data/history-collector.log` (na gostitelju `./data/history-collector.log`).
## API
`POST /v1/visits`, z glavo `Authorization: Bearer TVOJ_API_TOKEN`:
+92 -2
View File
@@ -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,
View File
Whitespace-only changes.
+147
View File
@@ -0,0 +1,147 @@
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
import httpx
from app import main
class IngestionLoggingTests(unittest.IsolatedAsyncioTestCase):
API_TOKEN = "test-api-token-that-is-long-enough"
SENTINELS = {
"token-ingestion-sentinel",
"device-ingestion-sentinel",
"https://url-ingestion-sentinel.example/secret",
"url-ingestion-invalid-sentinel",
"title-ingestion-sentinel",
"transition-ingestion-sentinel",
"2049-07-28T15:41:26+00:00",
}
async def request(self, **kwargs):
transport = httpx.ASGITransport(app=main.app, raise_app_exceptions=False)
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
return await client.post("/v1/visits", **kwargs)
def setUp(self):
main.API_TOKEN = self.API_TOKEN
def assert_local_timestamp(self, line):
self.assertRegex(line, r"ingestion_timestamp=\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}")
def assert_no_sentinels(self, line):
for sentinel in self.SENTINELS:
self.assertNotIn(sentinel, line)
def valid_payload(self):
return {
"device_id": "device-ingestion-sentinel",
"visits": [{
"url": "https://url-ingestion-sentinel.example/secret",
"title": "title-ingestion-sentinel",
"visit_time": "2049-07-28T15:41:26+00:00",
"transition": "transition-ingestion-sentinel",
}],
}
async def test_invalid_token_is_logged_without_authorization_value(self):
invalid_token = "token-ingestion-sentinel"
with self.assertLogs(main.logger, "WARNING") as captured:
response = await self.request(
headers={"Authorization": f"Bearer {invalid_token}"},
json=self.valid_payload(),
)
self.assertEqual(response.status_code, 401)
self.assertEqual(response.json(), {"detail": "Invalid API token"})
line = "\n".join(captured.output)
self.assert_local_timestamp(line)
self.assertIn("timezone=Europe/Ljubljana", line)
self.assertIn("status=401", line)
self.assertIn("reason=invalid_api_token", line)
self.assert_no_sentinels(line)
async def test_validation_log_is_sanitized_and_response_is_standard_422(self):
payload = self.valid_payload()
payload["visits"][0]["url"] = "url-ingestion-invalid-sentinel"
with self.assertLogs(main.logger, "WARNING") as captured:
response = await self.request(json=payload)
self.assertEqual(response.status_code, 422)
self.assertEqual(set(response.json()), {"detail"})
self.assertIsInstance(response.json()["detail"], list)
line = "\n".join(captured.output)
self.assert_local_timestamp(line)
self.assertIn("timezone=Europe/Ljubljana", line)
self.assertIn("status=422", line)
self.assertIn("body.visits.index_0", line)
self.assert_no_sentinels(line)
async def test_database_failure_is_logged_and_returns_500(self):
with patch.object(main, "save_batch", side_effect=RuntimeError("database unavailable")):
with self.assertLogs(main.logger, "ERROR") as captured:
response = await self.request(
headers={"Authorization": f"Bearer {self.API_TOKEN}"},
json=self.valid_payload(),
)
self.assertEqual(response.status_code, 500)
self.assertEqual(response.text, "Internal Server Error")
line = "\n".join(captured.output)
self.assert_local_timestamp(line)
self.assertIn("timezone=Europe/Ljubljana", line)
self.assertIn("status=500", line)
self.assertIn("validated_visits=1", line)
self.assertNotIn("device_id=", line)
self.assertNotIn("accepted=", line)
self.assert_no_sentinels(line)
async def test_malformed_json_is_logged_as_422_without_body_contents(self):
invalid_body = b'{"device_id":"test-device",'
with self.assertLogs(main.logger, "WARNING") as captured:
response = await self.request(
content=invalid_body,
headers={"Content-Type": "application/json"},
)
self.assertEqual(response.status_code, 422)
self.assertEqual(set(response.json()), {"detail"})
self.assertIsInstance(response.json()["detail"], list)
line = "\n".join(captured.output)
self.assert_local_timestamp(line)
self.assertIn("status=422", line)
self.assertNotIn(invalid_body.decode(), line)
def test_file_logging_is_append_only_and_idempotent(self):
original_data_dir = main.DATA_DIR
original_handler_ids = {id(handler) for handler in main.logger.handlers}
with TemporaryDirectory() as temp_dir:
main.DATA_DIR = Path(temp_dir)
log_path = main.ingestion_log_path()
log_path.write_text("existing line\n", encoding="utf-8")
try:
main.configure_file_logging()
main.logger.info("file_logging_sentinel")
for handler in main.logger.handlers:
handler.flush()
main.configure_file_logging()
file_handlers = [handler for handler in main.logger.handlers if getattr(handler, main._FILE_HANDLER_MARKER, False)]
self.assertEqual(len(file_handlers), 1)
lines = log_path.read_text(encoding="utf-8").splitlines()
self.assertEqual(lines[0], "existing line")
self.assertEqual(len(lines), 2)
self.assertRegex(lines[1], r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2} INFO file_logging_sentinel$")
self.assertEqual(log_path.stat().st_mode & 0o777, 0o600)
finally:
for handler in list(main.logger.handlers):
if id(handler) not in original_handler_ids:
main.logger.removeHandler(handler)
handler.close()
main.DATA_DIR = original_data_dir
if __name__ == "__main__":
unittest.main()