Download src/middleware/response_optimization.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 15.4 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/middleware/response_optimization.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/middleware/response_optimization.py
-
curl -L -o response_optimization.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/middleware/response_optimization.py
15.4 kB
| """ | |
| YAZ Care Platform - API Response Optimization Middleware | |
| Sprint 30 Task 30.5 - Optimize API response delivery | |
| Features: | |
| - GZIP compression with dynamic threshold | |
| - ETag caching for unchanged responses | |
| - Field filtering support (?fields=) | |
| - Streaming for large responses | |
| - Automatic response optimization | |
| """ | |
| import gzip | |
| import hashlib | |
| import json | |
| from datetime import datetime, timedelta | |
| from typing import Any, Dict, List, Optional, Set | |
| import structlog | |
| from fastapi import Request, Response | |
| from fastapi.responses import JSONResponse, StreamingResponse | |
| from prometheus_client import Counter, Gauge, Histogram | |
| from starlette.datastructures import Headers | |
| from starlette.middleware.base import BaseHTTPMiddleware | |
| logger = structlog.get_logger(__name__) | |
| # ============================================================================= | |
| # PROMETHEUS METRICS | |
| # ============================================================================= | |
| response_compression_ratio = Gauge( | |
| "http_response_compression_ratio", "Compression ratio for HTTP responses", ["endpoint"] | |
| ) | |
| response_size_bytes = Histogram( | |
| "http_response_size_bytes", | |
| "Size of HTTP responses in bytes", | |
| ["endpoint", "compressed"], | |
| buckets=[100, 1000, 10000, 100000, 1000000, 10000000], | |
| ) | |
| etag_hits = Counter("http_etag_hits_total", "Number of ETag cache hits", ["endpoint"]) | |
| etag_misses = Counter("http_etag_misses_total", "Number of ETag cache misses", ["endpoint"]) | |
| field_filtering_operations = Counter( | |
| "http_field_filtering_total", "Number of field filtering operations", ["endpoint"] | |
| ) | |
| # ============================================================================= | |
| # RESPONSE COMPRESSION MIDDLEWARE | |
| # ============================================================================= | |
| class CompressionMiddleware(BaseHTTPMiddleware): | |
| """ | |
| Intelligent GZIP compression middleware | |
| Features: | |
| - Dynamic compression threshold | |
| - Content-type filtering | |
| - Already-compressed detection | |
| - Compression ratio tracking | |
| """ | |
| def __init__( | |
| self, | |
| app, | |
| minimum_size: int = 1000, # 1KB minimum | |
| compression_level: int = 6, # Balance speed/ratio | |
| exclude_media_types: set[str] | None = None, | |
| ): | |
| super().__init__(app) | |
| self.minimum_size = minimum_size | |
| self.compression_level = compression_level | |
| self.exclude_media_types = exclude_media_types or { | |
| "image/jpeg", | |
| "image/png", | |
| "image/gif", | |
| "image/webp", | |
| "image/x-icon", | |
| "image/vnd.microsoft.icon", | |
| "video/mp4", | |
| "application/zip", | |
| "application/gzip", | |
| } | |
| async def dispatch(self, request: Request, call_next): | |
| """Apply compression to response if applicable""" | |
| response = await call_next(request) | |
| # Skip if client doesn't accept gzip | |
| if "gzip" not in request.headers.get("accept-encoding", ""): | |
| return response | |
| # Skip if already compressed | |
| if response.headers.get("content-encoding"): | |
| return response | |
| # Skip excluded media types | |
| content_type = response.headers.get("content-type", "") | |
| if any(excluded in content_type for excluded in self.exclude_media_types): | |
| return response | |
| # Get response body | |
| body = b"" | |
| async for chunk in response.body_iterator: | |
| body += chunk | |
| original_size = len(body) | |
| # Skip if too small | |
| if original_size < self.minimum_size: | |
| return Response( | |
| content=body, | |
| status_code=response.status_code, | |
| headers=dict(response.headers), | |
| media_type=response.media_type, | |
| ) | |
| # Compress | |
| compressed_body = gzip.compress(body, compresslevel=self.compression_level) | |
| compressed_size = len(compressed_body) | |
| compression_ratio = original_size / compressed_size if compressed_size > 0 else 1.0 | |
| # Track metrics | |
| endpoint = request.url.path | |
| response_compression_ratio.labels(endpoint=endpoint).set(compression_ratio) | |
| response_size_bytes.labels(endpoint=endpoint, compressed="yes").observe(compressed_size) | |
| logger.debug( | |
| f"Compressed {endpoint}: {original_size} → {compressed_size} bytes " | |
| f"({compression_ratio:.2f}x)" | |
| ) | |
| # Return compressed response | |
| return Response( | |
| content=compressed_body, | |
| status_code=response.status_code, | |
| headers={ | |
| **dict(response.headers), | |
| "content-encoding": "gzip", | |
| "content-length": str(compressed_size), | |
| "vary": "Accept-Encoding", | |
| }, | |
| media_type=response.media_type, | |
| ) | |
| # ============================================================================= | |
| # ETAG CACHING MIDDLEWARE | |
| # ============================================================================= | |
| class ETagMiddleware(BaseHTTPMiddleware): | |
| """ | |
| ETag-based HTTP caching | |
| Features: | |
| - Automatic ETag generation | |
| - If-None-Match header support | |
| - Cache-Control headers | |
| - 304 Not Modified responses | |
| """ | |
| def __init__( | |
| self, | |
| app, | |
| max_age: int = 300, | |
| exclude_paths: set[str] | None = None, # 5 minutes default | |
| ): | |
| super().__init__(app) | |
| self.max_age = max_age | |
| self.exclude_paths = exclude_paths or {"/health", "/metrics", "/docs", "/openapi.json"} | |
| async def dispatch(self, request: Request, call_next): | |
| """Add ETag support to responses""" | |
| # Skip excluded paths | |
| if any(request.url.path.startswith(path) for path in self.exclude_paths): | |
| return await call_next(request) | |
| # Skip non-GET requests | |
| if request.method != "GET": | |
| return await call_next(request) | |
| # Get response | |
| response = await call_next(request) | |
| # Get response body | |
| body = b"" | |
| async for chunk in response.body_iterator: | |
| body += chunk | |
| # Generate ETag | |
| etag = f'W/"{hashlib.md5(body).hexdigest()}"' | |
| # Check If-None-Match header | |
| if_none_match = request.headers.get("if-none-match") | |
| endpoint = request.url.path | |
| if if_none_match == etag: | |
| # ETag match - return 304 Not Modified | |
| etag_hits.labels(endpoint=endpoint).inc() | |
| logger.debug(f"ETag HIT for {endpoint}: {etag}") | |
| return Response( | |
| status_code=304, headers={"etag": etag, "cache-control": f"max-age={self.max_age}"} | |
| ) | |
| # ETag miss - return full response with ETag | |
| etag_misses.labels(endpoint=endpoint).inc() | |
| return Response( | |
| content=body, | |
| status_code=response.status_code, | |
| headers={ | |
| **dict(response.headers), | |
| "etag": etag, | |
| "cache-control": f"max-age={self.max_age}", | |
| "vary": "Accept-Encoding", | |
| }, | |
| media_type=response.media_type, | |
| ) | |
| # ============================================================================= | |
| # FIELD FILTERING SUPPORT | |
| # ============================================================================= | |
| def filter_fields(data: Any, fields: list[str] | None = None) -> Any: | |
| """ | |
| Filter response data to only include specified fields | |
| Args: | |
| data: Response data (dict, list, or primitive) | |
| fields: List of field names to include (e.g., ['id', 'name', 'email']) | |
| Returns: | |
| Filtered data with only requested fields | |
| Examples: | |
| >>> data = {"id": 1, "name": "John", "email": "john@example.com", "password": "secret"} | |
| >>> filter_fields(data, ["id", "name"]) | |
| {"id": 1, "name": "John"} | |
| >>> data = [{"id": 1, "name": "John"}, {"id": 2, "name": "Jane"}] | |
| >>> filter_fields(data, ["id"]) | |
| [{"id": 1}, {"id": 2}] | |
| """ | |
| if not fields: | |
| return data | |
| if isinstance(data, dict): | |
| return {k: v for k, v in data.items() if k in fields} | |
| elif isinstance(data, list): | |
| return [filter_fields(item, fields) for item in data] | |
| else: | |
| return data | |
| def apply_field_filtering(request: Request, data: Any) -> Any: | |
| """ | |
| Apply field filtering based on query parameter | |
| Usage: | |
| GET /api/users?fields=id,name,email | |
| Args: | |
| request: FastAPI request object | |
| data: Response data | |
| Returns: | |
| Filtered data if ?fields parameter present | |
| """ | |
| fields_param = request.query_params.get("fields") | |
| if not fields_param: | |
| return data | |
| # Parse fields | |
| fields = [f.strip() for f in fields_param.split(",")] | |
| # Track metric | |
| endpoint = request.url.path | |
| field_filtering_operations.labels(endpoint=endpoint).inc() | |
| logger.debug(f"Field filtering for {endpoint}: {fields}") | |
| return filter_fields(data, fields) | |
| # ============================================================================= | |
| # STREAMING RESPONSE HELPERS | |
| # ============================================================================= | |
| async def stream_large_response(data: list[dict[str, Any]], chunk_size: int = 100): | |
| """ | |
| Stream large lists as chunked JSON | |
| Args: | |
| data: List of items to stream | |
| chunk_size: Number of items per chunk | |
| Yields: | |
| JSON chunks with proper formatting | |
| Example: | |
| @app.get("/api/patients") | |
| async def get_patients(): | |
| patients = db.query(Patient).all() | |
| return StreamingResponse( | |
| stream_large_response(patients), | |
| media_type="application/json" | |
| ) | |
| """ | |
| yield b"[" | |
| for i, item in enumerate(data): | |
| if i > 0: | |
| yield b"," | |
| yield json.dumps(item, default=str).encode() | |
| # Yield control every chunk_size items | |
| if i % chunk_size == 0: | |
| yield b"" | |
| yield b"]" | |
| async def stream_csv_response(data: list[dict[str, Any]], headers: list[str]): | |
| """ | |
| Stream data as CSV | |
| Args: | |
| data: List of dictionaries | |
| headers: CSV column headers | |
| Yields: | |
| CSV rows | |
| Example: | |
| @app.get("/api/exports/patients.csv") | |
| async def export_patients_csv(): | |
| patients = db.query(Patient).all() | |
| return StreamingResponse( | |
| stream_csv_response(patients, ['id', 'name', 'dob']), | |
| media_type="text/csv", | |
| headers={"Content-Disposition": "attachment; filename=patients.csv"} | |
| ) | |
| """ | |
| import csv | |
| import io | |
| # Yield header | |
| output = io.StringIO() | |
| writer = csv.DictWriter(output, fieldnames=headers) | |
| writer.writeheader() | |
| yield output.getvalue().encode() | |
| # Yield rows | |
| for item in data: | |
| output = io.StringIO() | |
| writer = csv.DictWriter(output, fieldnames=headers) | |
| writer.writerow(item) | |
| yield output.getvalue().encode() | |
| # ============================================================================= | |
| # CONDITIONAL RESPONSE HELPERS | |
| # ============================================================================= | |
| def create_conditional_response( | |
| content: Any, | |
| status_code: int = 200, | |
| headers: dict[str, str] | None = None, | |
| max_age: int = 300, | |
| stale_while_revalidate: int = 60, | |
| ) -> Response: | |
| """ | |
| Create response with optimal caching headers | |
| Args: | |
| content: Response content | |
| status_code: HTTP status code | |
| headers: Additional headers | |
| max_age: Cache max-age in seconds | |
| stale_while_revalidate: Stale-while-revalidate in seconds | |
| Returns: | |
| Response with cache headers | |
| Example: | |
| @app.get("/api/config") | |
| def get_config(): | |
| config = load_config() | |
| return create_conditional_response( | |
| config, | |
| max_age=3600, # Cache for 1 hour | |
| stale_while_revalidate=300 # Allow 5 min stale | |
| ) | |
| """ | |
| response_headers = headers or {} | |
| # Add caching headers | |
| response_headers.update( | |
| { | |
| "cache-control": f"max-age={max_age}, stale-while-revalidate={stale_while_revalidate}", | |
| "vary": "Accept-Encoding", | |
| } | |
| ) | |
| # Generate ETag | |
| if isinstance(content, (dict, list)): | |
| content_bytes = json.dumps(content, sort_keys=True, default=str).encode() | |
| elif isinstance(content, str): | |
| content_bytes = content.encode() | |
| elif isinstance(content, bytes): | |
| content_bytes = content | |
| else: | |
| content_bytes = str(content).encode() | |
| etag = f'W/"{hashlib.md5(content_bytes).hexdigest()}"' | |
| response_headers["etag"] = etag | |
| return JSONResponse(content=content, status_code=status_code, headers=response_headers) | |
| # ============================================================================= | |
| # USAGE EXAMPLES | |
| # ============================================================================= | |
| """ | |
| Example 1: Enable compression middleware | |
| ----------------------------------------- | |
| from fastapi import FastAPI | |
| from middleware.response_optimization import CompressionMiddleware | |
| app = FastAPI() | |
| app.add_middleware(CompressionMiddleware, minimum_size=1000, compression_level=6) | |
| Example 2: Enable ETag caching | |
| ------------------------------- | |
| from middleware.response_optimization import ETagMiddleware | |
| app.add_middleware(ETagMiddleware, max_age=300) | |
| Example 3: Field filtering in endpoint | |
| --------------------------------------- | |
| from fastapi import Request | |
| from middleware.response_optimization import apply_field_filtering | |
| @app.get("/api/users") | |
| def get_users(request: Request): | |
| users = db.query(User).all() | |
| users_data = [user.dict() for user in users] | |
| # Supports ?fields=id,name,email | |
| return apply_field_filtering(request, users_data) | |
| Example 4: Streaming large responses | |
| ------------------------------------- | |
| from fastapi.responses import StreamingResponse | |
| from middleware.response_optimization import stream_large_response | |
| @app.get("/api/patients") | |
| async def get_all_patients(): | |
| patients = db.query(Patient).limit(10000).all() | |
| patients_data = [p.dict() for p in patients] | |
| return StreamingResponse( | |
| stream_large_response(patients_data, chunk_size=100), | |
| media_type="application/json" | |
| ) | |
| Example 5: CSV export streaming | |
| -------------------------------- | |
| from middleware.response_optimization import stream_csv_response | |
| @app.get("/api/exports/patients.csv") | |
| async def export_patients(): | |
| patients = db.query(Patient).all() | |
| patients_data = [p.dict() for p in patients] | |
| return StreamingResponse( | |
| stream_csv_response(patients_data, ['id', 'name', 'dob', 'mrn']), | |
| media_type="text/csv", | |
| headers={"Content-Disposition": "attachment; filename=patients.csv"} | |
| ) | |
| Example 6: Conditional responses | |
| --------------------------------- | |
| from middleware.response_optimization import create_conditional_response | |
| @app.get("/api/reference/countries") | |
| def get_countries(): | |
| countries = load_countries() # Static data | |
| return create_conditional_response( | |
| countries, | |
| max_age=86400, # Cache for 24 hours | |
| stale_while_revalidate=3600 # Allow 1 hour stale | |
| ) | |
| """ | |