Add user delete process

This commit is contained in:
Urtzi Alfaro
2025-10-31 11:54:19 +01:00
parent 63f5c6d512
commit 269d3b5032
74 changed files with 16783 additions and 213 deletions

View File

@@ -9,6 +9,7 @@ from pydantic import BaseModel, Field
import structlog
from shared.auth.decorators import get_current_user_dep
from shared.auth.access_control import service_only_access
logger = structlog.get_logger()
@@ -236,3 +237,124 @@ async def get_trends(
except Exception as e:
logger.error("Failed to get alert trends", error=str(e), tenant_id=str(tenant_id))
raise HTTPException(status_code=500, detail=f"Failed to get trends: {str(e)}")
# ============================================================================
# Tenant Data Deletion Operations (Internal Service Only)
# ============================================================================
@router.delete(
"/api/v1/alerts/tenant/{tenant_id}",
response_model=dict
)
@service_only_access
async def delete_tenant_data(
tenant_id: str = Path(..., description="Tenant ID to delete data for"),
current_user: dict = Depends(get_current_user_dep)
):
"""
Delete all alert data for a tenant (Internal service only)
This endpoint is called by the orchestrator during tenant deletion.
It permanently deletes all alert-related data including:
- Alerts (all types and severities)
- Alert interactions
- Audit logs
**WARNING**: This operation is irreversible!
Returns:
Deletion summary with counts of deleted records
"""
from app.services.tenant_deletion_service import AlertProcessorTenantDeletionService
from app.config import AlertProcessorConfig
from shared.database.base import create_database_manager
try:
logger.info("alert_processor.tenant_deletion.api_called", tenant_id=tenant_id)
config = AlertProcessorConfig()
db_manager = create_database_manager(config.DATABASE_URL, "alert-processor")
async with db_manager.get_session() as session:
deletion_service = AlertProcessorTenantDeletionService(session)
result = await deletion_service.safe_delete_tenant_data(tenant_id)
if not result.success:
raise HTTPException(
status_code=500,
detail=f"Tenant data deletion failed: {', '.join(result.errors)}"
)
return {
"message": "Tenant data deletion completed successfully",
"summary": result.to_dict()
}
except HTTPException:
raise
except Exception as e:
logger.error("alert_processor.tenant_deletion.api_error",
tenant_id=tenant_id,
error=str(e),
exc_info=True)
raise HTTPException(
status_code=500,
detail=f"Failed to delete tenant data: {str(e)}"
)
@router.get(
"/api/v1/alerts/tenant/{tenant_id}/deletion-preview",
response_model=dict
)
@service_only_access
async def preview_tenant_data_deletion(
tenant_id: str = Path(..., description="Tenant ID to preview deletion for"),
current_user: dict = Depends(get_current_user_dep)
):
"""
Preview what data would be deleted for a tenant (dry-run)
This endpoint shows counts of all data that would be deleted
without actually deleting anything. Useful for:
- Confirming deletion scope before execution
- Auditing and compliance
- Troubleshooting
Returns:
Dictionary with entity names and their counts
"""
from app.services.tenant_deletion_service import AlertProcessorTenantDeletionService
from app.config import AlertProcessorConfig
from shared.database.base import create_database_manager
try:
logger.info("alert_processor.tenant_deletion.preview_called", tenant_id=tenant_id)
config = AlertProcessorConfig()
db_manager = create_database_manager(config.DATABASE_URL, "alert-processor")
async with db_manager.get_session() as session:
deletion_service = AlertProcessorTenantDeletionService(session)
preview = await deletion_service.get_tenant_data_preview(tenant_id)
total_records = sum(preview.values())
return {
"tenant_id": tenant_id,
"service": "alert_processor",
"preview": preview,
"total_records": total_records,
"warning": "These records will be permanently deleted and cannot be recovered"
}
except Exception as e:
logger.error("alert_processor.tenant_deletion.preview_error",
tenant_id=tenant_id,
error=str(e),
exc_info=True)
raise HTTPException(
status_code=500,
detail=f"Failed to preview tenant data deletion: {str(e)}"
)

View File

@@ -0,0 +1,6 @@
# services/alert_processor/app/services/__init__.py
"""
Alert Processor Services Package
"""
__all__ = []

View File

@@ -0,0 +1,196 @@
# services/alert_processor/app/services/tenant_deletion_service.py
"""
Tenant Data Deletion Service for Alert Processor Service
Handles deletion of all alert-related data for a tenant
"""
from typing import Dict
from sqlalchemy import select, func, delete
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.dialects.postgresql import UUID
import structlog
from shared.services.tenant_deletion import (
BaseTenantDataDeletionService,
TenantDataDeletionResult
)
from app.models import Alert, AuditLog
logger = structlog.get_logger(__name__)
class AlertProcessorTenantDeletionService(BaseTenantDataDeletionService):
"""Service for deleting all alert-related data for a tenant"""
def __init__(self, db: AsyncSession):
self.db = db
self.service_name = "alert_processor"
async def get_tenant_data_preview(self, tenant_id: str) -> Dict[str, int]:
"""
Get counts of what would be deleted for a tenant (dry-run)
Args:
tenant_id: The tenant ID to preview deletion for
Returns:
Dictionary with entity names and their counts
"""
logger.info("alert_processor.tenant_deletion.preview", tenant_id=tenant_id)
preview = {}
try:
# Count alerts (CASCADE will delete alert_interactions)
alert_count = await self.db.scalar(
select(func.count(Alert.id)).where(
Alert.tenant_id == UUID(tenant_id)
)
)
preview["alerts"] = alert_count or 0
# Note: AlertInteraction has CASCADE delete, so counting manually
# Count alert interactions for informational purposes
from app.models.alerts import AlertInteraction
interaction_count = await self.db.scalar(
select(func.count(AlertInteraction.id)).where(
AlertInteraction.tenant_id == UUID(tenant_id)
)
)
preview["alert_interactions"] = interaction_count or 0
# Count audit logs
audit_count = await self.db.scalar(
select(func.count(AuditLog.id)).where(
AuditLog.tenant_id == UUID(tenant_id)
)
)
preview["audit_logs"] = audit_count or 0
logger.info(
"alert_processor.tenant_deletion.preview_complete",
tenant_id=tenant_id,
preview=preview
)
except Exception as e:
logger.error(
"alert_processor.tenant_deletion.preview_error",
tenant_id=tenant_id,
error=str(e),
exc_info=True
)
raise
return preview
async def delete_tenant_data(self, tenant_id: str) -> TenantDataDeletionResult:
"""
Permanently delete all alert data for a tenant
Deletion order (respecting foreign key constraints):
1. AlertInteraction (child of Alert with CASCADE, but deleted explicitly for tracking)
2. Alert (parent table)
3. AuditLog (independent)
Note: AlertInteraction has CASCADE delete from Alert, so it will be
automatically deleted when Alert is deleted. We delete it explicitly
first for proper counting and logging.
Args:
tenant_id: The tenant ID to delete data for
Returns:
TenantDataDeletionResult with deletion counts and any errors
"""
logger.info("alert_processor.tenant_deletion.started", tenant_id=tenant_id)
result = TenantDataDeletionResult(tenant_id=tenant_id, service_name=self.service_name)
try:
# Import AlertInteraction here to avoid circular imports
from app.models.alerts import AlertInteraction
# Step 1: Delete alert interactions (child of alerts)
logger.info("alert_processor.tenant_deletion.deleting_interactions", tenant_id=tenant_id)
interactions_result = await self.db.execute(
delete(AlertInteraction).where(
AlertInteraction.tenant_id == UUID(tenant_id)
)
)
result.deleted_counts["alert_interactions"] = interactions_result.rowcount
logger.info(
"alert_processor.tenant_deletion.interactions_deleted",
tenant_id=tenant_id,
count=interactions_result.rowcount
)
# Step 2: Delete alerts
logger.info("alert_processor.tenant_deletion.deleting_alerts", tenant_id=tenant_id)
alerts_result = await self.db.execute(
delete(Alert).where(
Alert.tenant_id == UUID(tenant_id)
)
)
result.deleted_counts["alerts"] = alerts_result.rowcount
logger.info(
"alert_processor.tenant_deletion.alerts_deleted",
tenant_id=tenant_id,
count=alerts_result.rowcount
)
# Step 3: Delete audit logs
logger.info("alert_processor.tenant_deletion.deleting_audit_logs", tenant_id=tenant_id)
audit_result = await self.db.execute(
delete(AuditLog).where(
AuditLog.tenant_id == UUID(tenant_id)
)
)
result.deleted_counts["audit_logs"] = audit_result.rowcount
logger.info(
"alert_processor.tenant_deletion.audit_logs_deleted",
tenant_id=tenant_id,
count=audit_result.rowcount
)
# Commit the transaction
await self.db.commit()
# Calculate total deleted
total_deleted = sum(result.deleted_counts.values())
logger.info(
"alert_processor.tenant_deletion.completed",
tenant_id=tenant_id,
total_deleted=total_deleted,
breakdown=result.deleted_counts
)
result.success = True
except Exception as e:
await self.db.rollback()
error_msg = f"Failed to delete alert data for tenant {tenant_id}: {str(e)}"
logger.error(
"alert_processor.tenant_deletion.failed",
tenant_id=tenant_id,
error=str(e),
exc_info=True
)
result.errors.append(error_msg)
result.success = False
return result
def get_alert_processor_tenant_deletion_service(
db: AsyncSession
) -> AlertProcessorTenantDeletionService:
"""
Factory function to create AlertProcessorTenantDeletionService instance
Args:
db: AsyncSession database session
Returns:
AlertProcessorTenantDeletionService instance
"""
return AlertProcessorTenantDeletionService(db)