Coverage for /Users/les/Projects/crackerjack/crackerjack/services/bounded_status_operations.py: 0%
197 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
1"""
2Bounded Status Operations to prevent DoS attacks.
4Provides comprehensive operation limits, circuit breakers, and
5resource protection for status collection operations.
6"""
8import asyncio
9import time
10import typing as t
11from collections import defaultdict, deque
12from dataclasses import dataclass, field
13from enum import Enum
14from threading import RLock
16from .security_logger import SecurityEventLevel, SecurityEventType, get_security_logger
19class OperationState(str, Enum):
20 """States for circuit breaker pattern."""
22 CLOSED = "closed" # Normal operation
23 OPEN = "open" # Circuit breaker tripped
24 HALF_OPEN = "half_open" # Testing if service recovered
27@dataclass
28class OperationLimits:
29 """Limits for status operations."""
31 max_concurrent_operations: int = 10
32 max_operations_per_minute: int = 60
33 max_operation_duration: float = 30.0
34 max_memory_usage_mb: int = 50
35 max_cpu_time_seconds: float = 5.0
36 max_file_operations: int = 100
37 timeout_seconds: float = 15.0
38 circuit_breaker_threshold: int = 5
39 circuit_breaker_timeout: float = 60.0
42@dataclass
43class OperationMetrics:
44 """Metrics for operation tracking."""
46 operation_id: str
47 operation_type: str
48 client_id: str
49 start_time: float = field(default_factory=time.time)
50 end_time: float | None = None
51 memory_usage: int = 0
52 cpu_time: float = 0.0
53 file_operations: int = 0
54 success: bool | None = None
55 error_message: str | None = None
57 @property
58 def duration(self) -> float:
59 """Get operation duration in seconds."""
60 end = self.end_time or time.time()
61 return end - self.start_time
63 @property
64 def is_completed(self) -> bool:
65 """Check if operation is completed."""
66 return self.end_time is not None
69class OperationLimitExceededError(Exception):
70 """Raised when operation limits are exceeded."""
72 pass
75class CircuitBreakerOpenError(Exception):
76 """Raised when circuit breaker is open."""
78 pass
81class BoundedStatusOperations:
82 """
83 Bounded operations manager for status collection.
85 Features:
86 - Concurrent operation limits
87 - Rate limiting per client
88 - Memory and CPU usage monitoring
89 - Circuit breaker pattern for fault tolerance
90 - Operation timeout enforcement
91 - Comprehensive metrics collection
92 """
94 def __init__(self, limits: OperationLimits | None = None):
95 """
96 Initialize bounded operations manager.
98 Args:
99 limits: Operation limits configuration
100 """
101 self.limits = limits or OperationLimits()
102 self.security_logger = get_security_logger()
104 # Thread-safe operation tracking
105 self._lock = RLock()
106 self._active_operations: dict[str, OperationMetrics] = {}
107 self._client_operations: dict[str, deque] = defaultdict(
108 lambda: deque(maxlen=100)
109 )
110 self._operation_history: list[OperationMetrics] = []
112 # Circuit breaker tracking
113 self._circuit_states: dict[str, OperationState] = defaultdict(
114 lambda: OperationState.CLOSED
115 )
116 self._failure_counts: dict[str, int] = defaultdict(int)
117 self._last_failure_times: dict[str, float] = {}
119 # Resource usage tracking
120 self._total_memory_usage = 0
121 self._total_cpu_time = 0.0
122 self._total_file_operations = 0
124 # Operation type definitions
125 self._operation_types = {
126 "collect_status": "Status collection operation",
127 "get_jobs": "Job information retrieval",
128 "get_services": "Service status check",
129 "get_metrics": "Metrics collection",
130 "health_check": "Health check operation",
131 }
133 async def execute_bounded_operation(
134 self,
135 operation_type: str,
136 client_id: str,
137 operation_func: t.Callable[..., t.Awaitable[t.Any]],
138 *args,
139 **kwargs,
140 ) -> t.Any:
141 """
142 Execute a bounded status operation with comprehensive limits.
144 Args:
145 operation_type: Type of operation being performed
146 client_id: Client identifier
147 operation_func: Async function to execute
148 *args: Positional arguments for operation_func
149 **kwargs: Keyword arguments for operation_func
151 Returns:
152 Result of the operation
154 Raises:
155 OperationLimitExceededError: If operation limits exceeded
156 CircuitBreakerOpenError: If circuit breaker is open
157 asyncio.TimeoutError: If operation times out
158 """
160 # Check circuit breaker
161 self._check_circuit_breaker(operation_type)
163 # Validate operation can be started
164 operation_id = self._validate_and_reserve_operation(operation_type, client_id)
166 # Create operation metrics
167 metrics = OperationMetrics(
168 operation_id=operation_id,
169 operation_type=operation_type,
170 client_id=client_id,
171 )
173 try:
174 # Register operation
175 with self._lock:
176 self._active_operations[operation_id] = metrics
178 # Execute with timeout and resource monitoring
179 result = await self._execute_with_monitoring(
180 operation_func, metrics, *args, **kwargs
181 )
183 # Mark as successful
184 metrics.success = True
185 metrics.end_time = time.time()
187 # Update circuit breaker on success
188 self._record_operation_success(operation_type)
190 # Log successful operation
191 self.security_logger.log_security_event(
192 event_type=SecurityEventType.OPERATION_SUCCESS,
193 level=SecurityEventLevel.INFO,
194 message=f"Operation completed: {operation_type}",
195 client_id=client_id,
196 operation=operation_type,
197 additional_data={
198 "operation_id": operation_id,
199 "duration": metrics.duration,
200 "memory_usage": metrics.memory_usage,
201 "cpu_time": metrics.cpu_time,
202 "file_operations": metrics.file_operations,
203 },
204 )
206 return result
208 except Exception as e:
209 # Mark as failed
210 metrics.success = False
211 metrics.end_time = time.time()
212 metrics.error_message = str(e)
214 # Update circuit breaker on failure
215 self._record_operation_failure(operation_type)
217 # Log failed operation
218 self.security_logger.log_security_event(
219 event_type=SecurityEventType.OPERATION_FAILURE,
220 level=SecurityEventLevel.ERROR,
221 message=f"Operation failed: {operation_type} - {e}",
222 client_id=client_id,
223 operation=operation_type,
224 additional_data={
225 "operation_id": operation_id,
226 "duration": metrics.duration,
227 "error": str(e),
228 },
229 )
231 raise
233 finally:
234 # Clean up operation
235 self._cleanup_operation(operation_id, metrics)
237 def _check_circuit_breaker(self, operation_type: str) -> None:
238 """Check if circuit breaker allows operation."""
240 current_time = time.time()
242 with self._lock:
243 state = self._circuit_states[operation_type]
244 failure_count = self._failure_counts[operation_type]
245 last_failure = self._last_failure_times.get(operation_type, 0)
247 if state == OperationState.OPEN:
248 # Check if circuit breaker timeout has passed
249 if current_time - last_failure >= self.limits.circuit_breaker_timeout:
250 # Move to half-open state for testing
251 self._circuit_states[operation_type] = OperationState.HALF_OPEN
252 self.security_logger.log_security_event(
253 event_type=SecurityEventType.CIRCUIT_BREAKER_HALF_OPEN,
254 level=SecurityEventLevel.INFO,
255 message=f"Circuit breaker half-open: {operation_type}",
256 operation=operation_type,
257 )
258 else:
259 # Circuit breaker still open
260 self.security_logger.log_security_event(
261 event_type=SecurityEventType.CIRCUIT_BREAKER_OPEN,
262 level=SecurityEventLevel.WARNING,
263 message=f"Circuit breaker open: {operation_type}",
264 operation=operation_type,
265 additional_data={
266 "failure_count": failure_count,
267 "time_remaining": self.limits.circuit_breaker_timeout
268 - (current_time - last_failure),
269 },
270 )
271 raise CircuitBreakerOpenError(
272 f"Circuit breaker open for {operation_type}"
273 )
275 def _validate_and_reserve_operation(
276 self, operation_type: str, client_id: str
277 ) -> str:
278 """Validate operation can be started and reserve resources."""
280 current_time = time.time()
281 operation_id = f"{operation_type}_{client_id}_{int(current_time * 1000)}"
283 with self._lock:
284 # Check concurrent operation limit
285 if len(self._active_operations) >= self.limits.max_concurrent_operations:
286 self.security_logger.log_security_event(
287 event_type=SecurityEventType.RATE_LIMIT_EXCEEDED,
288 level=SecurityEventLevel.WARNING,
289 message=f"Max concurrent operations exceeded: {len(self._active_operations)}",
290 client_id=client_id,
291 operation=operation_type,
292 )
293 raise OperationLimitExceededError(
294 f"Maximum concurrent operations exceeded: {len(self._active_operations)}"
295 )
297 # Check client rate limiting
298 client_ops = self._client_operations[client_id]
300 # Remove operations older than 1 minute
301 while client_ops and current_time - client_ops[0] > 60.0:
302 client_ops.popleft()
304 if len(client_ops) >= self.limits.max_operations_per_minute:
305 self.security_logger.log_security_event(
306 event_type=SecurityEventType.RATE_LIMIT_EXCEEDED,
307 level=SecurityEventLevel.WARNING,
308 message=f"Client operation rate limit exceeded: {len(client_ops)}",
309 client_id=client_id,
310 operation=operation_type,
311 )
312 raise OperationLimitExceededError(
313 f"Operation rate limit exceeded: {len(client_ops)} operations/min"
314 )
316 # Check resource usage limits
317 if (
318 self._total_memory_usage
319 >= self.limits.max_memory_usage_mb * 1024 * 1024
320 ):
321 self.security_logger.log_security_event(
322 event_type=SecurityEventType.RESOURCE_EXHAUSTED,
323 level=SecurityEventLevel.ERROR,
324 message=f"Memory limit exceeded: {self._total_memory_usage / 1024 / 1024:.1f}MB",
325 client_id=client_id,
326 operation=operation_type,
327 )
328 raise OperationLimitExceededError(
329 f"Memory limit exceeded: {self._total_memory_usage / 1024 / 1024:.1f}MB"
330 )
332 # Record operation start
333 client_ops.append(current_time)
335 return operation_id
337 async def _execute_with_monitoring(
338 self,
339 operation_func: t.Callable[..., t.Awaitable[t.Any]],
340 metrics: OperationMetrics,
341 *args,
342 **kwargs,
343 ) -> t.Any:
344 """Execute operation with resource monitoring and timeout."""
346 # Create monitoring task
347 monitor_task = asyncio.create_task(self._monitor_operation(metrics))
349 try:
350 # Execute operation with timeout
351 result = await asyncio.wait_for(
352 operation_func(*args, **kwargs),
353 timeout=self.limits.timeout_seconds,
354 )
356 return result
358 except TimeoutError:
359 self.security_logger.log_security_event(
360 event_type=SecurityEventType.OPERATION_TIMEOUT,
361 level=SecurityEventLevel.ERROR,
362 message=f"Operation timeout: {metrics.operation_type}",
363 client_id=metrics.client_id,
364 operation=metrics.operation_type,
365 additional_data={
366 "operation_id": metrics.operation_id,
367 "timeout": self.limits.timeout_seconds,
368 },
369 )
370 raise TimeoutError(
371 f"Operation timed out after {self.limits.timeout_seconds}s"
372 )
374 finally:
375 # Cancel monitoring
376 monitor_task.cancel()
377 try:
378 await monitor_task
379 except asyncio.CancelledError:
380 pass
382 async def _monitor_operation(self, metrics: OperationMetrics) -> None:
383 """Monitor operation resource usage."""
385 import os
387 import psutil
389 try:
390 process = psutil.Process(os.getpid())
391 initial_cpu_time = process.cpu_times().user + process.cpu_times().system
393 while not metrics.is_completed:
394 try:
395 # Update CPU time
396 current_cpu_time = (
397 process.cpu_times().user + process.cpu_times().system
398 )
399 metrics.cpu_time = current_cpu_time - initial_cpu_time
401 # Update memory usage
402 metrics.memory_usage = process.memory_info().rss
404 # Check limits
405 if metrics.cpu_time > self.limits.max_cpu_time_seconds:
406 self.security_logger.log_security_event(
407 event_type=SecurityEventType.RESOURCE_LIMIT_EXCEEDED,
408 level=SecurityEventLevel.WARNING,
409 message=f"CPU time limit exceeded: {metrics.cpu_time:.2f}s",
410 client_id=metrics.client_id,
411 operation=metrics.operation_type,
412 additional_data={"operation_id": metrics.operation_id},
413 )
414 break
416 if metrics.duration > self.limits.max_operation_duration:
417 self.security_logger.log_security_event(
418 event_type=SecurityEventType.OPERATION_DURATION_EXCEEDED,
419 level=SecurityEventLevel.WARNING,
420 message=f"Operation duration limit exceeded: {metrics.duration:.2f}s",
421 client_id=metrics.client_id,
422 operation=metrics.operation_type,
423 additional_data={"operation_id": metrics.operation_id},
424 )
425 break
427 await asyncio.sleep(0.1) # Monitor every 100ms
429 except psutil.NoSuchProcess:
430 break
432 except Exception as e:
433 # Monitoring failure shouldn't stop the operation
434 self.security_logger.log_security_event(
435 event_type=SecurityEventType.MONITORING_ERROR,
436 level=SecurityEventLevel.WARNING,
437 message=f"Operation monitoring failed: {e}",
438 client_id=metrics.client_id,
439 operation=metrics.operation_type,
440 )
442 def _record_operation_success(self, operation_type: str) -> None:
443 """Record successful operation for circuit breaker."""
445 with self._lock:
446 state = self._circuit_states[operation_type]
448 if state == OperationState.HALF_OPEN:
449 # Success in half-open state - close circuit breaker
450 self._circuit_states[operation_type] = OperationState.CLOSED
451 self._failure_counts[operation_type] = 0
453 self.security_logger.log_security_event(
454 event_type=SecurityEventType.CIRCUIT_BREAKER_CLOSED,
455 level=SecurityEventLevel.INFO,
456 message=f"Circuit breaker closed: {operation_type}",
457 operation=operation_type,
458 )
459 elif state == OperationState.CLOSED:
460 # Reset failure count on success
461 self._failure_counts[operation_type] = 0
463 def _record_operation_failure(self, operation_type: str) -> None:
464 """Record failed operation for circuit breaker."""
466 current_time = time.time()
468 with self._lock:
469 self._failure_counts[operation_type] += 1
470 self._last_failure_times[operation_type] = current_time
472 state = self._circuit_states[operation_type]
473 failure_count = self._failure_counts[operation_type]
475 if failure_count >= self.limits.circuit_breaker_threshold:
476 if state != OperationState.OPEN:
477 # Trip circuit breaker
478 self._circuit_states[operation_type] = OperationState.OPEN
480 self.security_logger.log_security_event(
481 event_type=SecurityEventType.CIRCUIT_BREAKER_OPEN,
482 level=SecurityEventLevel.ERROR,
483 message=f"Circuit breaker opened: {operation_type}",
484 operation=operation_type,
485 additional_data={
486 "failure_count": failure_count,
487 "threshold": self.limits.circuit_breaker_threshold,
488 },
489 )
491 def _cleanup_operation(self, operation_id: str, metrics: OperationMetrics) -> None:
492 """Clean up operation and update metrics."""
494 with self._lock:
495 # Remove from active operations
496 if operation_id in self._active_operations:
497 del self._active_operations[operation_id]
499 # Add to history (keep last 1000 operations)
500 self._operation_history.append(metrics)
501 if len(self._operation_history) > 1000:
502 self._operation_history.pop(0)
504 # Update resource usage tracking
505 self._total_memory_usage = max(
506 0, self._total_memory_usage - metrics.memory_usage
507 )
508 self._total_cpu_time += metrics.cpu_time
509 self._total_file_operations += metrics.file_operations
511 def get_operation_status(self) -> dict[str, t.Any]:
512 """Get current operation status and limits."""
514 with self._lock:
515 current_time = time.time()
517 # Calculate recent operation stats
518 recent_ops = [
519 m
520 for m in self._operation_history
521 if current_time - m.start_time < 300 # Last 5 minutes
522 ]
524 successful_ops = [m for m in recent_ops if m.success is True]
525 failed_ops = [m for m in recent_ops if m.success is False]
527 return {
528 "active_operations": len(self._active_operations),
529 "max_concurrent": self.limits.max_concurrent_operations,
530 "recent_operations": {
531 "total": len(recent_ops),
532 "successful": len(successful_ops),
533 "failed": len(failed_ops),
534 "success_rate": len(successful_ops) / len(recent_ops)
535 if recent_ops
536 else 1.0,
537 },
538 "circuit_breakers": {
539 op_type: {
540 "state": state.value,
541 "failure_count": self._failure_counts.get(op_type, 0),
542 "last_failure": self._last_failure_times.get(op_type),
543 }
544 for op_type, state in self._circuit_states.items()
545 },
546 "resource_usage": {
547 "memory_usage_mb": self._total_memory_usage / 1024 / 1024,
548 "memory_limit_mb": self.limits.max_memory_usage_mb,
549 "total_cpu_time": self._total_cpu_time,
550 "total_file_operations": self._total_file_operations,
551 },
552 "limits": {
553 "max_concurrent_operations": self.limits.max_concurrent_operations,
554 "max_operations_per_minute": self.limits.max_operations_per_minute,
555 "max_operation_duration": self.limits.max_operation_duration,
556 "timeout_seconds": self.limits.timeout_seconds,
557 },
558 }
560 def reset_circuit_breaker(self, operation_type: str) -> bool:
561 """
562 Manually reset a circuit breaker.
564 Args:
565 operation_type: Type of operation
567 Returns:
568 True if circuit breaker was reset
569 """
571 with self._lock:
572 if operation_type in self._circuit_states:
573 self._circuit_states[operation_type] = OperationState.CLOSED
574 self._failure_counts[operation_type] = 0
576 self.security_logger.log_security_event(
577 event_type=SecurityEventType.CIRCUIT_BREAKER_RESET,
578 level=SecurityEventLevel.INFO,
579 message=f"Circuit breaker manually reset: {operation_type}",
580 operation=operation_type,
581 )
583 return True
585 return False
588# Global singleton instance
589_bounded_operations: BoundedStatusOperations | None = None
592def get_bounded_status_operations(
593 limits: OperationLimits | None = None,
594) -> BoundedStatusOperations:
595 """Get the global bounded status operations instance."""
597 global _bounded_operations
598 if _bounded_operations is None:
599 _bounded_operations = BoundedStatusOperations(limits)
600 return _bounded_operations
603async def execute_bounded_status_operation(
604 operation_type: str,
605 client_id: str,
606 operation_func: t.Callable[..., t.Awaitable[t.Any]],
607 *args,
608 **kwargs,
609) -> t.Any:
610 """
611 Convenience function for bounded operation execution.
613 Args:
614 operation_type: Type of operation
615 client_id: Client identifier
616 operation_func: Async function to execute
617 *args: Positional arguments
618 **kwargs: Keyword arguments
620 Returns:
621 Operation result
622 """
624 operations_manager = get_bounded_status_operations()
625 return await operations_manager.execute_bounded_operation(
626 operation_type, client_id, operation_func, *args, **kwargs
627 )