pyferrum 1.0.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.
- pyferrum-1.0.0/API.md +379 -0
- pyferrum-1.0.0/ARCHITECTURE.md +195 -0
- pyferrum-1.0.0/CHANGELOG.md +54 -0
- pyferrum-1.0.0/CODE_OF_CONDUCT.md +19 -0
- pyferrum-1.0.0/CONTRIBUTING.md +102 -0
- pyferrum-1.0.0/Cargo.lock +1209 -0
- pyferrum-1.0.0/Cargo.toml +47 -0
- pyferrum-1.0.0/LICENSE-MIT +21 -0
- pyferrum-1.0.0/PKG-INFO +227 -0
- pyferrum-1.0.0/README.md +182 -0
- pyferrum-1.0.0/ROADMAP.md +77 -0
- pyferrum-1.0.0/SECURITY.md +58 -0
- pyferrum-1.0.0/crates/ferrum-core/Cargo.toml +32 -0
- pyferrum-1.0.0/crates/ferrum-core/src/handler.rs +37 -0
- pyferrum-1.0.0/crates/ferrum-core/src/json.rs +18 -0
- pyferrum-1.0.0/crates/ferrum-core/src/lib.rs +28 -0
- pyferrum-1.0.0/crates/ferrum-core/src/native_abi.rs +147 -0
- pyferrum-1.0.0/crates/ferrum-core/src/plugins.rs +132 -0
- pyferrum-1.0.0/crates/ferrum-core/src/python/app.rs +345 -0
- pyferrum-1.0.0/crates/ferrum-core/src/python/conversion.rs +91 -0
- pyferrum-1.0.0/crates/ferrum-core/src/python/handler.rs +87 -0
- pyferrum-1.0.0/crates/ferrum-core/src/python/mod.rs +25 -0
- pyferrum-1.0.0/crates/ferrum-core/src/python/request.rs +112 -0
- pyferrum-1.0.0/crates/ferrum-core/src/python/response.rs +237 -0
- pyferrum-1.0.0/crates/ferrum-core/src/python/runtime.rs +161 -0
- pyferrum-1.0.0/crates/ferrum-core/src/request.rs +119 -0
- pyferrum-1.0.0/crates/ferrum-core/src/response.rs +186 -0
- pyferrum-1.0.0/crates/ferrum-core/src/router.rs +214 -0
- pyferrum-1.0.0/crates/ferrum-core/src/server/config.rs +119 -0
- pyferrum-1.0.0/crates/ferrum-core/src/server/dispatch.rs +616 -0
- pyferrum-1.0.0/crates/ferrum-core/src/server/lifecycle.rs +279 -0
- pyferrum-1.0.0/crates/ferrum-core/src/server/metrics.rs +92 -0
- pyferrum-1.0.0/crates/ferrum-core/src/server.rs +7 -0
- pyferrum-1.0.0/example-app/README.md +111 -0
- pyferrum-1.0.0/example-app/app.py +234 -0
- pyferrum-1.0.0/example-app/index.html +8 -0
- pyferrum-1.0.0/example-app/native/Cargo.toml +12 -0
- pyferrum-1.0.0/example-app/native/src/lib.rs +19 -0
- pyferrum-1.0.0/example-app/routes.toml +23 -0
- pyferrum-1.0.0/pyproject.toml +113 -0
- pyferrum-1.0.0/python/pyferrum/__init__.py +557 -0
- pyferrum-1.0.0/python/pyferrum/cli.py +277 -0
- pyferrum-1.0.0/python/pyferrum/py.typed +1 -0
- pyferrum-1.0.0/tests/benchmark_compare.py +179 -0
- pyferrum-1.0.0/tests/test_cli.py +558 -0
- pyferrum-1.0.0/tests/test_e2e.py +297 -0
- pyferrum-1.0.0/tests/test_middleware.py +221 -0
- pyferrum-1.0.0/tests/test_overload.py +112 -0
- pyferrum-1.0.0/tests/test_perf.py +111 -0
- pyferrum-1.0.0/tests/test_perf_async.py +159 -0
- pyferrum-1.0.0/tests/test_reliability.py +130 -0
- pyferrum-1.0.0/tests/test_responses.py +147 -0
- pyferrum-1.0.0/tests/test_routes_file.py +50 -0
- pyferrum-1.0.0/tests/test_rust_routes.py +90 -0
- pyferrum-1.0.0/tests/test_tls.py +118 -0
- pyferrum-1.0.0/tests/test_workers.py +81 -0
pyferrum-1.0.0/API.md
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
# pyferrum API reference
|
|
2
|
+
|
|
3
|
+
This document describes the public Python API in pyferrum 1.0.0. It covers
|
|
4
|
+
application setup, route registration, requests and responses, server options,
|
|
5
|
+
and the command-line runner. For architecture and execution order, see
|
|
6
|
+
[ARCHITECTURE.md](ARCHITECTURE.md). For a runnable app, see
|
|
7
|
+
[example-app/](example-app/).
|
|
8
|
+
|
|
9
|
+
## Application
|
|
10
|
+
|
|
11
|
+
### `Ferrum`
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from pyferrum import Ferrum
|
|
15
|
+
|
|
16
|
+
app = Ferrum(
|
|
17
|
+
server_name: str = "pyferrum/1.0",
|
|
18
|
+
max_python_in_flight: int = 100,
|
|
19
|
+
)
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Creates an application and its route table.
|
|
23
|
+
|
|
24
|
+
| Argument | Meaning |
|
|
25
|
+
| --- | --- |
|
|
26
|
+
| `server_name` | Value of the HTTP `Server` response header. An empty string disables the header. |
|
|
27
|
+
| `max_python_in_flight` | Maximum concurrent Python handler invocations for this application instance. Must be greater than zero; excess Python dispatch receives `503 Service Unavailable`. |
|
|
28
|
+
|
|
29
|
+
Register routes before calling `run()`. Routes are moved into the server when
|
|
30
|
+
it starts; the same application instance is not intended to be restarted.
|
|
31
|
+
|
|
32
|
+
### Route decorators
|
|
33
|
+
|
|
34
|
+
The application supports `get`, `post`, `put`, `patch`, `delete`, `head`, and
|
|
35
|
+
`options`:
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
@app.get("/users/{user_id}")
|
|
39
|
+
async def get_user(request):
|
|
40
|
+
return {"id": request.path_params["user_id"]}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Each decorator takes one route pattern and returns a decorator that registers
|
|
44
|
+
the function and returns it unchanged. A route handler accepts one `Request`
|
|
45
|
+
and may be synchronous or asynchronous. Path parameters use braces, such as
|
|
46
|
+
`{user_id}`. Duplicate or invalid registrations raise `ValueError`.
|
|
47
|
+
|
|
48
|
+
The HTTP method and route pattern together identify a route. A path that has
|
|
49
|
+
routes registered for other methods returns `405 Method Not Allowed`; a path
|
|
50
|
+
that does not match any route returns `404 Not Found`.
|
|
51
|
+
|
|
52
|
+
### `route_count()`
|
|
53
|
+
|
|
54
|
+
Returns the number of registered routes. Once `run()` has started, routes have
|
|
55
|
+
been moved into the server; after it returns, this count reflects the
|
|
56
|
+
application's remaining route table.
|
|
57
|
+
|
|
58
|
+
### `load_routes(route_file, python_handlers=None)`
|
|
59
|
+
|
|
60
|
+
Loads a TOML file containing a `[[routes]]` array and returns its entry count.
|
|
61
|
+
Each table requires string `method`, `path`, and `handler` values. `runtime`
|
|
62
|
+
defaults to `"python"`.
|
|
63
|
+
|
|
64
|
+
```toml
|
|
65
|
+
[[routes]]
|
|
66
|
+
method = "GET"
|
|
67
|
+
path = "/healthz"
|
|
68
|
+
handler = "health"
|
|
69
|
+
runtime = "rust"
|
|
70
|
+
|
|
71
|
+
[[routes]]
|
|
72
|
+
method = "GET"
|
|
73
|
+
path = "/hello"
|
|
74
|
+
handler = "hello"
|
|
75
|
+
runtime = "python"
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
app.load_routes(
|
|
80
|
+
"routes.toml",
|
|
81
|
+
python_handlers={"hello": hello_handler},
|
|
82
|
+
)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Python handlers must be explicitly supplied in `python_handlers`; TOML does
|
|
86
|
+
not import or execute arbitrary Python names. Supported Rust handler names
|
|
87
|
+
are `health`, `liveness`, and `readiness`. They return fixed responses and do
|
|
88
|
+
not check application dependencies. Invalid TOML, missing files, unsupported
|
|
89
|
+
runtimes, unknown handlers, or invalid routes raise `ValueError`. If loading
|
|
90
|
+
fails partway through, routes registered earlier in that call are not rolled
|
|
91
|
+
back.
|
|
92
|
+
|
|
93
|
+
### `static_file(path, file_path, content_type="application/octet-stream", method="GET")`
|
|
94
|
+
|
|
95
|
+
Registers a Rust-served route. The file is read into memory immediately when
|
|
96
|
+
the route is registered; later changes to the file are not reflected. File
|
|
97
|
+
read failures raise `OSError`; invalid methods, paths, or content types raise
|
|
98
|
+
`ValueError`. This is not a streaming or range-request file server.
|
|
99
|
+
|
|
100
|
+
### `redirect(path, location, status_code=302)`
|
|
101
|
+
|
|
102
|
+
Registers a Rust-served `GET` redirect. The status must be in the 3xx range.
|
|
103
|
+
Invalid status codes or locations raise `ValueError`. Validate user-provided
|
|
104
|
+
redirect destinations to prevent open redirects.
|
|
105
|
+
|
|
106
|
+
## Request object
|
|
107
|
+
|
|
108
|
+
Each handler receives one `Request`:
|
|
109
|
+
|
|
110
|
+
| Attribute | Type | Description |
|
|
111
|
+
| --- | --- | --- |
|
|
112
|
+
| `method` | `str` | HTTP method, such as `"GET"` or `"POST"`. |
|
|
113
|
+
| `path` | `str` | URL path without the query string. |
|
|
114
|
+
| `query_string` | `str` | Raw query string without the leading `?`; empty when absent. |
|
|
115
|
+
| `query_params` | `dict[str, str]` | URL-decoded query values. Repeated keys are joined with commas; this is a flat mapping, not a multi-value mapping. |
|
|
116
|
+
| `path_params` | `dict[str, str]` | Named route parameters, such as `{"user_id": "42"}`. |
|
|
117
|
+
| `headers` | `dict[str, str]` | Request headers whose values can be represented as text. Header names are normalized to lowercase by the HTTP parser. |
|
|
118
|
+
| `body` | `bytes` | Fully buffered request body. |
|
|
119
|
+
| `remote_addr` | `str \| None` | Client socket address, or the forwarded address when the peer is a configured trusted proxy. |
|
|
120
|
+
| `scheme` | `str` | `"http"` or `"https"`; trusted forwarded protocol is used for configured proxies. |
|
|
121
|
+
|
|
122
|
+
Use `request.headers.get("authorization")` to read an `Authorization` header.
|
|
123
|
+
The framework does not parse credentials, authenticate a principal, or enforce
|
|
124
|
+
permissions.
|
|
125
|
+
|
|
126
|
+
### Request methods
|
|
127
|
+
|
|
128
|
+
- `request.text()` decodes the body as UTF-8. Invalid UTF-8 raises `ValueError`.
|
|
129
|
+
- `request.json()` parses a JSON body and returns the corresponding Python
|
|
130
|
+
value. Invalid JSON raises `ValueError`.
|
|
131
|
+
|
|
132
|
+
Request bodies are fully buffered before a handler runs. The default engine
|
|
133
|
+
limit is 10 MiB. This limit is not currently exposed through the Python
|
|
134
|
+
`run()` API.
|
|
135
|
+
|
|
136
|
+
## Handler return values
|
|
137
|
+
|
|
138
|
+
A handler can return:
|
|
139
|
+
|
|
140
|
+
- `Response` or `StreamingResponse` for explicit status, headers, and content
|
|
141
|
+
type.
|
|
142
|
+
- A `dict`, `list`, tuple, or another supported JSON-compatible value for a
|
|
143
|
+
pretty-printed JSON response.
|
|
144
|
+
- `str` for a UTF-8 `text/plain` response.
|
|
145
|
+
- `bytes` for an `application/octet-stream` response.
|
|
146
|
+
|
|
147
|
+
Unsupported objects and serialization errors are reported as handler errors;
|
|
148
|
+
they are not silently converted to strings.
|
|
149
|
+
|
|
150
|
+
## Response types and helpers
|
|
151
|
+
|
|
152
|
+
### `Response`
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
Response(body, status_code=200, content_type="application/json", headers=None)
|
|
156
|
+
Response.json(data, status_code=200, headers=None)
|
|
157
|
+
Response.text(text, status_code=200, headers=None)
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
`body` is bytes-like input; `headers` is an optional mapping of string names
|
|
161
|
+
to string values. `Response.json` serializes JSON-compatible values. Use
|
|
162
|
+
`JsonResponse` or `TextResponse` below for the same common response patterns.
|
|
163
|
+
|
|
164
|
+
### `StreamingResponse`
|
|
165
|
+
|
|
166
|
+
```python
|
|
167
|
+
StreamingResponse(
|
|
168
|
+
source,
|
|
169
|
+
status_code=200,
|
|
170
|
+
content_type="application/octet-stream",
|
|
171
|
+
headers=None,
|
|
172
|
+
)
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
`source` must be an asynchronous iterable that yields only `bytes` or `str`.
|
|
176
|
+
The stream uses a bounded channel to apply backpressure. Once response headers
|
|
177
|
+
have been sent, a stream failure ends the stream; the server cannot replace
|
|
178
|
+
the already-sent status with an error response.
|
|
179
|
+
|
|
180
|
+
### Convenience response helpers
|
|
181
|
+
|
|
182
|
+
```python
|
|
183
|
+
JsonResponse(data, status_code=200, headers=None)
|
|
184
|
+
TextResponse(text, status_code=200, headers=None)
|
|
185
|
+
HtmlResponse(html, status_code=200, headers=None)
|
|
186
|
+
XmlResponse(xml, status_code=200, headers=None)
|
|
187
|
+
CsvResponse(rows, status_code=200, headers=None)
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
- `JsonResponse` returns JSON.
|
|
191
|
+
- `TextResponse` returns UTF-8 `text/plain`.
|
|
192
|
+
- `HtmlResponse` returns UTF-8 `text/html`; callers must escape untrusted
|
|
193
|
+
values before embedding them in markup.
|
|
194
|
+
- `XmlResponse` returns UTF-8 `application/xml`; callers supply serialized
|
|
195
|
+
XML.
|
|
196
|
+
- `CsvResponse` serializes an iterable of rows with Python's CSV writer.
|
|
197
|
+
Spreadsheet-formula injection in untrusted cells is not neutralized.
|
|
198
|
+
|
|
199
|
+
### `FileResponse`
|
|
200
|
+
|
|
201
|
+
```python
|
|
202
|
+
FileResponse(
|
|
203
|
+
path,
|
|
204
|
+
filename=None,
|
|
205
|
+
content_type=None,
|
|
206
|
+
status_code=200,
|
|
207
|
+
headers=None,
|
|
208
|
+
)
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
Reads the entire file into memory and returns it as an attachment. The
|
|
212
|
+
filename defaults to the basename of `path`, and content type is inferred from
|
|
213
|
+
the filename when not specified. A filename must not be empty, `"."`, `".."`,
|
|
214
|
+
contain a path separator, or contain control characters. File errors
|
|
215
|
+
propagate. This helper does not stream or support byte ranges; validate
|
|
216
|
+
untrusted paths and permissions in application code.
|
|
217
|
+
|
|
218
|
+
### `RedirectResponse`
|
|
219
|
+
|
|
220
|
+
```python
|
|
221
|
+
RedirectResponse(location, status_code=302, headers=None)
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
Returns an empty-body redirect. Supported status codes are `301`, `302`,
|
|
225
|
+
`303`, `307`, and `308`. A location must be non-empty and contain no control
|
|
226
|
+
characters. Validate destinations supplied by clients.
|
|
227
|
+
|
|
228
|
+
### Server-sent events
|
|
229
|
+
|
|
230
|
+
```python
|
|
231
|
+
ServerSentEvent(data, event=None, id=None, retry=None)
|
|
232
|
+
EventSourceResponse(source, status_code=200, headers=None)
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
`source` is an asynchronous iterable of strings or `ServerSentEvent`
|
|
236
|
+
instances. `ServerSentEvent.encode()` formats an event according to the SSE
|
|
237
|
+
wire format, splitting multiline data into `data:` fields. `event` and `id`
|
|
238
|
+
cannot contain CR, LF, or NUL; `retry` must be a non-negative integer.
|
|
239
|
+
`EventSourceResponse` uses `text/event-stream; charset=utf-8` and defaults to
|
|
240
|
+
`Cache-Control: no-cache`. A caller-provided cache-control header is preserved.
|
|
241
|
+
Connection lifetime and shutdown deadlines also apply to SSE streams.
|
|
242
|
+
|
|
243
|
+
## Running the server
|
|
244
|
+
|
|
245
|
+
### `app.run(...)`
|
|
246
|
+
|
|
247
|
+
`app.run()` starts the server and blocks the calling thread. The supported
|
|
248
|
+
options are:
|
|
249
|
+
|
|
250
|
+
| Option | Type | Default | Description |
|
|
251
|
+
| --- | --- | ---: | --- |
|
|
252
|
+
| `host` | `str` | `"127.0.0.1"` | Bind address. |
|
|
253
|
+
| `port` | `int` | `8080` | Listening port. |
|
|
254
|
+
| `request_timeout_seconds` | `float` | `30` | Maximum handler response time. Expiry returns `504`; it cannot forcibly stop synchronous Python code already running. |
|
|
255
|
+
| `body_timeout_seconds` | `float` | `30` | Maximum time to collect a request body. |
|
|
256
|
+
| `shutdown_timeout_seconds` | `float` | `10` | Maximum drain time during shutdown. |
|
|
257
|
+
| `connection_timeout_seconds` | `float` | `120` | Maximum lifetime of an accepted connection. |
|
|
258
|
+
| `security_headers_enabled` | `bool` | `True` | Add `X-Content-Type-Options`, `X-Frame-Options`, and `Referrer-Policy`. |
|
|
259
|
+
| `request_logging` | `bool` | `False` | Emit status-dependent access logs with method, path, and request ID. |
|
|
260
|
+
| `compression_enabled` | `bool` | `True` | Enable gzip compression for eligible buffered responses. |
|
|
261
|
+
| `compression_threshold` | `int` | `1024` | Minimum buffered response size, in bytes, eligible for gzip. |
|
|
262
|
+
| `metrics_enabled` | `bool` | `True` | Serve basic request counters at `/metrics`. |
|
|
263
|
+
| `max_in_flight_requests` | `int` | `1000` | Process-level request cap; `0` disables this cap. |
|
|
264
|
+
| `max_header_size` | `int \| None` | `None` | Maximum aggregate request-header size; `None` uses 64 KiB. |
|
|
265
|
+
| `max_header_count` | `int \| None` | `None` | Maximum request header count; `None` uses 128. |
|
|
266
|
+
| `rate_limit_requests` | `int` | `0` | Requests allowed per fixed window and remote IP; `0` disables rate limiting. |
|
|
267
|
+
| `rate_limit_window_seconds` | `float` | `60` | Fixed-window duration when rate limiting is enabled. |
|
|
268
|
+
| `max_rate_limit_clients` | `int` | `10000` | Maximum tracked client IPs; must be positive when rate limiting is enabled. |
|
|
269
|
+
| `trusted_proxy_hosts` | `list[str] \| None` | `None` | IP addresses allowed to supply `X-Forwarded-For` and `X-Forwarded-Proto`. |
|
|
270
|
+
| `tls_cert_file` | `str \| None` | `None` | PEM certificate path. |
|
|
271
|
+
| `tls_key_file` | `str \| None` | `None` | PEM private-key path. Set both certificate and key to enable TLS. |
|
|
272
|
+
| `tls_handshake_timeout_seconds` | `float` | `10` | Maximum TLS handshake time. |
|
|
273
|
+
| `reuse_port` | `bool` | `False` | Allow multiple worker processes to bind the same address where supported. |
|
|
274
|
+
| `workers` | `int` | `1` | Number of Python worker subprocesses. |
|
|
275
|
+
| `worker_restart_limit` | `int` | `3` | Maximum worker restarts after non-zero exit. |
|
|
276
|
+
|
|
277
|
+
Invalid durations, limits, proxy addresses, or worker settings raise
|
|
278
|
+
`ValueError`. Listener and TLS initialization errors raise `OSError`.
|
|
279
|
+
`workers > 1` requires platform support for `SO_REUSEPORT`; each process has
|
|
280
|
+
independent app state, metrics, and rate-limit state.
|
|
281
|
+
|
|
282
|
+
The top-level convenience function `run(app, ...)` accepts the same server
|
|
283
|
+
options as keyword arguments, with the same defaults, except that `app` is
|
|
284
|
+
required as its first argument.
|
|
285
|
+
|
|
286
|
+
## CORS
|
|
287
|
+
|
|
288
|
+
CORS is disabled by default. It controls whether a browser may expose a
|
|
289
|
+
cross-origin response to frontend JavaScript; it is **not** authentication,
|
|
290
|
+
authorization, or a request firewall. A disallowed origin on a normal request
|
|
291
|
+
does not stop the request handler from running; the response simply has no
|
|
292
|
+
CORS allow-origin header. Enforce access permissions in application code.
|
|
293
|
+
|
|
294
|
+
| Option | Type | Default | Description |
|
|
295
|
+
| --- | --- | --- | --- |
|
|
296
|
+
| `cors_enabled` | `bool` | `False` | Enable CORS response headers and preflight handling. |
|
|
297
|
+
| `cors_allowed_origins` | `list[str] \| None` | `None` (no origins allowed) | Exact origins allowed, for example `https://app.example`. Use `"*"` only for non-credentialed public access. |
|
|
298
|
+
| `cors_allowed_methods` | `list[str] \| None` | `GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS` | Methods accepted in preflight requests. |
|
|
299
|
+
| `cors_allowed_headers` | `list[str] \| None` | `Authorization, Content-Type, Accept, Origin, X-Requested-With` | Headers accepted in preflight requests. |
|
|
300
|
+
| `cors_exposed_headers` | `list[str] \| None` | Empty | Response headers browser JavaScript may read. |
|
|
301
|
+
| `cors_allow_credentials` | `bool` | `False` | Include `Access-Control-Allow-Credentials: true`. |
|
|
302
|
+
| `cors_max_age` | `int` | `86400` | Preflight cache duration in seconds. |
|
|
303
|
+
|
|
304
|
+
Example:
|
|
305
|
+
|
|
306
|
+
```python
|
|
307
|
+
app.run(
|
|
308
|
+
host="127.0.0.1",
|
|
309
|
+
port=8080,
|
|
310
|
+
cors_enabled=True,
|
|
311
|
+
cors_allowed_origins=["https://frontend.example"],
|
|
312
|
+
cors_allowed_methods=["GET", "POST", "OPTIONS"],
|
|
313
|
+
cors_allowed_headers=["Authorization", "Content-Type"],
|
|
314
|
+
cors_exposed_headers=["X-Request-ID"],
|
|
315
|
+
cors_allow_credentials=True,
|
|
316
|
+
cors_max_age=600,
|
|
317
|
+
)
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
Origins are matched exactly; scheme, host, and port are significant. Preflight
|
|
321
|
+
`OPTIONS` requests are short-circuited with `204 No Content` when the origin,
|
|
322
|
+
requested method, and requested headers are allowed. A rejected CORS preflight
|
|
323
|
+
returns `403 Forbidden`. The default allowed request-header list includes
|
|
324
|
+
`Authorization`, so a browser can make a preflight request for bearer-token
|
|
325
|
+
headers once CORS is enabled.
|
|
326
|
+
|
|
327
|
+
For credentialed access, configure explicit origins rather than `"*"`. The
|
|
328
|
+
application must independently validate credentials and authorize requests.
|
|
329
|
+
For example:
|
|
330
|
+
|
|
331
|
+
```python
|
|
332
|
+
@app.get("/profile")
|
|
333
|
+
def profile(request):
|
|
334
|
+
authorization = request.headers.get("authorization")
|
|
335
|
+
if authorization != "Bearer expected-token":
|
|
336
|
+
return JsonResponse({"error": "unauthorized"}, status_code=401)
|
|
337
|
+
return {"user": "example"}
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
The example above is illustrative only; production authentication should use
|
|
341
|
+
an appropriate token-validation strategy and secret management.
|
|
342
|
+
|
|
343
|
+
## Command line
|
|
344
|
+
|
|
345
|
+
Run an importable application using `module:object` notation:
|
|
346
|
+
|
|
347
|
+
```sh
|
|
348
|
+
pyferrum run app:app --host 127.0.0.1 --port 8080
|
|
349
|
+
```
|
|
350
|
+
|
|
351
|
+
Useful options:
|
|
352
|
+
|
|
353
|
+
- `--dev` watches Python, Rust, and TOML project files and reloads after
|
|
354
|
+
changes.
|
|
355
|
+
- `--debug` enables debug-level server logs and access logging.
|
|
356
|
+
- `--host` and `--port` select the bind address.
|
|
357
|
+
|
|
358
|
+
The CLI validates Python sources and configured Rust routes before starting.
|
|
359
|
+
See `pyferrum run --help` for the installed version's options. Debug logging
|
|
360
|
+
does not expose handler tracebacks in HTTP responses.
|
|
361
|
+
|
|
362
|
+
## Runtime limits and security notes
|
|
363
|
+
|
|
364
|
+
- The default maximum request body is 10 MiB; bodies are buffered before
|
|
365
|
+
dispatch.
|
|
366
|
+
- The default header limits are 64 KiB total and 128 fields.
|
|
367
|
+
- The process-level request limit defaults to 1,000; Python handler
|
|
368
|
+
concurrency defaults to 100 per app.
|
|
369
|
+
- Rate limiting is disabled by default and is per process, not distributed.
|
|
370
|
+
- The metrics endpoint is a small built-in counter endpoint, not a full
|
|
371
|
+
Prometheus instrumentation suite.
|
|
372
|
+
- TLS uses PEM files and does not provide automatic certificate management
|
|
373
|
+
or client-certificate authentication.
|
|
374
|
+
- Forwarded metadata is honored only from configured proxy IPs. Do not trust
|
|
375
|
+
arbitrary client-provided forwarding headers.
|
|
376
|
+
- Native route plugins execute trusted native code in-process with the
|
|
377
|
+
server's privileges.
|
|
378
|
+
|
|
379
|
+
See [SECURITY.md](SECURITY.md) for reporting and security guidance.
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
# pyferrum architecture
|
|
2
|
+
|
|
3
|
+
This document describes the **implemented 1.0.0 design**. Planned work is
|
|
4
|
+
tracked separately in [ROADMAP.md](ROADMAP.md); a proposal is not a feature
|
|
5
|
+
commitment.
|
|
6
|
+
|
|
7
|
+
## Components
|
|
8
|
+
|
|
9
|
+
```text
|
|
10
|
+
Client
|
|
11
|
+
│ HTTP
|
|
12
|
+
▼
|
|
13
|
+
pyferrum worker process
|
|
14
|
+
├─ Hyper connection handling and Tokio runtime
|
|
15
|
+
├─ request limits, timeouts, rate limiting, IDs, metrics
|
|
16
|
+
├─ matchit router
|
|
17
|
+
├─ Rust handlers ── built-in health, static responses, redirects, plugins
|
|
18
|
+
└─ Python handler adapter (PyO3)
|
|
19
|
+
├─ sync callable on Tokio's blocking pool
|
|
20
|
+
└─ async callable submitted to the process-level asyncio loop
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
The Python package in `python/pyferrum` provides the application class,
|
|
24
|
+
decorators, route-file loader, and CLI. The native extension and Rust server
|
|
25
|
+
are in `crates/ferrum-core`. Rust-only handlers avoid Python dispatch; Python
|
|
26
|
+
handlers still execute Python code and follow normal CPython GIL behavior.
|
|
27
|
+
This design does not make Python business logic execute at Rust speed.
|
|
28
|
+
|
|
29
|
+
## Source layout
|
|
30
|
+
|
|
31
|
+
```text
|
|
32
|
+
Cargo.toml workspace metadata and shared dependencies
|
|
33
|
+
pyproject.toml Python package and maturin configuration
|
|
34
|
+
crates/ferrum-core/
|
|
35
|
+
src/
|
|
36
|
+
handler.rs Rust handler interface
|
|
37
|
+
router.rs method/path matching
|
|
38
|
+
request.rs, response.rs engine request and response types
|
|
39
|
+
json.rs JSON conversion helpers
|
|
40
|
+
python/ PyO3 app, handler, request, response, loop
|
|
41
|
+
server/
|
|
42
|
+
config.rs server defaults and limits
|
|
43
|
+
dispatch.rs per-request processing and response rendering
|
|
44
|
+
lifecycle.rs listener, TLS, connections, shutdown
|
|
45
|
+
metrics.rs request counters and rate limiter
|
|
46
|
+
native_abi.rs, plugins.rs native route ABI and trusted plugin loader
|
|
47
|
+
python/pyferrum/ public Python API and CLI
|
|
48
|
+
tests/ Rust/Python behavior and integration tests
|
|
49
|
+
example-app/ runnable app, including native routes
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Request lifecycle
|
|
53
|
+
|
|
54
|
+
1. The Tokio listener accepts a connection. If both TLS certificate and key
|
|
55
|
+
paths are configured, rustls performs a TLS handshake subject to its
|
|
56
|
+
handshake deadline.
|
|
57
|
+
2. Hyper parses the HTTP request. The engine rejects requests over the
|
|
58
|
+
configured header count or byte limit with `431`.
|
|
59
|
+
3. Request IDs are accepted from `X-Request-ID` when non-empty and at most
|
|
60
|
+
128 characters; otherwise the server generates one. Optional request
|
|
61
|
+
logging records the response status, method, path (without the query
|
|
62
|
+
string), and request ID after a response is selected, including early
|
|
63
|
+
rejections. The log level is INFO for 1xx/2xx, DEBUG for 3xx, WARN for
|
|
64
|
+
4xx or nonstandard 6xx-9xx, and ERROR for 5xx, subject to `RUST_LOG`
|
|
65
|
+
filtering. For streaming responses this is the initial status; body errors
|
|
66
|
+
may occur after the access log.
|
|
67
|
+
4. CORS is disabled by default. When enabled, exact allowed origins receive
|
|
68
|
+
`Access-Control-Allow-Origin`; credentialed wildcard use echoes the request
|
|
69
|
+
origin. Browser `OPTIONS` preflight requests are checked against configured
|
|
70
|
+
methods and headers (including `Authorization` by default) and are
|
|
71
|
+
short-circuited before routing.
|
|
72
|
+
5. The fixed-window per-IP limiter runs if enabled. A `/metrics` request is
|
|
73
|
+
served by Rust when metrics are enabled.
|
|
74
|
+
6. The process-level in-flight request cap is acquired. The body is then
|
|
75
|
+
buffered under the 10 MiB default and body-read deadline. Oversized bodies
|
|
76
|
+
receive `413`; body-read failures receive `400`; body timeouts receive
|
|
77
|
+
`504`.
|
|
78
|
+
7. The router matches method and path, extracts path parameters, and returns
|
|
79
|
+
`404` or `405` for unmatched requests.
|
|
80
|
+
8. A Rust handler responds in the engine, or the Python adapter invokes the
|
|
81
|
+
Python callable. Synchronous callables run on Tokio's blocking pool.
|
|
82
|
+
Asynchronous callables are submitted to a persistent asyncio loop running
|
|
83
|
+
on a dedicated thread shared by the process.
|
|
84
|
+
9. Supported Python return values are converted to Rust responses. JSON
|
|
85
|
+
values use the engine's serde-based conversion; supported values include
|
|
86
|
+
dictionaries, lists, tuples, strings, bytes, `Response`, and
|
|
87
|
+
`StreamingResponse`.
|
|
88
|
+
10. The engine adds response headers such as `X-Request-ID`, the configured
|
|
89
|
+
`Server` value, and the default security headers. Eligible buffered
|
|
90
|
+
responses may be gzipped. Hyper writes the result to the connection.
|
|
91
|
+
|
|
92
|
+
The request body is fully buffered before route dispatch. Streaming is
|
|
93
|
+
currently a **response-only** facility: an async iterator may yield bytes or
|
|
94
|
+
strings, and a bounded channel applies backpressure to its producer. This
|
|
95
|
+
does not provide streaming request bodies or guarantee cancellation of
|
|
96
|
+
synchronous Python work after a timeout.
|
|
97
|
+
|
|
98
|
+
Python response helpers provide HTML and XML from caller-serialized text,
|
|
99
|
+
CSV serialization, buffered file downloads, redirects, and SSE framing on
|
|
100
|
+
the existing async response stream. File downloads read the entire file into
|
|
101
|
+
memory and do not implement ranges. SSE connections are still subject to the
|
|
102
|
+
configured connection lifetime and shutdown deadline; reconnection and
|
|
103
|
+
event replay are the application's responsibility.
|
|
104
|
+
|
|
105
|
+
## Python boundary and concurrency
|
|
106
|
+
|
|
107
|
+
The handler adapter owns invocation and result conversion. For async handlers,
|
|
108
|
+
the adapter schedules the coroutine on the process-level event loop rather
|
|
109
|
+
than creating a new loop for each request. The event loop is not one loop per
|
|
110
|
+
app or per worker thread.
|
|
111
|
+
|
|
112
|
+
Two independent limits bound work:
|
|
113
|
+
|
|
114
|
+
- `Ferrum(max_python_in_flight=100)` limits concurrent Python handler work per
|
|
115
|
+
application instance. Saturated Python dispatch receives `503`.
|
|
116
|
+
- `app.run(max_in_flight_requests=1000)` limits process-level in-flight HTTP
|
|
117
|
+
requests. Set it to `0` to disable this cap.
|
|
118
|
+
|
|
119
|
+
`request_timeout_seconds` bounds handler response time. A timeout returns
|
|
120
|
+
`504`; it is not a general-purpose way to forcibly stop synchronous Python
|
|
121
|
+
code. Request bodies, connections, TLS handshakes, and shutdown have separate
|
|
122
|
+
deadlines.
|
|
123
|
+
|
|
124
|
+
## Implemented server controls
|
|
125
|
+
|
|
126
|
+
The Python `app.run()` API exposes server options. Relevant defaults and
|
|
127
|
+
behavior:
|
|
128
|
+
|
|
129
|
+
| Control | Default | Behavior |
|
|
130
|
+
| --- | ---: | --- |
|
|
131
|
+
| Request body size | 10 MiB | Engine limit; not currently configurable through the Python `run()` API. |
|
|
132
|
+
| Body/request deadlines | 30 seconds each | Expired body or handler work returns `504`. |
|
|
133
|
+
| Connection lifetime | 120 seconds | Bounds an accepted connection. |
|
|
134
|
+
| Shutdown drain | 10 seconds | Stops accepting and drains active connections until the deadline. |
|
|
135
|
+
| Header size/count | 64 KiB / 128 | Can be overridden through `app.run()`. |
|
|
136
|
+
| Process in-flight requests | 1,000 | `0` disables the cap. |
|
|
137
|
+
| Python handler concurrency | 100 | Configured on `Ferrum(...)`; excess work receives `503`. |
|
|
138
|
+
| Rate limiting | Disabled | Fixed-window, per remote IP; configure with `rate_limit_requests` and `rate_limit_window_seconds`. |
|
|
139
|
+
| Security headers | Enabled | Emits `X-Content-Type-Options`, `X-Frame-Options`, and `Referrer-Policy`. |
|
|
140
|
+
| CORS | Disabled | Exact-origin allowlist, preflight methods/headers, exposed headers, credentials, and max-age. |
|
|
141
|
+
| Gzip | Enabled | Applies to buffered responses meeting the threshold when the client accepts gzip. |
|
|
142
|
+
| Metrics | Enabled | `/metrics` exposes request total and in-flight counters. |
|
|
143
|
+
| TLS | Disabled | Configure both `tls_cert_file` and `tls_key_file` to enable PEM-based TLS. |
|
|
144
|
+
|
|
145
|
+
Rate limiting is per process and is not a distributed limiter. Its in-memory
|
|
146
|
+
client table is bounded. The metrics endpoint exposes a small set of counters,
|
|
147
|
+
not a full Prometheus instrumentation suite.
|
|
148
|
+
|
|
149
|
+
## Routes that stay in Rust
|
|
150
|
+
|
|
151
|
+
Python decorators register Python handlers. The `Ferrum` wrapper also exposes
|
|
152
|
+
these startup-time Rust routes:
|
|
153
|
+
|
|
154
|
+
- `app.static_file(path, file_path, content_type=..., method="GET")` reads the
|
|
155
|
+
file at registration and serves the in-memory bytes.
|
|
156
|
+
- `app.redirect(path, location, status_code=302)` registers a GET redirect.
|
|
157
|
+
- `app.load_routes(...)` can load a TOML `[[routes]]` table. Python handlers
|
|
158
|
+
must be supplied explicitly; built-in Rust handler names are `health`,
|
|
159
|
+
`liveness`, and `readiness`.
|
|
160
|
+
- The CLI can build and load an optional native `cdylib` configured by
|
|
161
|
+
`[tool.pyferrum].rust_manifest`.
|
|
162
|
+
|
|
163
|
+
Native plugins use the versioned JSON-byte ABI in `native_abi.rs`. They are
|
|
164
|
+
synchronous, buffered, execute in-process, and are **not sandboxed**. Plugin
|
|
165
|
+
code runs with the server process's privileges. Plugin response buffers are
|
|
166
|
+
limited to 128 MiB; only load code you trust.
|
|
167
|
+
|
|
168
|
+
## Workers and deployment
|
|
169
|
+
|
|
170
|
+
`app.run(workers=N)` starts N application subprocesses and uses
|
|
171
|
+
`SO_REUSEPORT` to share the listening address on supported Unix platforms.
|
|
172
|
+
Each worker has its own Python interpreter, GIL, Tokio runtime, and app state.
|
|
173
|
+
The lightweight parent restarts a worker that exits non-zero up to
|
|
174
|
+
`worker_restart_limit`; it is not a general-purpose process supervisor.
|
|
175
|
+
|
|
176
|
+
Use one worker where `SO_REUSEPORT` is unavailable or unverified. A reverse
|
|
177
|
+
proxy or external process manager may be used for TLS termination, traffic
|
|
178
|
+
distribution, and supervision. Forwarded client metadata is used only when
|
|
179
|
+
the connecting proxy IP is in `trusted_proxy_hosts`; do not trust arbitrary
|
|
180
|
+
client-supplied forwarding headers.
|
|
181
|
+
|
|
182
|
+
Native TLS reads PEM certificate/key files at startup. Certificate rotation
|
|
183
|
+
requires restarting workers. TLS does not configure client-certificate
|
|
184
|
+
authentication or automatic certificate provisioning. The documented and
|
|
185
|
+
integration-tested protocol contract is HTTP/1.1; explicit HTTP/2 TLS ALPN
|
|
186
|
+
configuration and protocol integration coverage remain roadmap work.
|
|
187
|
+
|
|
188
|
+
## Extension boundaries
|
|
189
|
+
|
|
190
|
+
`crates/ferrum-core/src/handler.rs` defines the Rust handler interface.
|
|
191
|
+
Pure-Rust routes can implement it without Python. Python route handlers use
|
|
192
|
+
the PyO3 adapter. CORS is an engine-level server policy rather than a general
|
|
193
|
+
Python middleware extension. The public extension boundary does not include an
|
|
194
|
+
ASGI/WSGI adapter or request-body streaming API; see [ROADMAP.md](ROADMAP.md)
|
|
195
|
+
for possible future work.
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
Notable changes are recorded here. This project follows
|
|
4
|
+
[Semantic Versioning](https://semver.org/spec/v2.0.0.html) and the
|
|
5
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/) format.
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- Configurable CORS origin, method, request-header, credential, exposed-header,
|
|
12
|
+
and preflight max-age controls. `Authorization` is allowed by the default
|
|
13
|
+
CORS request-header policy and remains available to Python handlers through
|
|
14
|
+
`Request.headers`.
|
|
15
|
+
- Python response helpers for HTML, XML, CSV, file downloads, redirects, and
|
|
16
|
+
server-sent events over the existing streaming response support.
|
|
17
|
+
|
|
18
|
+
## [1.0.0] - 2026-11-27
|
|
19
|
+
|
|
20
|
+
The first stable 1.x public API baseline. This release reflects the current
|
|
21
|
+
implemented feature set; it does not claim compatibility with ASGI/WSGI
|
|
22
|
+
frameworks or feature parity with FastAPI, Flask, or Django.
|
|
23
|
+
|
|
24
|
+
### Added
|
|
25
|
+
|
|
26
|
+
- Tokio/Hyper HTTP server, method/path routing, sync and async Python handlers,
|
|
27
|
+
and a process-level asyncio event loop.
|
|
28
|
+
- Rust JSON conversion, Python request/response types, and async response
|
|
29
|
+
streaming with bounded backpressure.
|
|
30
|
+
- Request/body/connection/shutdown timeouts, body/header limits, bounded
|
|
31
|
+
concurrency, request IDs, optional fixed-window IP rate limiting, and
|
|
32
|
+
default security headers.
|
|
33
|
+
- Optional PEM-based TLS, trusted-proxy forwarding, gzip for eligible
|
|
34
|
+
buffered responses, and a basic Prometheus-format `/metrics` endpoint.
|
|
35
|
+
- TOML route loading, Rust built-in health handlers, static-file and redirect
|
|
36
|
+
routes, and synchronous native route plugins.
|
|
37
|
+
- Python CLI runner and optional worker subprocesses using `SO_REUSEPORT` on
|
|
38
|
+
supported Unix platforms.
|
|
39
|
+
- Updated architecture, roadmap, security, and contribution documentation.
|
|
40
|
+
|
|
41
|
+
### Packaging
|
|
42
|
+
|
|
43
|
+
- Python package and Rust workspace version set to `1.0.0`.
|
|
44
|
+
- MIT License; this project is not dual-licensed under Apache-2.0.
|
|
45
|
+
- CPython abi3 extension targeting CPython 3.8 and newer. CI tests CPython
|
|
46
|
+
3.8, 3.10, 3.12, and 3.13.
|
|
47
|
+
|
|
48
|
+
### Limitations
|
|
49
|
+
|
|
50
|
+
- No ASGI/WSGI hosting, built-in authentication or CSRF middleware,
|
|
51
|
+
OpenAPI generation, ORM, WebSockets, server-sent events, or HTTP/3.
|
|
52
|
+
- Request bodies are buffered. HTTP/2 TLS ALPN behavior is not yet documented
|
|
53
|
+
as supported or covered by integration tests.
|
|
54
|
+
- Native plugins execute synchronously in-process and are trusted code.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Code of Conduct
|
|
2
|
+
|
|
3
|
+
Participation in pyferrum is expected to be respectful and constructive.
|
|
4
|
+
Examples of unacceptable behavior include harassment, personal attacks,
|
|
5
|
+
discrimination, threats, and publishing another person's private information
|
|
6
|
+
without permission.
|
|
7
|
+
|
|
8
|
+
Project participants should:
|
|
9
|
+
|
|
10
|
+
- Discuss technical disagreements without attacking people.
|
|
11
|
+
- Give useful, specific feedback and be open to good-faith correction.
|
|
12
|
+
- Respect different experience levels and backgrounds.
|
|
13
|
+
- Keep project spaces focused on pyferrum and its contributors.
|
|
14
|
+
|
|
15
|
+
If you experience or witness unacceptable behavior, contact the repository
|
|
16
|
+
maintainers privately through GitHub. Do not post personal details in public
|
|
17
|
+
issues. Maintainers may remove content or restrict participation when
|
|
18
|
+
necessary to keep the project safe and welcoming.
|
|
19
|
+
|