43 lines
1.4 KiB
Python
43 lines
1.4 KiB
Python
"""Periodic purge of alert_logs older than ALERT_LOG_RETENTION_DAYS (7 days)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import logging
|
|
|
|
from server.infrastructure.database.alert_log_repo import (
|
|
ALERT_LOG_RETENTION_DAYS,
|
|
AlertLogRepositoryImpl,
|
|
)
|
|
from server.infrastructure.database.session import AsyncSessionLocal
|
|
|
|
logger = logging.getLogger("nexus.alert_log_purge")
|
|
|
|
PURGE_INTERVAL_SECONDS = 24 * 3600
|
|
|
|
|
|
async def purge_stale_alert_logs() -> int:
|
|
"""Delete alert_logs rows older than retention window. Returns rows removed."""
|
|
async with AsyncSessionLocal() as session:
|
|
repo = AlertLogRepositoryImpl(session)
|
|
return await repo.purge_older_than(retention_days=ALERT_LOG_RETENTION_DAYS)
|
|
|
|
|
|
async def alert_log_purge_loop() -> None:
|
|
"""Run daily on primary worker; first purge runs immediately at startup."""
|
|
while True:
|
|
try:
|
|
count = await purge_stale_alert_logs()
|
|
if count:
|
|
logger.info(
|
|
"Alert log purge: removed %s row(s) older than %s days",
|
|
count,
|
|
ALERT_LOG_RETENTION_DAYS,
|
|
)
|
|
await asyncio.sleep(PURGE_INTERVAL_SECONDS)
|
|
except asyncio.CancelledError:
|
|
raise
|
|
except Exception:
|
|
logger.exception("Alert log purge loop error")
|
|
await asyncio.sleep(PURGE_INTERVAL_SECONDS)
|