File size: 10,941 Bytes
138f7cb 3177117 138f7cb |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 |
"""
Module: infrastructure.queue.tasks.investigation_tasks
Description: Celery tasks for investigation processing
Author: Anderson H. Silva
Date: 2025-01-25
License: Proprietary - All rights reserved
"""
from typing import Dict, Any, List, Optional
from datetime import datetime
import asyncio
from celery import group, chain
from celery.utils.log import get_task_logger
from src.infrastructure.queue.celery_app import celery_app, priority_task, TaskPriority
from src.services.investigation_service_selector import investigation_service as InvestigationService
from src.services.data_service import DataService
from src.core.dependencies import get_db_session
from src.agents import get_agent_pool
logger = get_task_logger(__name__)
@celery_app.task(name="tasks.run_investigation", bind=True, queue="high")
def run_investigation(
self,
investigation_id: str,
query: str,
config: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""
Run a complete investigation asynchronously.
Args:
investigation_id: Unique investigation ID
query: Investigation query
config: Optional investigation configuration
Returns:
Investigation results
"""
try:
logger.info(
"investigation_started",
investigation_id=investigation_id,
query=query[:100]
)
# Run async investigation in sync context
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
result = loop.run_until_complete(
_run_investigation_async(investigation_id, query, config)
)
logger.info(
"investigation_completed",
investigation_id=investigation_id,
findings_count=len(result.get("findings", []))
)
return result
finally:
loop.close()
except Exception as e:
logger.error(
"investigation_failed",
investigation_id=investigation_id,
error=str(e),
exc_info=True
)
# Retry with exponential backoff
raise self.retry(
exc=e,
countdown=60 * (2 ** self.request.retries),
max_retries=3
)
async def _run_investigation_async(
investigation_id: str,
query: str,
config: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""Async implementation of investigation."""
async with get_db_session() as db:
investigation_service = InvestigationService(db)
agent_pool = get_agent_pool()
# Create investigation
investigation = await investigation_service.create(
query=query,
context=config or {},
initiated_by="celery_task"
)
# Run investigation with agents
result = await investigation_service.run_investigation(
investigation_id=investigation.id,
agent_pool=agent_pool
)
return result.dict()
@celery_app.task(name="tasks.analyze_contracts_batch", queue="normal")
def analyze_contracts_batch(
contract_ids: List[str],
analysis_type: str = "anomaly",
threshold: float = 0.7
) -> Dict[str, Any]:
"""
Analyze multiple contracts in batch.
Args:
contract_ids: List of contract IDs to analyze
analysis_type: Type of analysis (anomaly, compliance, value)
threshold: Detection threshold
Returns:
Batch analysis results
"""
logger.info(
"batch_analysis_started",
contract_count=len(contract_ids),
analysis_type=analysis_type
)
# Create subtasks for each contract
tasks = []
for contract_id in contract_ids:
task = analyze_single_contract.s(
contract_id=contract_id,
analysis_type=analysis_type,
threshold=threshold
)
tasks.append(task)
# Execute tasks in parallel
job = group(tasks)
results = job.apply_async()
# Wait for results
contract_results = results.get(timeout=300) # 5 minutes timeout
# Aggregate results
summary = {
"total_contracts": len(contract_ids),
"analyzed": len(contract_results),
"anomalies_found": sum(1 for r in contract_results if r.get("has_anomaly", False)),
"analysis_type": analysis_type,
"threshold": threshold,
"results": contract_results
}
logger.info(
"batch_analysis_completed",
total=summary["total_contracts"],
anomalies=summary["anomalies_found"]
)
return summary
@celery_app.task(name="tasks.analyze_single_contract", queue="normal")
def analyze_single_contract(
contract_id: str,
analysis_type: str,
threshold: float
) -> Dict[str, Any]:
"""Analyze a single contract."""
try:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
result = loop.run_until_complete(
_analyze_contract_async(contract_id, analysis_type, threshold)
)
return result
finally:
loop.close()
except Exception as e:
logger.error(
"contract_analysis_failed",
contract_id=contract_id,
error=str(e)
)
return {
"contract_id": contract_id,
"error": str(e),
"has_anomaly": False
}
async def _analyze_contract_async(
contract_id: str,
analysis_type: str,
threshold: float
) -> Dict[str, Any]:
"""Async contract analysis."""
async with get_db_session() as db:
data_service = DataService(db)
agent_pool = get_agent_pool()
# Get contract data
contract = await data_service.get_contract(contract_id)
if not contract:
return {
"contract_id": contract_id,
"error": "Contract not found",
"has_anomaly": False
}
# Get Zumbi agent for anomaly detection
zumbi = agent_pool.get_agent("zumbi")
if not zumbi:
return {
"contract_id": contract_id,
"error": "Agent not available",
"has_anomaly": False
}
# Analyze contract
analysis = await zumbi.analyze_contract(
contract,
threshold=threshold,
analysis_type=analysis_type
)
return {
"contract_id": contract_id,
"has_anomaly": analysis.anomaly_detected,
"anomaly_score": analysis.anomaly_score,
"indicators": analysis.indicators,
"recommendations": analysis.recommendations
}
@celery_app.task(name="tasks.detect_anomalies_batch", queue="high")
def detect_anomalies_batch(
data_source: str,
time_range: Dict[str, str],
detection_config: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""
Run batch anomaly detection on data source.
Args:
data_source: Source of data (contracts, transactions, etc.)
time_range: Time range for analysis
detection_config: Detection configuration
Returns:
Anomaly detection results
"""
logger.info(
"anomaly_detection_started",
data_source=data_source,
time_range=time_range
)
try:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
result = loop.run_until_complete(
_detect_anomalies_async(data_source, time_range, detection_config)
)
logger.info(
"anomaly_detection_completed",
anomalies_found=len(result.get("anomalies", []))
)
return result
finally:
loop.close()
except Exception as e:
logger.error(
"anomaly_detection_failed",
error=str(e),
exc_info=True
)
raise
async def _detect_anomalies_async(
data_source: str,
time_range: Dict[str, str],
detection_config: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""Async anomaly detection."""
async with get_db_session() as db:
data_service = DataService(db)
agent_pool = get_agent_pool()
# Get data for analysis
if data_source == "contracts":
data = await data_service.get_contracts_in_range(
start_date=time_range.get("start"),
end_date=time_range.get("end")
)
else:
raise ValueError(f"Unknown data source: {data_source}")
# Get Zumbi agent
zumbi = agent_pool.get_agent("zumbi")
if not zumbi:
raise RuntimeError("Anomaly detection agent not available")
# Run detection
anomalies = []
for item in data:
result = await zumbi.detect_anomalies(
data=item,
config=detection_config or {}
)
if result.anomaly_detected:
anomalies.append({
"id": item.get("id"),
"type": result.anomaly_type,
"score": result.anomaly_score,
"description": result.description,
"timestamp": datetime.now().isoformat()
})
return {
"data_source": data_source,
"time_range": time_range,
"total_analyzed": len(data),
"anomalies_found": len(anomalies),
"anomalies": anomalies
}
@priority_task(priority=TaskPriority.CRITICAL)
def emergency_investigation(
query: str,
reason: str,
initiated_by: str
) -> Dict[str, Any]:
"""
Run emergency investigation with highest priority.
Args:
query: Investigation query
reason: Reason for emergency
initiated_by: Who initiated the investigation
Returns:
Investigation results
"""
logger.warning(
"emergency_investigation_started",
query=query[:100],
reason=reason,
initiated_by=initiated_by
)
# Create investigation with special handling
investigation_id = f"EMERGENCY-{datetime.now().strftime('%Y%m%d%H%M%S')}"
# Run with increased resources
result = run_investigation.apply_async(
args=[investigation_id, query],
kwargs={"config": {"priority": "critical", "reason": reason}},
priority=10, # Highest priority
time_limit=1800, # 30 minutes
)
return result.get() |