-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbase.py
More file actions
294 lines (250 loc) · 11.8 KB
/
base.py
File metadata and controls
294 lines (250 loc) · 11.8 KB
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
"""Base class for library benchmarks"""
import asyncio
import statistics
import time
from abc import ABC, abstractmethod
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import urlparse
class LibraryBenchmark(ABC):
"""Base class for library-specific benchmark implementations"""
def __init__(self, config):
"""
Args:
config: Benchmark configuration dictionary with:
- num_sequential: Number of sequential requests
- num_concurrent: Number of concurrent requests
- concurrent_workers: Number of concurrent workers
- warmup_requests: Number of warmup requests
- local_url: Local HTTP server URL
- remote_http_url: Remote HTTP URL
- remote_https_url: Remote HTTPS URL
- http2_url: HTTP/2 test URL
- proxy_url_http: Proxy URL for HTTP targets
- proxy_url_https: Proxy URL for HTTPS targets
- proxy_target_http: HTTP target via proxy
- proxy_target_https: HTTPS target via proxy
"""
self.config = config
self.num_sequential = config["num_sequential"]
self.num_concurrent = config["num_concurrent"]
self.concurrent_workers = config["concurrent_workers"]
self.warmup_requests = config["warmup_requests"]
self.local_url = config["local_url"]
self.remote_http_url = config["remote_http_url"]
self.remote_https_url = config["remote_https_url"]
self.http2_url = config["http2_url"]
self.proxy_url_http = config.get("proxy_url_http")
self.proxy_url_https = config.get("proxy_url_https")
self.proxy_target_http = config["proxy_target_http"]
self.proxy_target_https = config["proxy_target_https"]
def validate_response_body(self, url, body_text):
"""
Validate that the response body contains the hostname from the URL.
Args:
url: The requested URL (e.g., "http://httpbin.org/get")
body_text: The response body as text
Raises:
AssertionError: If the hostname is not found in the response body
"""
try:
parsed = urlparse(url)
hostname = parsed.hostname or parsed.netloc.split('@')[-1].split(':')[0]
if not hostname or hostname in ['127.0.0.1', 'localhost']:
# Skip validation for local URLs
return
# Check if hostname appears in the response body
assert hostname in body_text, (
f"Validation failed: hostname '{hostname}' not found in response body. "
f"This might indicate proxy misconfiguration or incorrect routing."
)
except (AttributeError, IndexError) as e:
# If URL parsing fails, skip validation
pass
@abstractmethod
def get_test_matrix(self):
"""Return list of (test_name, test_key) tuples for this library"""
pass
@abstractmethod
def is_available(self):
"""Return True if library is available/installed"""
pass
def run_sequential_benchmark(self, name, func):
"""Run sequential benchmark"""
try:
# Warmup
for _ in range(self.warmup_requests):
func()
# Actual test
times = []
for _ in range(self.num_sequential):
start = time.perf_counter()
func()
elapsed = (time.perf_counter() - start) * 1000 # Convert to ms
times.append(elapsed)
# Detailed trend analysis
n = len(times)
# Quartile analysis
q1_size = n // 4
q1 = times[:q1_size] if q1_size > 0 else times[:1]
q2 = times[q1_size : 2 * q1_size] if q1_size > 0 else times
q3 = times[2 * q1_size : 3 * q1_size] if q1_size > 0 else times
q4 = times[3 * q1_size :] if q1_size > 0 else times
# Linear regression trend (slope in ms per request)
try:
x_vals = list(range(n))
x_mean = sum(x_vals) / n
y_mean = statistics.mean(times)
numerator = sum((x_vals[i] - x_mean) * (times[i] - y_mean) for i in range(n))
denominator = sum((x_vals[i] - x_mean) ** 2 for i in range(n))
trend_slope_ms = numerator / denominator if denominator != 0 else 0
except Exception:
trend_slope_ms = 0
# Stability metric (coefficient of variation)
mean_val = statistics.mean(times)
cv = (
(statistics.stdev(times) / mean_val * 100) if mean_val > 0 and len(times) > 1 else 0
)
return {
"mean_ms": mean_val,
"median_ms": statistics.median(times),
"min_ms": min(times),
"max_ms": max(times),
"stdev_ms": statistics.stdev(times) if len(times) > 1 else 0,
"p50_ms": statistics.median(times),
"p95_ms": times[int(n * 0.95)] if n > 20 else max(times),
"p99_ms": times[int(n * 0.99)] if n > 100 else max(times),
"timings": times, # All individual timings
"q1_avg_ms": statistics.mean(q1) if q1 else 0,
"q2_avg_ms": statistics.mean(q2) if q2 else 0,
"q3_avg_ms": statistics.mean(q3) if q3 else 0,
"q4_avg_ms": statistics.mean(q4) if q4 else 0,
"trend_slope_ms_per_req": trend_slope_ms, # Linear trend
"cv_pct": cv, # Coefficient of variation (stability metric)
"first_avg_ms": statistics.mean(q1) if q1 else 0,
"last_avg_ms": statistics.mean(q4) if q4 else 0,
}
except Exception as e:
return {"error": f"{type(e).__name__}: {str(e)[:100]}"}
def run_concurrent_sync(self, func):
"""Run concurrent synchronous benchmark"""
try:
# Track individual completion times
completion_times = []
start_time = time.perf_counter()
def timed_func():
func()
completion_times.append((time.perf_counter() - start_time) * 1000)
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=self.concurrent_workers) as executor:
futures = [executor.submit(timed_func) for _ in range(self.num_concurrent)]
for future in futures:
future.result()
total_time = time.perf_counter() - start
# Sort by completion time to analyze progression
completion_times.sort()
# Detailed analysis of completion times
n = len(completion_times)
# Quartile analysis
q1_size = n // 4
q1 = completion_times[:q1_size] if q1_size > 0 else completion_times[:1]
q4 = completion_times[3 * q1_size :] if q1_size > 0 else completion_times
# Linear trend
try:
x_vals = list(range(n))
x_mean = sum(x_vals) / n
y_mean = statistics.mean(completion_times)
numerator = sum(
(x_vals[i] - x_mean) * (completion_times[i] - y_mean) for i in range(n)
)
denominator = sum((x_vals[i] - x_mean) ** 2 for i in range(n))
trend_slope_ms = numerator / denominator if denominator != 0 else 0
except Exception:
trend_slope_ms = 0
mean_val = statistics.mean(completion_times)
cv = (
(statistics.stdev(completion_times) / mean_val * 100)
if mean_val > 0 and len(completion_times) > 1
else 0
)
return {
"total_time_s": total_time,
"req_per_sec": self.num_concurrent / total_time,
"avg_ms": (total_time / self.num_concurrent) * 1000,
"mean_completion_ms": mean_val,
"median_completion_ms": statistics.median(completion_times),
"min_completion_ms": min(completion_times) if completion_times else 0,
"max_completion_ms": max(completion_times) if completion_times else 0,
"p95_completion_ms": completion_times[int(n * 0.95)]
if n > 20
else max(completion_times)
if completion_times
else 0,
"completion_times": completion_times, # All individual completion times
"trend_slope_ms_per_req": trend_slope_ms,
"cv_pct": cv,
"first_avg_ms": statistics.mean(q1) if q1 else 0,
"last_avg_ms": statistics.mean(q4) if q4 else 0,
}
except Exception as e:
return {"error": f"{type(e).__name__}: {str(e)[:100]}"}
def run_async_benchmark(self, async_func):
"""Run async benchmark"""
try:
completion_times = []
async def run_test():
start_time = time.perf_counter()
async def timed_func():
await async_func()
completion_times.append((time.perf_counter() - start_time) * 1000)
start = time.perf_counter()
tasks = [timed_func() for _ in range(self.num_concurrent)]
await asyncio.gather(*tasks)
return time.perf_counter() - start
total_time = asyncio.run(run_test())
# Sort by completion time
completion_times.sort()
# Detailed analysis of completion times
n = len(completion_times)
# Quartile analysis
q1_size = n // 4
q1 = completion_times[:q1_size] if q1_size > 0 else completion_times[:1]
q4 = completion_times[3 * q1_size :] if q1_size > 0 else completion_times
# Linear trend
try:
x_vals = list(range(n))
x_mean = sum(x_vals) / n
y_mean = statistics.mean(completion_times)
numerator = sum(
(x_vals[i] - x_mean) * (completion_times[i] - y_mean) for i in range(n)
)
denominator = sum((x_vals[i] - x_mean) ** 2 for i in range(n))
trend_slope_ms = numerator / denominator if denominator != 0 else 0
except Exception:
trend_slope_ms = 0
mean_val = statistics.mean(completion_times)
cv = (
(statistics.stdev(completion_times) / mean_val * 100)
if mean_val > 0 and len(completion_times) > 1
else 0
)
return {
"total_time_s": total_time,
"req_per_sec": self.num_concurrent / total_time,
"avg_ms": (total_time / self.num_concurrent) * 1000,
"mean_completion_ms": mean_val,
"median_completion_ms": statistics.median(completion_times),
"min_completion_ms": min(completion_times) if completion_times else 0,
"max_completion_ms": max(completion_times) if completion_times else 0,
"p95_completion_ms": completion_times[int(n * 0.95)]
if n > 20
else max(completion_times)
if completion_times
else 0,
"completion_times": completion_times, # All individual completion times
"trend_slope_ms_per_req": trend_slope_ms,
"cv_pct": cv,
"first_avg_ms": statistics.mean(q1) if q1 else 0,
"last_avg_ms": statistics.mean(q4) if q4 else 0,
}
except Exception as e:
return {"error": f"{type(e).__name__}: {str(e)[:100]}"}