Spaces:
Paused

File size: 15,994 Bytes
357bfdf
 
 
 
 
 
 
46a26b0
 
 
 
 
 
357bfdf
 
 
 
 
 
 
 
 
 
 
 
 
383d839
357bfdf
 
 
 
 
 
46a26b0
 
357bfdf
 
 
 
 
383d839
357bfdf
 
383d839
 
 
 
 
357bfdf
383d839
357bfdf
383d839
 
 
 
 
 
357bfdf
 
 
 
 
 
383d839
357bfdf
383d839
357bfdf
 
383d839
 
 
 
 
 
 
357bfdf
 
383d839
357bfdf
 
383d839
357bfdf
 
383d839
357bfdf
 
 
 
 
 
383d839
357bfdf
383d839
357bfdf
 
 
383d839
357bfdf
 
 
 
 
 
 
 
383d839
357bfdf
 
 
 
383d839
357bfdf
 
 
383d839
 
 
 
 
 
 
 
 
 
357bfdf
 
 
 
383d839
357bfdf
383d839
357bfdf
 
 
 
 
383d839
357bfdf
 
 
 
 
 
 
383d839
357bfdf
 
 
 
579285c
 
 
 
357bfdf
 
 
 
 
383d839
357bfdf
 
383d839
 
 
 
 
 
357bfdf
383d839
357bfdf
 
383d839
 
 
 
 
 
357bfdf
 
 
 
 
 
383d839
357bfdf
 
 
383d839
357bfdf
 
383d839
357bfdf
 
383d839
357bfdf
383d839
357bfdf
 
 
 
 
 
383d839
357bfdf
383d839
357bfdf
 
383d839
357bfdf
383d839
 
357bfdf
c85f9e9
383d839
357bfdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
383d839
357bfdf
 
 
c85f9e9
 
357bfdf
c85f9e9
579285c
383d839
357bfdf
 
 
 
383d839
357bfdf
383d839
357bfdf
 
 
 
 
383d839
357bfdf
383d839
357bfdf
383d839
c85f9e9
 
 
 
 
383d839
c85f9e9
383d839
357bfdf
 
c85f9e9
357bfdf
 
 
 
 
 
383d839
357bfdf
383d839
357bfdf
 
 
 
 
 
 
383d839
357bfdf
 
 
 
383d839
357bfdf
 
383d839
357bfdf
 
383d839
357bfdf
 
383d839
357bfdf
 
 
383d839
357bfdf
 
 
 
 
 
 
 
383d839
357bfdf
 
383d839
357bfdf
 
 
383d839
357bfdf
 
 
 
 
 
 
383d839
357bfdf
 
383d839
357bfdf
 
46a26b0
357bfdf
 
 
 
383d839
357bfdf
 
 
 
 
383d839
357bfdf
383d839
357bfdf
 
 
 
 
 
 
 
383d839
357bfdf
 
 
 
 
46a26b0
357bfdf
 
 
 
383d839
357bfdf
579285c
 
 
357bfdf
 
579285c
357bfdf
 
 
 
 
 
5b36da5
357bfdf
 
 
 
383d839
357bfdf
 
5b36da5
357bfdf
 
 
383d839
357bfdf
 
 
 
 
 
383d839
357bfdf
 
 
383d839
357bfdf
 
 
 
 
 
 
 
 
 
 
 
 
 
383d839
357bfdf
383d839
357bfdf
579285c
383d839
357bfdf
579285c
357bfdf
 
383d839
357bfdf
383d839
357bfdf
579285c
357bfdf
 
 
383d839
357bfdf
383d839
357bfdf
579285c
357bfdf
 
 
383d839
 
 
 
 
 
 
357bfdf
383d839
 
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
"""
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