""" Healthcare Service Patterns Enhanced base class for healthcare services with tenant validation, audit logging, and observability """ import asyncio import time from datetime import UTC, datetime, timezone from functools import wraps from typing import Any, Dict, Optional import structlog logger = structlog.get_logger(__name__) class AsyncHealthcareService: """ Enhanced base class for healthcare services Features: - Multi-tenancy support with tenant_id validation - Automatic audit logging for HIPAA compliance - Performance monitoring for SLA compliance - Standardized error handling - Observability hooks for metrics/tracing """ def __init__( self, db_session: Any | None = None, tenant_id: str | None = None, user_id: str | None = None, ): """ Initialize healthcare service Args: db_session: Database session for queries tenant_id: Multi-tenant isolation identifier user_id: User performing operations (for audit trail) """ self.db_session = db_session self.tenant_id = tenant_id self.user_id = user_id self.logger = logger self._audit_logs = [] # type: ignore[name-defined, index, return-value, var-annotated] self._performance_metrics = [] # type: ignore[name-defined, index, return-value, var-annotated] def health_check(self) -> dict: """ Basic health check for service Returns: Dict with service health status """ return { "status": "healthy", "service": self.__class__.__name__, "tenant_id": self.tenant_id, "timestamp": datetime.now(UTC).isoformat(), } def validate_tenant_id(self, tenant_id: str | None = None) -> bool: """ Validate tenant ID is set and matches (multi-tenancy isolation) Args: tenant_id: Tenant ID to validate (uses self.tenant_id if not provided) Returns: True if valid Raises: ValueError: If tenant_id not set or doesn't match """ check_tenant = tenant_id or self.tenant_id if not check_tenant: raise ValueError("tenant_id is required for multi-tenant operations") if self.tenant_id and tenant_id and self.tenant_id != tenant_id: raise ValueError( f"Tenant mismatch: service tenant={self.tenant_id}, request tenant={tenant_id}" ) return True async def audit_log( self, action: str, resource_type: str, resource_id: str | None = None, details: dict[str, Any] | None = None, result: str = "success", ) -> None: """ Log action for HIPAA audit trail Clinical Context: All PHI access must be logged Standards Compliance: HIPAA audit logging requirements Args: action: Action performed (e.g., "patient_record_viewed") resource_type: Type of resource (e.g., "patient", "prescription") resource_id: Identifier of resource accessed details: Additional details (no PHI in logs) result: Operation result ("success", "failure", "denied") Performance: <5ms (async, non-blocking) """ audit_entry = { "timestamp": datetime.now(UTC).isoformat(), "tenant_id": self.tenant_id, "user_id": self.user_id, "service": self.__class__.__name__, "action": action, "resource_type": resource_type, "resource_id": resource_id, "result": result, "details": details or {}, } self._audit_logs.append(audit_entry) # Log to structured logger (ELK/CloudWatch integration) self.logger.info(f"AUDIT: {action}", extra={"audit": True, **audit_entry}) def record_performance( self, operation: str, duration_ms: float, status: str = "success" ) -> None: """ Record operation performance metrics Args: operation: Operation name duration_ms: Duration in milliseconds status: Operation status """ metric = { "timestamp": datetime.now(UTC).isoformat(), "operation": operation, "duration_ms": duration_ms, "status": status, "service": self.__class__.__name__, "tenant_id": self.tenant_id, "sla_compliant": duration_ms < 200, # P95 target } self._performance_metrics.append(metric) # Warn if SLA breached if duration_ms >= 200: self.logger.warning( f"Performance SLA breach: {operation} took {duration_ms}ms (target <200ms)", extra=metric, ) def get_audit_logs(self) -> list: """Get audit logs for this service instance""" return self._audit_logs.copy() def get_performance_metrics(self) -> list: """Get performance metrics for this service instance""" return self._performance_metrics.copy() def healthcare_operation(operation_name: str, require_tenant: bool = True): """ Decorator for healthcare operations with enhanced logging and monitoring Args: operation_name: Name of operation (for logging/metrics) require_tenant: Whether tenant_id is required (default True) Features: - Automatic tenant validation - Performance monitoring - Error logging - Audit trail entry """ def decorator(func): @wraps(func) async def wrapper(self, *args, **kwargs): start_time = time.time() # Validate tenant if required if require_tenant and hasattr(self, "validate_tenant_id"): try: self.validate_tenant_id() except ValueError as e: logger.error(f"Tenant validation failed for {operation_name}: {e}") raise logger.info( f"Healthcare operation started: {operation_name}", extra={ "operation": operation_name, "tenant_id": getattr(self, "tenant_id", None), "user_id": getattr(self, "user_id", None), }, ) try: # Execute operation result = await func(self, *args, **kwargs) # Record success metrics duration_ms = (time.time() - start_time) * 1000 if hasattr(self, "record_performance"): self.record_performance(operation_name, duration_ms, "success") logger.info( f"Healthcare operation completed: {operation_name} ({duration_ms:.2f}ms)", extra={ "operation": operation_name, "duration_ms": duration_ms, "status": "success", }, ) return result except Exception as e: # Record failure metrics duration_ms = (time.time() - start_time) * 1000 if hasattr(self, "record_performance"): self.record_performance(operation_name, duration_ms, "failure") logger.error( f"Healthcare operation failed: {operation_name}: {str(e)}", extra={ "operation": operation_name, "duration_ms": duration_ms, "error": str(e), "error_type": type(e).__name__, }, exc_info=True, ) raise return wrapper return decorator