hailstorm-loadgen 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,22 @@
1
+
2
+ MIT License
3
+
4
+ Copyright (c) 2026 [Your Name]
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
@@ -0,0 +1,250 @@
1
+ Metadata-Version: 2.4
2
+ Name: hailstorm-loadgen
3
+ Version: 0.1.0
4
+ Summary: A standalone asyncio-based HTTP load-generation engine
5
+ Author: Karunakar Raunak
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/karunakar78/hailstorm
8
+ Project-URL: Repository, https://github.com/karunakar78/hailstorm
9
+ Project-URL: Issues, https://github.com/karunakar78/hailstorm/issues
10
+ Keywords: load-testing,http,asyncio,performance-testing,benchmarking
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Topic :: Software Development :: Testing
14
+ Classifier: Topic :: System :: Benchmark
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Operating System :: OS Independent
20
+ Requires-Python: >=3.11
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: httpx>=0.28
24
+ Requires-Dist: pydantic>=2.0
25
+ Requires-Dist: pyyaml>=6.0
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest>=8.0; extra == "dev"
28
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
29
+ Dynamic: license-file
30
+
31
+ # loadgen
32
+
33
+ A standalone, asyncio-based HTTP load-generation engine. It sends a configured number of requests per second against a target API for a configured duration, then prints a latency and success report.
34
+
35
+ ## Overview
36
+
37
+ loadgen answers a narrow question: *what happens to my API when I send N requests per second for M seconds?* It is a single-process command-line engine, not a distributed load-testing platform. Configuration is a YAML file; results are printed to stdout as a text report.
38
+
39
+ The engine separates three concerns:
40
+
41
+ - **Scheduling** — a fixed-rate clock decides when requests are launched.
42
+ - **Execution** — a semaphore caps how many requests are in flight at once.
43
+ - **Observation** — every request becomes an immutable sample; metrics are aggregated once, after the run.
44
+
45
+ ## Features
46
+
47
+ Implemented:
48
+
49
+ - YAML configuration validated with Pydantic before any traffic is generated
50
+ - Fixed-rate request pacing on a monotonic clock
51
+ - Configurable concurrency cap (maximum in-flight requests)
52
+ - Per-request timeout
53
+ - Per-request latency, status code, and error recording
54
+ - Summary report: totals, average RPS, error rate, average/p50/p95/p99 latency, status-code counts, error-type counts
55
+ - CLI (`loadgen` or `python -m loadgen`) and a small Python API
56
+ - Async test suite (pytest + pytest-asyncio) using httpx mock transports
57
+
58
+ Not implemented (planned / future):
59
+
60
+ - Distributed workers and test orchestration
61
+ - Request bodies (only method, URL, headers, and timeout are configurable)
62
+ - Retries, ramp-up, and graceful shutdown (signal handling)
63
+ - Live monitoring during a run; results are reported only at completion
64
+ - Persistent storage of results
65
+
66
+ ## Technology stack
67
+
68
+ | Technology | Role |
69
+ |---|---|
70
+ | Python >= 3.11 | Runtime |
71
+ | asyncio | Concurrency model (single event loop) |
72
+ | httpx >= 0.28 | Async HTTP client; connection pool sized to concurrency |
73
+ | pydantic >= 2.0 | Configuration parsing and validation |
74
+ | PyYAML >= 6.0 | YAML config parsing |
75
+ | pytest, pytest-asyncio | Test framework (dev dependency) |
76
+
77
+ ## Architecture
78
+
79
+ Request and data flow:
80
+
81
+ ```text
82
+ config.yaml
83
+ → load_config() # YAML → EngineConfig (Pydantic)
84
+ → LoadGenerator.run()
85
+ → httpx.AsyncClient # shared client, pool limit = concurrency
86
+ → Worker.run()
87
+ → RateLimiter.acquire() # one slot every 1/rate seconds
88
+ → asyncio.create_task(_execute_one)
89
+ → semaphore # at most `concurrency` in flight
90
+ → client.request() # HTTP request to target
91
+ → Metrics.record() # RequestSample(latency, status | error)
92
+ → gather(pending) # drain in-flight requests
93
+ → Metrics.summary(elapsed) # totals, RPS, percentiles
94
+ → Summary.render() # text report to stdout
95
+ ```
96
+
97
+ Key units:
98
+
99
+ - `RateLimiter` controls launch cadence (rate).
100
+ - The `asyncio.Semaphore` plus the httpx connection pool cap in-flight requests (concurrency).
101
+ - `RequestSample` is the only data unit between the target and the report.
102
+
103
+ ## Prerequisites
104
+
105
+ - Python 3.11 or newer
106
+ - pip
107
+
108
+
109
+ ## Installation
110
+
111
+ ### Install from PyPI
112
+
113
+ ```bash
114
+ pip install hailstorm-loadgen
115
+ ```
116
+
117
+ ### Install from source
118
+
119
+ Clone the Hailstorm repository:
120
+
121
+ ```bash
122
+ git clone https://github.com/karunakar78/hailstorm.git
123
+ cd hailstorm/loadgen
124
+ ```
125
+
126
+ Install in editable mode:
127
+
128
+ ```bash
129
+ pip install -e ".[dev]"
130
+ ```
131
+
132
+ The `dev` extra installs pytest and pytest-asyncio for the test suite.
133
+
134
+ ## Configuration
135
+
136
+ The engine reads a YAML file (`--config` defaults to `config.yaml`):
137
+
138
+ ```yaml
139
+ target:
140
+ url: "http://localhost:8000/test" # Target endpoint (required)
141
+ method: "GET" # HTTP method (default: GET; uppercased)
142
+ headers: {} # Optional request headers
143
+
144
+ load:
145
+ duration: 30 # Test duration in seconds (required, > 0)
146
+ rate: 10 # Target requests per second (required, > 0)
147
+ concurrency: 5 # Max in-flight requests (required, >= 1)
148
+
149
+ request:
150
+ timeout: 5 # Per-request timeout in seconds (default: 5.0)
151
+ ```
152
+
153
+ The `request` section is optional; all of its fields have defaults.
154
+
155
+ Validation is fail-fast: invalid values (for example `duration <= 0`, `rate <= 0`, `concurrency < 1`) raise a `ValidationError` before any request is sent.
156
+
157
+ ## Running
158
+
159
+ ```bash
160
+ cd loadgen
161
+ loadgen --config config.yaml
162
+ ```
163
+
164
+ or without the console script:
165
+
166
+ ```bash
167
+ python -m loadgen --config config.yaml
168
+ ```
169
+
170
+ The report is printed to stdout after the run:
171
+
172
+ ```text
173
+ Duration: 2.1 s
174
+ Total requests: 20
175
+ Average RPS: 9.5
176
+ Successful: 20
177
+ Failed: 0
178
+ Error rate: 0.0%
179
+ Latency:
180
+ avg: 7.2 ms
181
+ p50: 4.7 ms
182
+ p95: 18.0 ms
183
+ p99: 42.1 ms
184
+ Status codes:
185
+ 200: 20
186
+ ```
187
+
188
+ Note: the engine waits for in-flight requests to finish after the deadline, so the reported duration can slightly exceed the configured `duration`.
189
+
190
+ ## Python API
191
+
192
+ ```python
193
+ import asyncio
194
+ from loadgen import LoadGenerator, load_config
195
+
196
+ config = load_config("config.yaml")
197
+ summary = asyncio.run(LoadGenerator(config).run())
198
+ print(summary.render())
199
+ ```
200
+
201
+ `LoadGenerator` also accepts an optional `httpx.AsyncClient` for dependency injection (used by the tests with `httpx.MockTransport`).
202
+
203
+ ## Testing
204
+
205
+ ```bash
206
+ cd loadgen
207
+ pytest
208
+ ```
209
+
210
+ The suite uses `asyncio_mode = "auto"` (configured in `pyproject.toml`) and `httpx.MockTransport` to exercise the engine without network access. Last observed run: **12 passed** (pytest 9.1.1, pytest-asyncio 1.4.0, Python 3.12.6).
211
+
212
+ ## Project structure
213
+
214
+ ```text
215
+ loadgen/
216
+ ├── config.yaml # Example configuration
217
+ ├── pyproject.toml # Package metadata, dependencies, entry point, pytest config
218
+ ├── src/loadgen/
219
+ │ ├── __init__.py # Public API re-exports
220
+ │ ├── __main__.py # python -m loadgen entry point
221
+ │ ├── cli.py # argparse CLI (--config), runs engine, prints report
222
+ │ ├── config.py # Pydantic config models and load_config()
223
+ │ ├── engine.py # LoadGenerator: client setup, run, summary
224
+ │ ├── metrics.py # RequestSample, Metrics, Summary, percentile calculation
225
+ │ ├── rate_limiter.py # Fixed-rate slot scheduler
226
+ │ └── worker.py # Scheduler loop, concurrency semaphore, request execution
227
+ └── tests/
228
+ ├── test_config.py # Config loading, defaults, validation
229
+ ├── test_engine.py # End-to-end runs against mock transports
230
+ ├── test_metrics.py # Aggregation and percentile math
231
+ └── test_rate_limiter.py # Pacing accuracy
232
+ ```
233
+
234
+ ## Design decisions
235
+
236
+ - **Fixed-rate scheduling, not a token bucket.** Each `acquire()` advances a slot counter by `1/rate` on a monotonic clock. If a slot is missed (busy event loop), the delay is clamped to zero, producing a short catch-up burst; this keeps the aggregate rate on schedule instead of silently under-shooting the target RPS.
237
+ - **Rate and concurrency are independent knobs.** Tasks are spawned at the configured rate regardless of response times; the semaphore (plus the httpx pool limit) is the actual in-flight cap. Raising `rate` without `concurrency` deepens the queue; raising `concurrency` lets the engine sustain the rate against a slower target.
238
+ - **One shared HTTP client.** A single `httpx.AsyncClient` with `max_connections` and `max_keepalive_connections` set to `concurrency`, so at most that many sockets exist at once.
239
+ - **Fail-fast validation.** Configuration is parsed and validated before any socket is opened.
240
+ - **Drain before reporting.** In-flight requests are awaited in a `finally` block, so the summary includes every launched request.
241
+ - **Errors are samples, not run failures.** Timeouts and connection errors are recorded as samples with the exception type; the run continues and there are no retries.
242
+ - **Aggregate at the end.** Samples accumulate in a lock-protected list and are summarized once, keeping the hot path simple.
243
+
244
+ ## Known limitations
245
+
246
+ - Single-process, single machine; no distributed workers.
247
+ - All samples are held in memory until the run ends, which caps very long tests.
248
+ - No request body support; `target` accepts only `url`, `method`, and `headers`.
249
+ - No retries, ramp-up, or signal handling (interrupting the process does not produce a partial report).
250
+ - No live metrics during the run; the report is printed only at completion.
@@ -0,0 +1,220 @@
1
+ # loadgen
2
+
3
+ A standalone, asyncio-based HTTP load-generation engine. It sends a configured number of requests per second against a target API for a configured duration, then prints a latency and success report.
4
+
5
+ ## Overview
6
+
7
+ loadgen answers a narrow question: *what happens to my API when I send N requests per second for M seconds?* It is a single-process command-line engine, not a distributed load-testing platform. Configuration is a YAML file; results are printed to stdout as a text report.
8
+
9
+ The engine separates three concerns:
10
+
11
+ - **Scheduling** — a fixed-rate clock decides when requests are launched.
12
+ - **Execution** — a semaphore caps how many requests are in flight at once.
13
+ - **Observation** — every request becomes an immutable sample; metrics are aggregated once, after the run.
14
+
15
+ ## Features
16
+
17
+ Implemented:
18
+
19
+ - YAML configuration validated with Pydantic before any traffic is generated
20
+ - Fixed-rate request pacing on a monotonic clock
21
+ - Configurable concurrency cap (maximum in-flight requests)
22
+ - Per-request timeout
23
+ - Per-request latency, status code, and error recording
24
+ - Summary report: totals, average RPS, error rate, average/p50/p95/p99 latency, status-code counts, error-type counts
25
+ - CLI (`loadgen` or `python -m loadgen`) and a small Python API
26
+ - Async test suite (pytest + pytest-asyncio) using httpx mock transports
27
+
28
+ Not implemented (planned / future):
29
+
30
+ - Distributed workers and test orchestration
31
+ - Request bodies (only method, URL, headers, and timeout are configurable)
32
+ - Retries, ramp-up, and graceful shutdown (signal handling)
33
+ - Live monitoring during a run; results are reported only at completion
34
+ - Persistent storage of results
35
+
36
+ ## Technology stack
37
+
38
+ | Technology | Role |
39
+ |---|---|
40
+ | Python >= 3.11 | Runtime |
41
+ | asyncio | Concurrency model (single event loop) |
42
+ | httpx >= 0.28 | Async HTTP client; connection pool sized to concurrency |
43
+ | pydantic >= 2.0 | Configuration parsing and validation |
44
+ | PyYAML >= 6.0 | YAML config parsing |
45
+ | pytest, pytest-asyncio | Test framework (dev dependency) |
46
+
47
+ ## Architecture
48
+
49
+ Request and data flow:
50
+
51
+ ```text
52
+ config.yaml
53
+ → load_config() # YAML → EngineConfig (Pydantic)
54
+ → LoadGenerator.run()
55
+ → httpx.AsyncClient # shared client, pool limit = concurrency
56
+ → Worker.run()
57
+ → RateLimiter.acquire() # one slot every 1/rate seconds
58
+ → asyncio.create_task(_execute_one)
59
+ → semaphore # at most `concurrency` in flight
60
+ → client.request() # HTTP request to target
61
+ → Metrics.record() # RequestSample(latency, status | error)
62
+ → gather(pending) # drain in-flight requests
63
+ → Metrics.summary(elapsed) # totals, RPS, percentiles
64
+ → Summary.render() # text report to stdout
65
+ ```
66
+
67
+ Key units:
68
+
69
+ - `RateLimiter` controls launch cadence (rate).
70
+ - The `asyncio.Semaphore` plus the httpx connection pool cap in-flight requests (concurrency).
71
+ - `RequestSample` is the only data unit between the target and the report.
72
+
73
+ ## Prerequisites
74
+
75
+ - Python 3.11 or newer
76
+ - pip
77
+
78
+
79
+ ## Installation
80
+
81
+ ### Install from PyPI
82
+
83
+ ```bash
84
+ pip install hailstorm-loadgen
85
+ ```
86
+
87
+ ### Install from source
88
+
89
+ Clone the Hailstorm repository:
90
+
91
+ ```bash
92
+ git clone https://github.com/karunakar78/hailstorm.git
93
+ cd hailstorm/loadgen
94
+ ```
95
+
96
+ Install in editable mode:
97
+
98
+ ```bash
99
+ pip install -e ".[dev]"
100
+ ```
101
+
102
+ The `dev` extra installs pytest and pytest-asyncio for the test suite.
103
+
104
+ ## Configuration
105
+
106
+ The engine reads a YAML file (`--config` defaults to `config.yaml`):
107
+
108
+ ```yaml
109
+ target:
110
+ url: "http://localhost:8000/test" # Target endpoint (required)
111
+ method: "GET" # HTTP method (default: GET; uppercased)
112
+ headers: {} # Optional request headers
113
+
114
+ load:
115
+ duration: 30 # Test duration in seconds (required, > 0)
116
+ rate: 10 # Target requests per second (required, > 0)
117
+ concurrency: 5 # Max in-flight requests (required, >= 1)
118
+
119
+ request:
120
+ timeout: 5 # Per-request timeout in seconds (default: 5.0)
121
+ ```
122
+
123
+ The `request` section is optional; all of its fields have defaults.
124
+
125
+ Validation is fail-fast: invalid values (for example `duration <= 0`, `rate <= 0`, `concurrency < 1`) raise a `ValidationError` before any request is sent.
126
+
127
+ ## Running
128
+
129
+ ```bash
130
+ cd loadgen
131
+ loadgen --config config.yaml
132
+ ```
133
+
134
+ or without the console script:
135
+
136
+ ```bash
137
+ python -m loadgen --config config.yaml
138
+ ```
139
+
140
+ The report is printed to stdout after the run:
141
+
142
+ ```text
143
+ Duration: 2.1 s
144
+ Total requests: 20
145
+ Average RPS: 9.5
146
+ Successful: 20
147
+ Failed: 0
148
+ Error rate: 0.0%
149
+ Latency:
150
+ avg: 7.2 ms
151
+ p50: 4.7 ms
152
+ p95: 18.0 ms
153
+ p99: 42.1 ms
154
+ Status codes:
155
+ 200: 20
156
+ ```
157
+
158
+ Note: the engine waits for in-flight requests to finish after the deadline, so the reported duration can slightly exceed the configured `duration`.
159
+
160
+ ## Python API
161
+
162
+ ```python
163
+ import asyncio
164
+ from loadgen import LoadGenerator, load_config
165
+
166
+ config = load_config("config.yaml")
167
+ summary = asyncio.run(LoadGenerator(config).run())
168
+ print(summary.render())
169
+ ```
170
+
171
+ `LoadGenerator` also accepts an optional `httpx.AsyncClient` for dependency injection (used by the tests with `httpx.MockTransport`).
172
+
173
+ ## Testing
174
+
175
+ ```bash
176
+ cd loadgen
177
+ pytest
178
+ ```
179
+
180
+ The suite uses `asyncio_mode = "auto"` (configured in `pyproject.toml`) and `httpx.MockTransport` to exercise the engine without network access. Last observed run: **12 passed** (pytest 9.1.1, pytest-asyncio 1.4.0, Python 3.12.6).
181
+
182
+ ## Project structure
183
+
184
+ ```text
185
+ loadgen/
186
+ ├── config.yaml # Example configuration
187
+ ├── pyproject.toml # Package metadata, dependencies, entry point, pytest config
188
+ ├── src/loadgen/
189
+ │ ├── __init__.py # Public API re-exports
190
+ │ ├── __main__.py # python -m loadgen entry point
191
+ │ ├── cli.py # argparse CLI (--config), runs engine, prints report
192
+ │ ├── config.py # Pydantic config models and load_config()
193
+ │ ├── engine.py # LoadGenerator: client setup, run, summary
194
+ │ ├── metrics.py # RequestSample, Metrics, Summary, percentile calculation
195
+ │ ├── rate_limiter.py # Fixed-rate slot scheduler
196
+ │ └── worker.py # Scheduler loop, concurrency semaphore, request execution
197
+ └── tests/
198
+ ├── test_config.py # Config loading, defaults, validation
199
+ ├── test_engine.py # End-to-end runs against mock transports
200
+ ├── test_metrics.py # Aggregation and percentile math
201
+ └── test_rate_limiter.py # Pacing accuracy
202
+ ```
203
+
204
+ ## Design decisions
205
+
206
+ - **Fixed-rate scheduling, not a token bucket.** Each `acquire()` advances a slot counter by `1/rate` on a monotonic clock. If a slot is missed (busy event loop), the delay is clamped to zero, producing a short catch-up burst; this keeps the aggregate rate on schedule instead of silently under-shooting the target RPS.
207
+ - **Rate and concurrency are independent knobs.** Tasks are spawned at the configured rate regardless of response times; the semaphore (plus the httpx pool limit) is the actual in-flight cap. Raising `rate` without `concurrency` deepens the queue; raising `concurrency` lets the engine sustain the rate against a slower target.
208
+ - **One shared HTTP client.** A single `httpx.AsyncClient` with `max_connections` and `max_keepalive_connections` set to `concurrency`, so at most that many sockets exist at once.
209
+ - **Fail-fast validation.** Configuration is parsed and validated before any socket is opened.
210
+ - **Drain before reporting.** In-flight requests are awaited in a `finally` block, so the summary includes every launched request.
211
+ - **Errors are samples, not run failures.** Timeouts and connection errors are recorded as samples with the exception type; the run continues and there are no retries.
212
+ - **Aggregate at the end.** Samples accumulate in a lock-protected list and are summarized once, keeping the hot path simple.
213
+
214
+ ## Known limitations
215
+
216
+ - Single-process, single machine; no distributed workers.
217
+ - All samples are held in memory until the run ends, which caps very long tests.
218
+ - No request body support; `target` accepts only `url`, `method`, and `headers`.
219
+ - No retries, ramp-up, or signal handling (interrupting the process does not produce a partial report).
220
+ - No live metrics during the run; the report is printed only at completion.
@@ -0,0 +1,63 @@
1
+
2
+ [build-system]
3
+ requires = ["setuptools>=68"]
4
+ build-backend = "setuptools.build_meta"
5
+
6
+ [project]
7
+ name = "hailstorm-loadgen"
8
+ version = "0.1.0"
9
+ description = "A standalone asyncio-based HTTP load-generation engine"
10
+ readme = "README.md"
11
+ requires-python = ">=3.11"
12
+ license = "MIT"
13
+
14
+ authors = [
15
+ { name = "Karunakar Raunak" }
16
+ ]
17
+
18
+ keywords = [
19
+ "load-testing",
20
+ "http",
21
+ "asyncio",
22
+ "performance-testing",
23
+ "benchmarking"
24
+ ]
25
+
26
+ classifiers = [
27
+ "Development Status :: 3 - Alpha",
28
+ "Intended Audience :: Developers",
29
+ "Topic :: Software Development :: Testing",
30
+ "Topic :: System :: Benchmark",
31
+ "Programming Language :: Python :: 3",
32
+ "Programming Language :: Python :: 3.11",
33
+ "Programming Language :: Python :: 3.12",
34
+ "Programming Language :: Python :: 3.13",
35
+ "Operating System :: OS Independent",
36
+ ]
37
+
38
+ dependencies = [
39
+ "httpx>=0.28",
40
+ "pydantic>=2.0",
41
+ "pyyaml>=6.0"
42
+ ]
43
+
44
+ [project.optional-dependencies]
45
+ dev = [
46
+ "pytest>=8.0",
47
+ "pytest-asyncio>=0.23"
48
+ ]
49
+
50
+ [project.scripts]
51
+ loadgen = "loadgen.cli:main"
52
+
53
+ [project.urls]
54
+ Homepage = "https://github.com/karunakar78/hailstorm"
55
+ Repository = "https://github.com/karunakar78/hailstorm"
56
+ Issues = "https://github.com/karunakar78/hailstorm/issues"
57
+
58
+ [tool.setuptools.packages.find]
59
+ where = ["src"]
60
+
61
+ [tool.pytest.ini_options]
62
+ asyncio_mode = "auto"
63
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,250 @@
1
+ Metadata-Version: 2.4
2
+ Name: hailstorm-loadgen
3
+ Version: 0.1.0
4
+ Summary: A standalone asyncio-based HTTP load-generation engine
5
+ Author: Karunakar Raunak
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/karunakar78/hailstorm
8
+ Project-URL: Repository, https://github.com/karunakar78/hailstorm
9
+ Project-URL: Issues, https://github.com/karunakar78/hailstorm/issues
10
+ Keywords: load-testing,http,asyncio,performance-testing,benchmarking
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Topic :: Software Development :: Testing
14
+ Classifier: Topic :: System :: Benchmark
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Operating System :: OS Independent
20
+ Requires-Python: >=3.11
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: httpx>=0.28
24
+ Requires-Dist: pydantic>=2.0
25
+ Requires-Dist: pyyaml>=6.0
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest>=8.0; extra == "dev"
28
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
29
+ Dynamic: license-file
30
+
31
+ # loadgen
32
+
33
+ A standalone, asyncio-based HTTP load-generation engine. It sends a configured number of requests per second against a target API for a configured duration, then prints a latency and success report.
34
+
35
+ ## Overview
36
+
37
+ loadgen answers a narrow question: *what happens to my API when I send N requests per second for M seconds?* It is a single-process command-line engine, not a distributed load-testing platform. Configuration is a YAML file; results are printed to stdout as a text report.
38
+
39
+ The engine separates three concerns:
40
+
41
+ - **Scheduling** — a fixed-rate clock decides when requests are launched.
42
+ - **Execution** — a semaphore caps how many requests are in flight at once.
43
+ - **Observation** — every request becomes an immutable sample; metrics are aggregated once, after the run.
44
+
45
+ ## Features
46
+
47
+ Implemented:
48
+
49
+ - YAML configuration validated with Pydantic before any traffic is generated
50
+ - Fixed-rate request pacing on a monotonic clock
51
+ - Configurable concurrency cap (maximum in-flight requests)
52
+ - Per-request timeout
53
+ - Per-request latency, status code, and error recording
54
+ - Summary report: totals, average RPS, error rate, average/p50/p95/p99 latency, status-code counts, error-type counts
55
+ - CLI (`loadgen` or `python -m loadgen`) and a small Python API
56
+ - Async test suite (pytest + pytest-asyncio) using httpx mock transports
57
+
58
+ Not implemented (planned / future):
59
+
60
+ - Distributed workers and test orchestration
61
+ - Request bodies (only method, URL, headers, and timeout are configurable)
62
+ - Retries, ramp-up, and graceful shutdown (signal handling)
63
+ - Live monitoring during a run; results are reported only at completion
64
+ - Persistent storage of results
65
+
66
+ ## Technology stack
67
+
68
+ | Technology | Role |
69
+ |---|---|
70
+ | Python >= 3.11 | Runtime |
71
+ | asyncio | Concurrency model (single event loop) |
72
+ | httpx >= 0.28 | Async HTTP client; connection pool sized to concurrency |
73
+ | pydantic >= 2.0 | Configuration parsing and validation |
74
+ | PyYAML >= 6.0 | YAML config parsing |
75
+ | pytest, pytest-asyncio | Test framework (dev dependency) |
76
+
77
+ ## Architecture
78
+
79
+ Request and data flow:
80
+
81
+ ```text
82
+ config.yaml
83
+ → load_config() # YAML → EngineConfig (Pydantic)
84
+ → LoadGenerator.run()
85
+ → httpx.AsyncClient # shared client, pool limit = concurrency
86
+ → Worker.run()
87
+ → RateLimiter.acquire() # one slot every 1/rate seconds
88
+ → asyncio.create_task(_execute_one)
89
+ → semaphore # at most `concurrency` in flight
90
+ → client.request() # HTTP request to target
91
+ → Metrics.record() # RequestSample(latency, status | error)
92
+ → gather(pending) # drain in-flight requests
93
+ → Metrics.summary(elapsed) # totals, RPS, percentiles
94
+ → Summary.render() # text report to stdout
95
+ ```
96
+
97
+ Key units:
98
+
99
+ - `RateLimiter` controls launch cadence (rate).
100
+ - The `asyncio.Semaphore` plus the httpx connection pool cap in-flight requests (concurrency).
101
+ - `RequestSample` is the only data unit between the target and the report.
102
+
103
+ ## Prerequisites
104
+
105
+ - Python 3.11 or newer
106
+ - pip
107
+
108
+
109
+ ## Installation
110
+
111
+ ### Install from PyPI
112
+
113
+ ```bash
114
+ pip install hailstorm-loadgen
115
+ ```
116
+
117
+ ### Install from source
118
+
119
+ Clone the Hailstorm repository:
120
+
121
+ ```bash
122
+ git clone https://github.com/karunakar78/hailstorm.git
123
+ cd hailstorm/loadgen
124
+ ```
125
+
126
+ Install in editable mode:
127
+
128
+ ```bash
129
+ pip install -e ".[dev]"
130
+ ```
131
+
132
+ The `dev` extra installs pytest and pytest-asyncio for the test suite.
133
+
134
+ ## Configuration
135
+
136
+ The engine reads a YAML file (`--config` defaults to `config.yaml`):
137
+
138
+ ```yaml
139
+ target:
140
+ url: "http://localhost:8000/test" # Target endpoint (required)
141
+ method: "GET" # HTTP method (default: GET; uppercased)
142
+ headers: {} # Optional request headers
143
+
144
+ load:
145
+ duration: 30 # Test duration in seconds (required, > 0)
146
+ rate: 10 # Target requests per second (required, > 0)
147
+ concurrency: 5 # Max in-flight requests (required, >= 1)
148
+
149
+ request:
150
+ timeout: 5 # Per-request timeout in seconds (default: 5.0)
151
+ ```
152
+
153
+ The `request` section is optional; all of its fields have defaults.
154
+
155
+ Validation is fail-fast: invalid values (for example `duration <= 0`, `rate <= 0`, `concurrency < 1`) raise a `ValidationError` before any request is sent.
156
+
157
+ ## Running
158
+
159
+ ```bash
160
+ cd loadgen
161
+ loadgen --config config.yaml
162
+ ```
163
+
164
+ or without the console script:
165
+
166
+ ```bash
167
+ python -m loadgen --config config.yaml
168
+ ```
169
+
170
+ The report is printed to stdout after the run:
171
+
172
+ ```text
173
+ Duration: 2.1 s
174
+ Total requests: 20
175
+ Average RPS: 9.5
176
+ Successful: 20
177
+ Failed: 0
178
+ Error rate: 0.0%
179
+ Latency:
180
+ avg: 7.2 ms
181
+ p50: 4.7 ms
182
+ p95: 18.0 ms
183
+ p99: 42.1 ms
184
+ Status codes:
185
+ 200: 20
186
+ ```
187
+
188
+ Note: the engine waits for in-flight requests to finish after the deadline, so the reported duration can slightly exceed the configured `duration`.
189
+
190
+ ## Python API
191
+
192
+ ```python
193
+ import asyncio
194
+ from loadgen import LoadGenerator, load_config
195
+
196
+ config = load_config("config.yaml")
197
+ summary = asyncio.run(LoadGenerator(config).run())
198
+ print(summary.render())
199
+ ```
200
+
201
+ `LoadGenerator` also accepts an optional `httpx.AsyncClient` for dependency injection (used by the tests with `httpx.MockTransport`).
202
+
203
+ ## Testing
204
+
205
+ ```bash
206
+ cd loadgen
207
+ pytest
208
+ ```
209
+
210
+ The suite uses `asyncio_mode = "auto"` (configured in `pyproject.toml`) and `httpx.MockTransport` to exercise the engine without network access. Last observed run: **12 passed** (pytest 9.1.1, pytest-asyncio 1.4.0, Python 3.12.6).
211
+
212
+ ## Project structure
213
+
214
+ ```text
215
+ loadgen/
216
+ ├── config.yaml # Example configuration
217
+ ├── pyproject.toml # Package metadata, dependencies, entry point, pytest config
218
+ ├── src/loadgen/
219
+ │ ├── __init__.py # Public API re-exports
220
+ │ ├── __main__.py # python -m loadgen entry point
221
+ │ ├── cli.py # argparse CLI (--config), runs engine, prints report
222
+ │ ├── config.py # Pydantic config models and load_config()
223
+ │ ├── engine.py # LoadGenerator: client setup, run, summary
224
+ │ ├── metrics.py # RequestSample, Metrics, Summary, percentile calculation
225
+ │ ├── rate_limiter.py # Fixed-rate slot scheduler
226
+ │ └── worker.py # Scheduler loop, concurrency semaphore, request execution
227
+ └── tests/
228
+ ├── test_config.py # Config loading, defaults, validation
229
+ ├── test_engine.py # End-to-end runs against mock transports
230
+ ├── test_metrics.py # Aggregation and percentile math
231
+ └── test_rate_limiter.py # Pacing accuracy
232
+ ```
233
+
234
+ ## Design decisions
235
+
236
+ - **Fixed-rate scheduling, not a token bucket.** Each `acquire()` advances a slot counter by `1/rate` on a monotonic clock. If a slot is missed (busy event loop), the delay is clamped to zero, producing a short catch-up burst; this keeps the aggregate rate on schedule instead of silently under-shooting the target RPS.
237
+ - **Rate and concurrency are independent knobs.** Tasks are spawned at the configured rate regardless of response times; the semaphore (plus the httpx pool limit) is the actual in-flight cap. Raising `rate` without `concurrency` deepens the queue; raising `concurrency` lets the engine sustain the rate against a slower target.
238
+ - **One shared HTTP client.** A single `httpx.AsyncClient` with `max_connections` and `max_keepalive_connections` set to `concurrency`, so at most that many sockets exist at once.
239
+ - **Fail-fast validation.** Configuration is parsed and validated before any socket is opened.
240
+ - **Drain before reporting.** In-flight requests are awaited in a `finally` block, so the summary includes every launched request.
241
+ - **Errors are samples, not run failures.** Timeouts and connection errors are recorded as samples with the exception type; the run continues and there are no retries.
242
+ - **Aggregate at the end.** Samples accumulate in a lock-protected list and are summarized once, keeping the hot path simple.
243
+
244
+ ## Known limitations
245
+
246
+ - Single-process, single machine; no distributed workers.
247
+ - All samples are held in memory until the run ends, which caps very long tests.
248
+ - No request body support; `target` accepts only `url`, `method`, and `headers`.
249
+ - No retries, ramp-up, or signal handling (interrupting the process does not produce a partial report).
250
+ - No live metrics during the run; the report is printed only at completion.
@@ -0,0 +1,21 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/hailstorm_loadgen.egg-info/PKG-INFO
5
+ src/hailstorm_loadgen.egg-info/SOURCES.txt
6
+ src/hailstorm_loadgen.egg-info/dependency_links.txt
7
+ src/hailstorm_loadgen.egg-info/entry_points.txt
8
+ src/hailstorm_loadgen.egg-info/requires.txt
9
+ src/hailstorm_loadgen.egg-info/top_level.txt
10
+ src/loadgen/__init__.py
11
+ src/loadgen/__main__.py
12
+ src/loadgen/cli.py
13
+ src/loadgen/config.py
14
+ src/loadgen/engine.py
15
+ src/loadgen/metrics.py
16
+ src/loadgen/rate_limiter.py
17
+ src/loadgen/worker.py
18
+ tests/test_config.py
19
+ tests/test_engine.py
20
+ tests/test_metrics.py
21
+ tests/test_rate_limiter.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ loadgen = loadgen.cli:main
@@ -0,0 +1,7 @@
1
+ httpx>=0.28
2
+ pydantic>=2.0
3
+ pyyaml>=6.0
4
+
5
+ [dev]
6
+ pytest>=8.0
7
+ pytest-asyncio>=0.23
@@ -0,0 +1,15 @@
1
+ from .config import EngineConfig, LoadConfig, RequestConfig, TargetConfig, load_config
2
+ from .engine import LoadGenerator
3
+ from .metrics import Metrics, RequestSample, Summary
4
+
5
+ __all__ = [
6
+ "EngineConfig",
7
+ "LoadConfig",
8
+ "LoadGenerator",
9
+ "Metrics",
10
+ "RequestConfig",
11
+ "RequestSample",
12
+ "Summary",
13
+ "TargetConfig",
14
+ "load_config",
15
+ ]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
@@ -0,0 +1,23 @@
1
+ """Command-line entry point."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+
8
+ from .config import load_config
9
+ from .engine import LoadGenerator
10
+
11
+
12
+ def main() -> None:
13
+ parser = argparse.ArgumentParser(prog="loadgen", description="HTTP load-generation engine")
14
+ parser.add_argument("--config", default="config.yaml", help="Path to YAML config file")
15
+ args = parser.parse_args()
16
+
17
+ config = load_config(args.config)
18
+ summary = asyncio.run(LoadGenerator(config).run())
19
+ print(summary.render())
20
+
21
+
22
+ if __name__ == "__main__":
23
+ main()
@@ -0,0 +1,40 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ import yaml
6
+ from pydantic import BaseModel, Field, field_validator
7
+
8
+
9
+ class TargetConfig(BaseModel):
10
+ url: str
11
+ method: str = "GET"
12
+ headers: dict[str, str] = Field(default_factory=dict)
13
+
14
+ @field_validator("method")
15
+ @classmethod
16
+ def method_upper(cls, v: str) -> str:
17
+ return v.upper()
18
+
19
+
20
+ class LoadConfig(BaseModel):
21
+ duration: float = Field(gt=0, description="Test duration in seconds")
22
+ rate: float = Field(gt=0, description="Target requests per second")
23
+ concurrency: int = Field(ge=1, description="Max in-flight requests")
24
+
25
+
26
+ class RequestConfig(BaseModel):
27
+ timeout: float = Field(default=5.0, gt=0, description="Per-request timeout in seconds")
28
+
29
+
30
+ class EngineConfig(BaseModel):
31
+ target: TargetConfig
32
+ load: LoadConfig
33
+ request: RequestConfig = Field(default_factory=RequestConfig)
34
+
35
+
36
+ def load_config(path: str | Path) -> EngineConfig:
37
+ data = yaml.safe_load(Path(path).read_text())
38
+ if not isinstance(data, dict):
39
+ raise ValueError(f"Config file {path} must contain a YAML mapping")
40
+ return EngineConfig.model_validate(data)
@@ -0,0 +1,31 @@
1
+ from __future__ import annotations
2
+
3
+ import time
4
+
5
+ import httpx
6
+
7
+ from .config import EngineConfig
8
+ from .metrics import Metrics, Summary
9
+ from .worker import Worker
10
+
11
+
12
+ class LoadGenerator:
13
+ def __init__(self, config: EngineConfig, client: httpx.AsyncClient | None = None) -> None:
14
+ self._config = config
15
+ self._metrics = Metrics()
16
+ self._client = client
17
+
18
+ async def run(self) -> Summary:
19
+ started = time.monotonic()
20
+ if self._client is not None:
21
+ worker = Worker(self._config, self._client, self._metrics)
22
+ await worker.run()
23
+ else:
24
+ limits = httpx.Limits(
25
+ max_connections=self._config.load.concurrency,
26
+ max_keepalive_connections=self._config.load.concurrency,
27
+ )
28
+ async with httpx.AsyncClient(limits=limits) as client:
29
+ worker = Worker(self._config, client, self._metrics)
30
+ await worker.run()
31
+ return self._metrics.summary(time.monotonic() - started)
@@ -0,0 +1,103 @@
1
+ from __future__ import annotations
2
+
3
+ import threading
4
+ from collections import Counter
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass
9
+ class RequestSample:
10
+ latency_ms: float
11
+ status_code: int | None = None
12
+ error: str | None = None
13
+
14
+ @property
15
+ def success(self) -> bool:
16
+ return self.error is None and self.status_code is not None and self.status_code < 400
17
+
18
+
19
+ @dataclass
20
+ class Summary:
21
+ duration_s: float
22
+ total: int
23
+ succeeded: int
24
+ failed: int
25
+ error_rate: float
26
+ avg_rps: float
27
+ latency_avg_ms: float
28
+ latency_p50_ms: float
29
+ latency_p95_ms: float
30
+ latency_p99_ms: float
31
+ status_codes: dict[int, int]
32
+ errors: dict[str, int]
33
+
34
+ def render(self) -> str:
35
+ lines = [
36
+ f"Duration: {self.duration_s:.1f} s",
37
+ f"Total requests: {self.total}",
38
+ f"Average RPS: {self.avg_rps:.1f}",
39
+ f"Successful: {self.succeeded}",
40
+ f"Failed: {self.failed}",
41
+ f"Error rate: {self.error_rate:.1%}",
42
+ "Latency:",
43
+ f" avg: {self.latency_avg_ms:.1f} ms",
44
+ f" p50: {self.latency_p50_ms:.1f} ms",
45
+ f" p95: {self.latency_p95_ms:.1f} ms",
46
+ f" p99: {self.latency_p99_ms:.1f} ms",
47
+ ]
48
+ if self.status_codes:
49
+ lines.append("Status codes:")
50
+ for code, count in sorted(self.status_codes.items()):
51
+ lines.append(f" {code}: {count}")
52
+ if self.errors:
53
+ lines.append("Errors:")
54
+ for err, count in sorted(self.errors.items()):
55
+ lines.append(f" {err}: {count}")
56
+ return "\n".join(lines)
57
+
58
+
59
+ def _percentile(sorted_values: list[float], pct: float) -> float:
60
+ if not sorted_values:
61
+ return 0.0
62
+ if len(sorted_values) == 1:
63
+ return sorted_values[0]
64
+ rank = (pct / 100) * (len(sorted_values) - 1)
65
+ low = int(rank)
66
+ high = min(low + 1, len(sorted_values) - 1)
67
+ frac = rank - low
68
+ return sorted_values[low] + frac * (sorted_values[high] - sorted_values[low])
69
+
70
+
71
+ class Metrics:
72
+ def __init__(self) -> None:
73
+ self._samples: list[RequestSample] = []
74
+ self._lock = threading.Lock()
75
+
76
+ def record(self, sample: RequestSample) -> None:
77
+ with self._lock:
78
+ self._samples.append(sample)
79
+
80
+ def summary(self, duration_s: float) -> Summary:
81
+ with self._lock:
82
+ samples = list(self._samples)
83
+ total = len(samples)
84
+ succeeded = sum(1 for s in samples if s.success)
85
+ failed = total - succeeded
86
+ latencies = sorted(s.latency_ms for s in samples)
87
+ status_codes = Counter(s.status_code for s in samples if s.status_code is not None)
88
+ errors = Counter(s.error for s in samples if s.error is not None)
89
+ avg_latency = sum(latencies) / len(latencies) if latencies else 0.0
90
+ return Summary(
91
+ duration_s=duration_s,
92
+ total=total,
93
+ succeeded=succeeded,
94
+ failed=failed,
95
+ error_rate=(failed / total) if total else 0.0,
96
+ avg_rps=(total / duration_s) if duration_s > 0 else 0.0,
97
+ latency_avg_ms=avg_latency,
98
+ latency_p50_ms=_percentile(latencies, 50),
99
+ latency_p95_ms=_percentile(latencies, 95),
100
+ latency_p99_ms=_percentile(latencies, 99),
101
+ status_codes=dict(status_codes),
102
+ errors=dict(errors),
103
+ )
@@ -0,0 +1,24 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import time
5
+
6
+
7
+ class RateLimiter:
8
+ def __init__(self, rate: float, clock=time.monotonic) -> None:
9
+ if rate <= 0:
10
+ raise ValueError("rate must be positive")
11
+ self._interval = 1.0 / rate
12
+ self._clock = clock
13
+ self._start: float | None = None
14
+ self._next_slot = 0.0
15
+
16
+ async def acquire(self) -> None:
17
+ if self._start is None:
18
+ self._start = self._clock()
19
+ self._next_slot = self._start
20
+ wait_until = self._next_slot
21
+ self._next_slot += self._interval
22
+ delay = wait_until - self._clock()
23
+ if delay > 0:
24
+ await asyncio.sleep(delay)
@@ -0,0 +1,51 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import time
5
+
6
+ import httpx
7
+
8
+ from .config import EngineConfig
9
+ from .metrics import Metrics, RequestSample
10
+ from .rate_limiter import RateLimiter
11
+
12
+
13
+ class Worker:
14
+ def __init__(self, config: EngineConfig, client: httpx.AsyncClient, metrics: Metrics) -> None:
15
+ self._config = config
16
+ self._client = client
17
+ self._metrics = metrics
18
+ self._semaphore = asyncio.Semaphore(config.load.concurrency)
19
+ self._limiter = RateLimiter(config.load.rate)
20
+
21
+ async def _execute_one(self) -> None:
22
+ async with self._semaphore:
23
+ target = self._config.target
24
+ start = time.perf_counter()
25
+ try:
26
+ response = await self._client.request(
27
+ target.method,
28
+ target.url,
29
+ headers=target.headers,
30
+ timeout=self._config.request.timeout,
31
+ )
32
+ latency_ms = (time.perf_counter() - start) * 1000
33
+ self._metrics.record(RequestSample(latency_ms=latency_ms, status_code=response.status_code))
34
+ except httpx.HTTPError as exc:
35
+ latency_ms = (time.perf_counter() - start) * 1000
36
+ self._metrics.record(RequestSample(latency_ms=latency_ms, error=type(exc).__name__))
37
+
38
+ async def run(self) -> None:
39
+ deadline = time.monotonic() + self._config.load.duration
40
+ pending: set[asyncio.Task] = set()
41
+ try:
42
+ while time.monotonic() < deadline:
43
+ await self._limiter.acquire()
44
+ if time.monotonic() >= deadline:
45
+ break
46
+ task = asyncio.create_task(self._execute_one())
47
+ pending.add(task)
48
+ task.add_done_callback(pending.discard)
49
+ finally:
50
+ if pending:
51
+ await asyncio.gather(*pending, return_exceptions=True)
@@ -0,0 +1,44 @@
1
+ import pytest
2
+ from pydantic import ValidationError
3
+
4
+ from loadgen.config import EngineConfig, load_config
5
+
6
+ SAMPLE = """
7
+ target:
8
+ url: "http://localhost:8000/test"
9
+ method: "get"
10
+ headers: {"X-Test": "1"}
11
+ load:
12
+ duration: 30
13
+ rate: 10
14
+ concurrency: 5
15
+ request:
16
+ timeout: 5
17
+ """
18
+
19
+
20
+ def test_load_config_roundtrip(tmp_path):
21
+ path = tmp_path / "config.yaml"
22
+ path.write_text(SAMPLE)
23
+ config = load_config(path)
24
+ assert config.target.url == "http://localhost:8000/test"
25
+ assert config.target.method == "GET"
26
+ assert config.target.headers == {"X-Test": "1"}
27
+ assert config.load.duration == 30
28
+ assert config.load.rate == 10
29
+ assert config.load.concurrency == 5
30
+ assert config.request.timeout == 5
31
+
32
+
33
+ def test_default_request_config(tmp_path):
34
+ path = tmp_path / "config.yaml"
35
+ path.write_text(SAMPLE.replace("request:\n timeout: 5\n", ""))
36
+ config = load_config(path)
37
+ assert config.request.timeout == 5.0
38
+
39
+
40
+ def test_invalid_config_rejected():
41
+ with pytest.raises(ValidationError):
42
+ EngineConfig.model_validate(
43
+ {"target": {"url": "http://x"}, "load": {"duration": -1, "rate": 0, "concurrency": 0}}
44
+ )
@@ -0,0 +1,84 @@
1
+ import asyncio
2
+
3
+ import httpx
4
+ import pytest
5
+
6
+ from loadgen.config import EngineConfig, LoadConfig, TargetConfig
7
+ from loadgen.engine import LoadGenerator
8
+
9
+
10
+ def make_config(**load_overrides) -> EngineConfig:
11
+ load = {"duration": 1, "rate": 10, "concurrency": 5, **load_overrides}
12
+ return EngineConfig(target=TargetConfig(url="http://test/"), load=LoadConfig(**load))
13
+
14
+
15
+ async def test_engine_success():
16
+ calls = 0
17
+
18
+ def handler(request: httpx.Request) -> httpx.Response:
19
+ nonlocal calls
20
+ calls += 1
21
+ return httpx.Response(200)
22
+
23
+ client = httpx.AsyncClient(transport=httpx.MockTransport(handler))
24
+ summary = await LoadGenerator(make_config(), client=client).run()
25
+ await client.aclose()
26
+
27
+ assert summary.total == 10
28
+ assert summary.succeeded == 10
29
+ assert summary.failed == 0
30
+ assert summary.status_codes == {200: 10}
31
+ assert calls == 10
32
+
33
+
34
+ async def test_engine_records_failures():
35
+ def handler(request: httpx.Request) -> httpx.Response:
36
+ if request.url.path == "/fail":
37
+ return httpx.Response(500)
38
+ return httpx.Response(200)
39
+
40
+ config = make_config()
41
+ config.target.url = "http://test/fail"
42
+ client = httpx.AsyncClient(transport=httpx.MockTransport(handler))
43
+ summary = await LoadGenerator(config, client=client).run()
44
+ await client.aclose()
45
+
46
+ assert summary.total == 10
47
+ assert summary.failed == 10
48
+ assert summary.error_rate == 1.0
49
+ assert summary.status_codes == {500: 10}
50
+
51
+
52
+ async def test_engine_records_http_errors():
53
+ def handler(request: httpx.Request) -> httpx.Response:
54
+ raise httpx.ConnectError("boom")
55
+
56
+ client = httpx.AsyncClient(transport=httpx.MockTransport(handler))
57
+ summary = await LoadGenerator(make_config(rate=5, duration=1), client=client).run()
58
+ await client.aclose()
59
+
60
+ assert summary.total == 5
61
+ assert summary.failed == 5
62
+ assert summary.errors.get("ConnectError") == 5
63
+
64
+
65
+ async def test_concurrency_cap_respected():
66
+ in_flight = 0
67
+ max_in_flight = 0
68
+
69
+ async def slow_handler(request: httpx.Request) -> httpx.Response:
70
+ nonlocal in_flight, max_in_flight
71
+ in_flight += 1
72
+ max_in_flight = max(max_in_flight, in_flight)
73
+ await asyncio.sleep(0.05)
74
+ in_flight -= 1
75
+ return httpx.Response(200)
76
+
77
+ client = httpx.AsyncClient(transport=httpx.MockTransport(slow_handler))
78
+ summary = await LoadGenerator(
79
+ make_config(rate=20, duration=1, concurrency=3), client=client
80
+ ).run()
81
+ await client.aclose()
82
+
83
+ assert max_in_flight <= 3
84
+ assert summary.succeeded > 0
@@ -0,0 +1,38 @@
1
+ import pytest
2
+
3
+ from loadgen.metrics import Metrics, RequestSample
4
+
5
+
6
+ def test_summary_counts_and_success():
7
+ metrics = Metrics()
8
+ metrics.record(RequestSample(latency_ms=10.0, status_code=200))
9
+ metrics.record(RequestSample(latency_ms=20.0, status_code=201))
10
+ metrics.record(RequestSample(latency_ms=30.0, status_code=500))
11
+ metrics.record(RequestSample(latency_ms=40.0, error="ReadTimeout"))
12
+
13
+ summary = metrics.summary(duration_s=2.0)
14
+ assert summary.total == 4
15
+ assert summary.succeeded == 2
16
+ assert summary.failed == 2
17
+ assert summary.error_rate == 0.5
18
+ assert summary.avg_rps == 2.0
19
+ assert summary.latency_avg_ms == 25.0
20
+ assert summary.status_codes == {200: 1, 201: 1, 500: 1}
21
+ assert summary.errors == {"ReadTimeout": 1}
22
+
23
+
24
+ def test_percentile_calculation():
25
+ metrics = Metrics()
26
+ for i in range(1, 101):
27
+ metrics.record(RequestSample(latency_ms=float(i), status_code=200))
28
+ summary = metrics.summary(duration_s=1.0)
29
+ assert summary.latency_p50_ms == pytest.approx(50.5)
30
+ assert summary.latency_p95_ms == pytest.approx(95.05)
31
+ assert summary.latency_p99_ms == pytest.approx(99.01)
32
+
33
+
34
+ def test_empty_summary():
35
+ summary = Metrics().summary(duration_s=1.0)
36
+ assert summary.total == 0
37
+ assert summary.error_rate == 0.0
38
+ assert summary.latency_p99_ms == 0.0
@@ -0,0 +1,21 @@
1
+ import time
2
+
3
+ import pytest
4
+
5
+ from loadgen.rate_limiter import RateLimiter
6
+
7
+
8
+ async def test_pacing_approximately_matches_rate():
9
+ rate = 20.0
10
+ limiter = RateLimiter(rate)
11
+ start = time.monotonic()
12
+ for _ in range(10):
13
+ await limiter.acquire()
14
+ elapsed = time.monotonic() - start
15
+ expected = 9 / rate # 10 acquisitions => 9 intervals of wait
16
+ assert elapsed == pytest.approx(expected, rel=0.35, abs=0.1)
17
+
18
+
19
+ def test_invalid_rate():
20
+ with pytest.raises(ValueError):
21
+ RateLimiter(0)