""" Celery tasks for event management and cleanup. """ from datetime import timedelta from django.utils import timezone from celery import shared_task from core.models.events import Event from core.services.events import MISSION_CRITICAL_EVENTS @shared_task def cleanup_old_events(): """ Periodic task to clean up old non-critical events. Retention policy: - Mission-critical events: Kept forever (audit trail, compliance) - Non-critical events: Deleted after 90 days This task should be scheduled to run daily or weekly via Celery Beat. """ # Calculate cutoff date (90 days ago) cutoff_date = timezone.now() - timedelta(days=90) # Delete non-critical events older than 90 days deleted_count, _ = Event.objects.filter( created_at__lt=cutoff_date ).exclude( event_type__in=MISSION_CRITICAL_EVENTS ).delete() return { 'deleted_count': deleted_count, 'cutoff_date': cutoff_date.isoformat(), 'retention_days': 90 } @shared_task def get_event_statistics(): """ Generate statistics about event storage and distribution. Useful for monitoring and capacity planning. """ from django.db.models import Count total_events = Event.objects.count() # Count by event type events_by_type = Event.objects.values('event_type').annotate( count=Count('event_type') ).order_by('-count')[:20] # Top 20 event types # Count mission-critical vs non-critical critical_count = Event.objects.filter( event_type__in=MISSION_CRITICAL_EVENTS ).count() non_critical_count = total_events - critical_count # Events in last 24 hours last_24h = timezone.now() - timedelta(hours=24) recent_count = Event.objects.filter(created_at__gte=last_24h).count() # Events in last 7 days last_7d = timezone.now() - timedelta(days=7) weekly_count = Event.objects.filter(created_at__gte=last_7d).count() return { 'total_events': total_events, 'critical_events': critical_count, 'non_critical_events': non_critical_count, 'events_last_24h': recent_count, 'events_last_7d': weekly_count, 'top_event_types': list(events_by_type), 'mission_critical_types_count': len(MISSION_CRITICAL_EVENTS), }