Files
Nexus/server/background/audit_log_purge.py
2026-07-08 22:31:31 +08:00

43 lines
1.4 KiB
Python

"""Periodic purge of audit_logs older than AUDIT_LOG_RETENTION_DAYS (7 days)."""
from __future__ import annotations
import asyncio
import logging
from server.infrastructure.database.audit_log_repo import (
AUDIT_LOG_RETENTION_DAYS,
AuditLogRepositoryImpl,
)
from server.infrastructure.database.session import AsyncSessionLocal
logger = logging.getLogger("nexus.audit_log_purge")
PURGE_INTERVAL_SECONDS = 24 * 3600
async def purge_stale_audit_logs() -> int:
"""Delete audit_logs rows older than retention window. Returns rows removed."""
async with AsyncSessionLocal() as session:
repo = AuditLogRepositoryImpl(session)
return await repo.purge_older_than(retention_days=AUDIT_LOG_RETENTION_DAYS)
async def audit_log_purge_loop() -> None:
"""Run daily on primary worker; first purge runs immediately at startup."""
while True:
try:
count = await purge_stale_audit_logs()
if count:
logger.info(
"Audit log purge: removed %s row(s) older than %s days",
count,
AUDIT_LOG_RETENTION_DAYS,
)
await asyncio.sleep(PURGE_INTERVAL_SECONDS)
except asyncio.CancelledError:
raise
except Exception:
logger.exception("Audit log purge loop error")
await asyncio.sleep(PURGE_INTERVAL_SECONDS)