Files
2026-07-23 06:40:30 +03:30

86 lines
3.0 KiB
Python

#!/usr/bin/env python3
from __future__ import annotations
import argparse
import asyncio
import statistics
import time
import httpx
PAYLOAD = {
"requestId": "benchmark",
"customerLocation": {"latitude": 35.72, "longitude": 51.33},
"items": [{"sku": "BENCHMARK-SKU", "quantity": 1}],
"transportationCosts": [
{
"warehouseId": f"w{i}",
"fixedCost": 100 + i,
"distanceKm": 10 + i,
"costPerKm": 2,
"baseDeliveryMinutes": 45 + i,
}
for i in range(1, 34)
],
}
async def run(url: str, count: int, concurrency: int) -> None:
limits = httpx.Limits(max_connections=concurrency, max_keepalive_connections=concurrency)
timeout = httpx.Timeout(2)
durations: list[float] = []
failures = 0
semaphore = asyncio.Semaphore(concurrency)
async with httpx.AsyncClient(base_url=url, limits=limits, timeout=timeout) as client:
levels = [{"sku": "BENCHMARK-SKU", "quantity": count}]
for i in range(1, 34):
await client.put(
"/v1/inventory",
headers={"X-Admin-Token": "local-development-token"},
json={"warehouseId": f"w{i}", "levels": levels},
)
async def send(index: int, prefix: str) -> tuple[float, int]:
payload = PAYLOAD | {"requestId": f"{prefix}-{index}"}
request_started = time.perf_counter()
response = await client.post("/v1/allocations", json=payload)
return (time.perf_counter() - request_started) * 1000, response.status_code
# Establish the whole keep-alive pool before measuring steady-state API latency.
warmup = await asyncio.gather(*(send(index, "warmup") for index in range(concurrency)))
if any(status != 200 for _, status in warmup):
raise SystemExit("warm-up request failed")
async def one(index: int) -> None:
nonlocal failures
async with semaphore:
duration, response_status = await send(index, "benchmark")
durations.append(duration)
failures += int(response_status != 200)
started = time.perf_counter()
await asyncio.gather(*(one(index) for index in range(count)))
elapsed = time.perf_counter() - started
ordered = sorted(durations)
p95 = ordered[max(0, round(len(ordered) * 0.95) - 1)]
print(
f"requests={count} failures={failures} throughput={count / elapsed:.1f} req/s "
f"mean={statistics.mean(durations):.1f}ms p95={p95:.1f}ms"
)
if failures or p95 >= 200:
raise SystemExit(1)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--url", default="http://localhost:8080")
parser.add_argument("--requests", type=int, default=1_000)
parser.add_argument("--concurrency", type=int, default=25)
args = parser.parse_args()
asyncio.run(run(args.url, args.requests, args.concurrency))
if __name__ == "__main__":
main()