ariadne/ariadne/services/mailu_events.py

152 lines
4.9 KiB
Python

from __future__ import annotations
from dataclasses import dataclass
import threading
import time
from typing import Any, Callable
from ..metrics.metrics import record_task_run
from ..settings import settings
from ..utils.logging import get_logger, task_context
from .mailu import mailu
logger = get_logger(__name__)
@dataclass(frozen=True)
class MailuEventResult:
status: str
detail: str = ""
triggered: bool = False
def _parse_bool(payload: dict[str, Any] | None, key: str) -> bool:
if not isinstance(payload, dict):
return False
value = payload.get(key)
if isinstance(value, bool):
return value
if isinstance(value, str):
return value.strip().lower() in {"1", "true", "yes", "y", "on"}
return False
def _event_reason(payload: dict[str, Any] | None) -> str:
if not isinstance(payload, dict):
return "keycloak_event"
for key in ("eventType", "type", "event_type"):
value = payload.get(key)
if isinstance(value, str) and value.strip():
return f"keycloak_event:{value.strip()}"
return "keycloak_event"
def _event_context(payload: dict[str, Any] | None) -> dict[str, Any]:
if not isinstance(payload, dict):
return {}
context: dict[str, Any] = {}
for key in ("eventType", "type", "userId", "clientId", "realmId"):
value = payload.get(key)
if isinstance(value, str) and value.strip():
context[key] = value.strip()
return context
class MailuEventRunner:
def __init__(
self,
min_interval_sec: float,
wait_timeout_sec: float,
runner: Callable[[str, bool], tuple[str, str]] | None = None,
thread_factory: Callable[..., threading.Thread] = threading.Thread,
) -> None:
self._min_interval_sec = min_interval_sec
self._wait_timeout_sec = wait_timeout_sec
self._runner = runner or self._default_runner
self._thread_factory = thread_factory
self._lock = threading.Lock()
self._last_run = 0.0
self._last_status = "unknown"
self._last_detail = ""
self._running = False
self._done = threading.Event()
self._done.set()
def _default_runner(self, reason: str, force: bool) -> tuple[str, str]:
summary = mailu.sync(reason, force=force)
status = "ok" if summary.failures == 0 else "error"
return status, summary.detail
def _run_sync(self, reason: str, force: bool) -> None:
started = time.monotonic()
status = "error"
detail = ""
with task_context("mailu_event"):
try:
status, detail = self._runner(reason, force)
except Exception as exc: # noqa: BLE001
status = "error"
detail = str(exc).strip() or "mailu sync failed"
finally:
duration = time.monotonic() - started
record_task_run("mailu_event", status, duration)
with self._lock:
self._running = False
self._last_run = time.time()
self._last_status = status
self._last_detail = detail
self._done.set()
def _trigger(self, reason: str, force: bool) -> bool:
with self._lock:
now = time.time()
if self._running:
return False
if not force and now - self._last_run < self._min_interval_sec:
return False
self._running = True
self._done.clear()
thread = self._thread_factory(
target=self._run_sync,
args=(reason, force),
daemon=True,
)
thread.start()
return True
def handle_event(self, payload: dict[str, Any] | None) -> tuple[int, dict[str, Any]]:
wait = _parse_bool(payload, "wait")
force = _parse_bool(payload, "force")
reason = _event_reason(payload)
context = _event_context(payload)
triggered = self._trigger(reason, force=force)
logger.info(
"mailu event received",
extra={"event": "mailu_event", "status": "queued" if triggered else "skipped", **context},
)
if not wait:
result = MailuEventResult(
status="accepted" if triggered else "skipped",
triggered=triggered,
)
return 202, {"status": result.status, "triggered": result.triggered}
self._done.wait(timeout=self._wait_timeout_sec)
with self._lock:
running = self._running
status = self._last_status
detail = self._last_detail
if running:
return 200, {"status": "running"}
return (200 if status == "ok" else 500), {"status": status, "detail": detail}
mailu_events = MailuEventRunner(
min_interval_sec=settings.mailu_event_min_interval_sec,
wait_timeout_sec=settings.mailu_sync_wait_timeout_sec,
)