|
| 1 | +"""Shared HTTP request timing utilities for metric collection.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import time |
| 5 | +from typing import Any, Dict, Optional |
| 6 | + |
| 7 | +import aiohttp |
| 8 | + |
| 9 | +MAX_RETRIES = 2 |
| 10 | + |
| 11 | + |
| 12 | +class HttpTimingCollector: |
| 13 | + """Utility class for measuring HTTP request timing with detailed breakdown.""" |
| 14 | + |
| 15 | + def __init__(self): |
| 16 | + self.timing: Dict[str, float] = {} |
| 17 | + |
| 18 | + def create_trace_config(self) -> aiohttp.TraceConfig: |
| 19 | + """Create aiohttp trace configuration for detailed timing measurement.""" |
| 20 | + trace_config = aiohttp.TraceConfig() |
| 21 | + |
| 22 | + async def on_request_start(session, context, params): |
| 23 | + self.timing["start"] = time.monotonic() |
| 24 | + |
| 25 | + async def on_dns_resolvehost_start(session, context, params): |
| 26 | + self.timing["dns_start"] = time.monotonic() |
| 27 | + |
| 28 | + async def on_dns_resolvehost_end(session, context, params): |
| 29 | + self.timing["dns_end"] = time.monotonic() |
| 30 | + |
| 31 | + async def on_connection_create_start(session, context, params): |
| 32 | + self.timing["conn_start"] = time.monotonic() |
| 33 | + |
| 34 | + async def on_connection_create_end(session, context, params): |
| 35 | + self.timing["conn_end"] = time.monotonic() |
| 36 | + |
| 37 | + async def on_request_end(session, context, params): |
| 38 | + self.timing["end"] = time.monotonic() |
| 39 | + |
| 40 | + trace_config.on_request_start.append(on_request_start) |
| 41 | + trace_config.on_dns_resolvehost_start.append(on_dns_resolvehost_start) |
| 42 | + trace_config.on_dns_resolvehost_end.append(on_dns_resolvehost_end) |
| 43 | + trace_config.on_connection_create_start.append(on_connection_create_start) |
| 44 | + trace_config.on_connection_create_end.append(on_connection_create_end) |
| 45 | + trace_config.on_request_end.append(on_request_end) |
| 46 | + |
| 47 | + return trace_config |
| 48 | + |
| 49 | + def get_connection_time(self) -> float: |
| 50 | + """Get connection establishment time in seconds.""" |
| 51 | + if "conn_start" in self.timing and "conn_end" in self.timing: |
| 52 | + return self.timing["conn_end"] - self.timing["conn_start"] |
| 53 | + return 0.0 |
| 54 | + |
| 55 | + def get_dns_time(self) -> float: |
| 56 | + """Get DNS resolution time in seconds.""" |
| 57 | + if "dns_start" in self.timing and "dns_end" in self.timing: |
| 58 | + return self.timing["dns_end"] - self.timing["dns_start"] |
| 59 | + return 0.0 |
| 60 | + |
| 61 | + |
| 62 | +async def measure_http_request_timing( |
| 63 | + session: aiohttp.ClientSession, |
| 64 | + method: str, |
| 65 | + url: str, |
| 66 | + headers: Optional[Dict[str, str]] = None, |
| 67 | + json_data: Optional[Dict[str, Any]] = None, |
| 68 | + exclude_connection_time: bool = True, |
| 69 | +) -> tuple[float, aiohttp.ClientResponse]: |
| 70 | + """Measure HTTP request timing with retry logic and detailed breakdown. |
| 71 | +
|
| 72 | + Returns: |
| 73 | + tuple: (response_time_seconds, response) |
| 74 | + """ |
| 75 | + response_time = 0.0 |
| 76 | + response = None |
| 77 | + |
| 78 | + for retry_count in range(MAX_RETRIES): |
| 79 | + start_time = time.monotonic() |
| 80 | + |
| 81 | + # Send request |
| 82 | + if method.upper() == "POST": |
| 83 | + response = await session.post( |
| 84 | + url, headers=headers, json=json_data |
| 85 | + ) |
| 86 | + else: |
| 87 | + response = await session.get(url, headers=headers) |
| 88 | + |
| 89 | + response_time = time.monotonic() - start_time |
| 90 | + |
| 91 | + # Handle rate limiting |
| 92 | + if response.status == 429 and retry_count < MAX_RETRIES - 1: |
| 93 | + wait_time = int(response.headers.get("Retry-After", 3)) |
| 94 | + await response.release() |
| 95 | + await asyncio.sleep(wait_time) |
| 96 | + continue |
| 97 | + |
| 98 | + break |
| 99 | + |
| 100 | + if not response: |
| 101 | + raise ValueError("No response received") |
| 102 | + |
| 103 | + return response_time, response |
0 commit comments