""" YAZ Care Platform - Performance Optimization Middleware FastAPI middleware for compression, caching, and performance optimization """ import gzip import json import time from typing import Any, Callable, Dict, Optional import brotli import structlog from core.services.cache import HealthcareCacheNamespaces, cache_manager from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests import Request from starlette.responses import Response, StreamingResponse from starlette.types import ASGIApp logger = structlog.get_logger(__name__) class CompressionMiddleware(BaseHTTPMiddleware): """ Advanced compression middleware supporting Brotli and gzip with healthcare-specific optimizations """ def __init__( self, app: ASGIApp, minimum_size: int = 500, brotli_quality: int = 4, gzip_quality: int = 6, exclude_paths: set | None = None, exclude_media_types: set | None = None, ): super().__init__(app) self.minimum_size = minimum_size self.brotli_quality = brotli_quality self.gzip_quality = gzip_quality # Default exclusions for healthcare data self.exclude_paths = exclude_paths or { "/health", "/metrics", "/api/stream", "/emergency", "/realtime", # Emergency endpoints should be fast } self.exclude_media_types = exclude_media_types or { "image/", "video/", "audio/", "application/octet-stream", "application/pdf", "application/zip", } async def dispatch(self, request: Request, call_next: Callable) -> Response: # Skip compression for excluded paths if any(request.url.path.startswith(path) for path in self.exclude_paths): return await call_next(request) response = await call_next(request) # Skip compression for certain conditions if ( response.status_code < 200 or response.status_code >= 300 or "content-encoding" in response.headers or any( response.headers.get("content-type", "").startswith(media_type) for media_type in self.exclude_media_types ) ): return response # Get accept-encoding header accept_encoding = request.headers.get("accept-encoding", "").lower() # Get response content response_body = b"".join([chunk async for chunk in response.body_iterator]) # Skip small responses if len(response_body) < self.minimum_size: return Response( content=response_body, status_code=response.status_code, headers=response.headers, media_type=response.media_type, ) # Choose compression method compressed_body = None encoding = None if "br" in accept_encoding: # Brotli compression (best) compressed_body = brotli.compress(response_body, quality=self.brotli_quality) encoding = "br" elif "gzip" in accept_encoding: # Gzip compression (fallback) compressed_body = gzip.compress(response_body, compresslevel=self.gzip_quality) encoding = "gzip" if compressed_body and len(compressed_body) < len(response_body): # Compression successful response.headers["content-encoding"] = encoding response.headers["content-length"] = str(len(compressed_body)) # Add compression ratio for monitoring ratio = len(compressed_body) / len(response_body) response.headers["x-compression-ratio"] = f"{ratio:.3f}" logger.debug( "Response compressed", path=request.url.path, method=encoding, original_size=len(response_body), compressed_size=len(compressed_body), ratio=ratio, ) return Response( content=compressed_body, status_code=response.status_code, headers=response.headers, media_type=response.media_type, ) # Return uncompressed if compression didn't help return Response( content=response_body, status_code=response.status_code, headers=response.headers, media_type=response.media_type, ) class ResponseCacheMiddleware(BaseHTTPMiddleware): """ Response caching middleware with healthcare-safe caching """ def __init__( self, app: ASGIApp, default_ttl: int = 300, cache_methods: set = None, # type: ignore[arg-type, assignment] cacheable_status_codes: set = None, # type: ignore[arg-type, assignment] exclude_paths: set = None, # type: ignore[arg-type, assignment] phi_safe_paths: set = None, # type: ignore[arg-type, assignment] ): super().__init__(app) self.default_ttl = default_ttl self.cache_methods = cache_methods or {"GET", "HEAD"} self.cacheable_status_codes = cacheable_status_codes or {200} # Paths that should never be cached (contain PHI) self.exclude_paths = exclude_paths or { "/api/patients/", "/api/phi/", "/api/medical-records/", "/auth/", "/admin/", "/emergency/", } # Paths that are safe to cache (no PHI) self.phi_safe_paths = phi_safe_paths or { "/api/config/", "/api/public/", "/api/analytics/summary/", "/static/", "/health", "/metrics", } async def dispatch(self, request: Request, call_next: Callable) -> Response: # Only cache certain HTTP methods if request.method not in self.cache_methods: return await call_next(request) # Check if path should be excluded from caching if self._should_exclude_from_cache(request.url.path): return await call_next(request) # Generate cache key cache_key = self._generate_cache_key(request) # Try to get from cache first cached_response = await cache_manager.get( cache_key, namespace=HealthcareCacheNamespaces.ANALYTICS ) if cached_response: logger.debug("Response cache hit", path=request.url.path) return Response( content=cached_response["content"], status_code=cached_response["status_code"], headers=cached_response["headers"], media_type=cached_response["media_type"], ) # Execute request response = await call_next(request) # Cache response if appropriate if response.status_code in self.cacheable_status_codes and self._is_phi_safe_path( request.url.path ): response = await self._cache_response(cache_key, response) return response def _should_exclude_from_cache(self, path: str) -> bool: """Check if path should be excluded from caching""" return any(excluded in path for excluded in self.exclude_paths) def _is_phi_safe_path(self, path: str) -> bool: """Check if path is safe to cache (no PHI)""" return any(safe_path in path for safe_path in self.phi_safe_paths) def _generate_cache_key(self, request: Request) -> str: """Generate cache key for request""" key_parts = [ request.method, str(request.url), request.headers.get("accept", ""), request.headers.get("accept-language", ""), ] return "_".join(key_parts) async def _cache_response(self, cache_key: str, response: Response) -> Response: """Cache response data and return a new response with the body intact""" try: # Get response content — this consumes the body iterator response_body = b"".join([chunk async for chunk in response.body_iterator]) # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr] cache_data = { "content": response_body, "status_code": response.status_code, "headers": dict(response.headers), "media_type": response.media_type, } await cache_manager.set( cache_key, cache_data, ttl=self.default_ttl, namespace=HealthcareCacheNamespaces.ANALYTICS, healthcare_context={"safe": True, "type": "response_cache"}, ) logger.debug("Response cached", key=cache_key) # Return new response with body content restored return Response( content=response_body, status_code=response.status_code, headers=dict(response.headers), media_type=response.media_type, ) except Exception as e: logger.warning("Failed to cache response", error=str(e)) return response class PerformanceMonitoringMiddleware(BaseHTTPMiddleware): """ Performance monitoring middleware for healthcare APIs """ def __init__( self, app: ASGIApp, slow_request_threshold: float = 1.0, track_memory: bool = False ): super().__init__(app) self.slow_request_threshold = slow_request_threshold self.track_memory = track_memory async def dispatch(self, request: Request, call_next: Callable) -> Response: start_time = time.time() # Track memory usage if enabled memory_before = None if self.track_memory: import psutil process = psutil.Process() memory_before = process.memory_info().rss / 1024 / 1024 # MB # Process request response = await call_next(request) # Calculate metrics duration = time.time() - start_time # Add performance headers response.headers["x-response-time"] = f"{duration:.3f}s" response.headers["x-timestamp"] = str(int(time.time())) # Log performance metrics log_data = { "method": request.method, "path": request.url.path, "duration": duration, "status_code": response.status_code, "user_agent": request.headers.get("user-agent", ""), } if self.track_memory and memory_before: import psutil process = psutil.Process() memory_after = process.memory_info().rss / 1024 / 1024 # MB log_data["memory_delta"] = memory_after - memory_before # Determine log level based on performance if duration > self.slow_request_threshold: logger.warning("Slow request detected", **log_data) elif response.status_code >= 400: logger.warning("Request error", **log_data) else: logger.debug("Request completed", **log_data) # Store performance metrics for analytics await self._store_performance_metric(log_data) return response async def _store_performance_metric(self, metric_data: dict[str, Any]): """Store performance metrics for analysis""" try: # Store in cache for real-time monitoring metric_key = f"perf_{int(time.time())}_{metric_data['path'].replace('/', '_')}" await cache_manager.set( metric_key, metric_data, ttl=3600, # 1 hour namespace="performance_metrics", healthcare_context={"safe": True, "type": "performance"}, ) except Exception as e: logger.warning("Failed to store performance metric", error=str(e)) class SecurityHeadersMiddleware(BaseHTTPMiddleware): """ Security headers middleware for healthcare compliance """ def __init__( self, app: ASGIApp, hsts_max_age: int = 31536000, # 1 year include_subdomains: bool = True, content_security_policy: str | None = None, ): super().__init__(app) self.hsts_max_age = hsts_max_age self.include_subdomains = include_subdomains # Default CSP for healthcare applications # OWASP A03:2021 — unsafe-eval REMOVED (S1). unsafe-inline retained in # style-src until M6 (inline style audit) completes; in script-src until # M7 (DOMPurify htmx:beforeSwap) completes. self.csp = content_security_policy or ( "default-src 'self'; " "script-src 'self' 'unsafe-inline'; " "style-src 'self' 'unsafe-inline'; " "img-src 'self' data: https:; " "font-src 'self' data:; " "connect-src 'self'; " "media-src 'self'; " "object-src 'none'; " "frame-ancestors 'self' https://*.hf.space https://huggingface.co;" ) async def dispatch(self, request: Request, call_next: Callable) -> Response: response = await call_next(request) # Add security headers response.headers["x-content-type-options"] = "nosniff" response.headers["x-frame-options"] = "SAMEORIGIN" response.headers["x-xss-protection"] = "1; mode=block" response.headers["referrer-policy"] = "strict-origin-when-cross-origin" response.headers["content-security-policy"] = self.csp # Add HSTS for HTTPS if request.url.scheme == "https": hsts_value = f"max-age={self.hsts_max_age}" if self.include_subdomains: hsts_value += "; includeSubDomains" response.headers["strict-transport-security"] = hsts_value # Healthcare-specific headers response.headers["x-healthcare-compliant"] = "HIPAA" response.headers["x-phi-safe"] = "true" if self._is_phi_safe_response(response) else "false" return response def _is_phi_safe_response(self, response: Response) -> bool: """Check if response is PHI-safe""" # Simple check - in production, this would be more sophisticated content_type = response.headers.get("content-type", "") return "application/json" in content_type or "text/html" in content_type # Middleware factory function def create_optimization_middlewares(app: ASGIApp) -> ASGIApp: """ Create and configure all optimization middlewares """ # Add middlewares in reverse order (last added = first executed) # Security headers (outermost) app.add_middleware(SecurityHeadersMiddleware) # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr] # Performance monitoring app.add_middleware( # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr] PerformanceMonitoringMiddleware, slow_request_threshold=2.0, # 2 seconds for healthcare apps track_memory=True, ) # Response compression app.add_middleware( # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr] CompressionMiddleware, minimum_size=500, brotli_quality=4, # Balance between compression and speed exclude_paths={"/emergency", "/realtime", "/stream"}, ) # Response caching app.add_middleware( # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr] ResponseCacheMiddleware, default_ttl=300, # 5 minutes exclude_paths={ "/api/patients/", "/api/phi/", "/api/medical-records/", "/auth/", "/admin/", "/emergency/", }, ) return app