flpit-stoop 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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 riemar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,254 @@
1
+ Metadata-Version: 2.4
2
+ Name: flpit-stoop
3
+ Version: 0.1.0
4
+ Summary: FastAPI-style web framework on the flpit Task runtime, served by Granian with loop-free Kestrel-style dispatch
5
+ Keywords: web,framework,api,fastapi,granian,flpit,rsgi,dependency-injection,free-threading
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Programming Language :: Python :: 3.15
16
+ Classifier: Programming Language :: Python :: Free Threading :: 2 - Beta
17
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
18
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
19
+ Classifier: Typing :: Typed
20
+ Requires-Dist: flpit>=0.5.0,<0.6
21
+ Requires-Dist: granian>=2.8.9,<2.9
22
+ Requires-Python: >=3.12
23
+ Project-URL: Homepage, https://github.com/riemar/flpit-stoop
24
+ Project-URL: Repository, https://github.com/riemar/flpit-stoop
25
+ Project-URL: Issues, https://github.com/riemar/flpit-stoop/issues
26
+ Description-Content-Type: text/markdown
27
+
28
+ # flpit-stoop
29
+
30
+ A FastAPI-style web framework that runs on the [flpit](https://pypi.org/project/flpit/) Task runtime and is served by [Granian](https://github.com/emmett-framework/granian), using Kestrel's execution model: **one process, no asyncio event loop in the request path**.
31
+
32
+ *A stoop is the falcon's high-speed dive. The name comes from the kestrel, a falcon, which is also where ASP.NET's Kestrel server got its name.*
33
+
34
+ ```bash
35
+ pip install flpit-stoop # or: uv add flpit-stoop
36
+ ```
37
+
38
+ The distribution is `flpit-stoop`; the code lives in the `flpit.stoop` package next to flpit itself (`from flpit.stoop import Stoop`). It installs a `stoop` command (also available as `flpit-stoop`). Requires flpit ≥ 0.5.0: its package is extensible (`pkgutil.extend_path`), so `flpit.stoop` also imports from editable/dev installs, and it has the public `ThreadPool.queue` stoop dispatches with.
39
+
40
+ ```python
41
+ from dataclasses import dataclass
42
+ from flpit.stoop import Stoop, CancellationToken, Task
43
+
44
+ app = Stoop(title="Shop")
45
+
46
+ @dataclass
47
+ class Item:
48
+ item_id: int
49
+ name: str
50
+
51
+ @app.get("/items/{item_id:int}")
52
+ def get_item(item_id: int, verbose: bool = False) -> Item: # sync: runs on a pool worker
53
+ return Item(item_id, "widget")
54
+
55
+ @app.post("/items", status_code=201)
56
+ async def create(item: Item, token: CancellationToken) -> Item: # cancelled if the client leaves
57
+ await Task.delay(0.1, token=token)
58
+ return item
59
+
60
+ if __name__ == "__main__":
61
+ app.run(port=8000) # Swagger UI at /docs
62
+ ```
63
+
64
+ ```bash
65
+ uv run stoop run myapp:app --port 8000 # loop-free direct host (default)
66
+ uv run stoop run myapp:app --host-mode rsgi # Granian's standard embedded RSGI server
67
+ uv run granian --interface rsgi myapp:app # stock Granian CLI works too
68
+ ```
69
+
70
+ ## How it runs
71
+
72
+ ```
73
+ Granian (Rust / tokio) flpit Task runtime (Python thread pool)
74
+ ────────────────────────────────── ─────────────────────────────────────────
75
+ accept · TLS · HTTP/1 + HTTP/2 · WS ──► schedule(watcher): match route
76
+ ├─ sync route → plain pool work item
77
+ └─ async route → Task.run (one hop)
78
+ body bytes · disconnect · ws frames ──► FlpitLoop.call_soon* → TaskCompletionSource
79
+ response channel ◄── proto.response_*() straight from the worker
80
+ ```
81
+
82
+ * **Single process, threads only.** Granian's `RSGIWorker` runs in multi-threaded runtime mode inside the current process (`flpit.stoop.server.Server`). Granian's processes, workers and asyncio loops are not used.
83
+ * **No event loop in between.** Granian normally sends each request to an asyncio loop. stoop installs its own `CallbackScheduler`, which posts the request straight onto the flpit pool. Granian's future-like objects (request body, `client_disconnect()`, WebSocket `accept`/`receive`) complete through `FlpitLoop`, a loop shim that completes flpit `TaskCompletionSource`s. The awaiting coroutine then resumes on the pool.
84
+ * **Kestrel model.** Granian's Rust threads do the I/O. Application code runs on a thread pool modelled on .NET's: coroutines resume on any worker, and blocking code may run on a worker (the pool injects more threads if workers block). On free-threaded Python (3.14t) the workers run in parallel.
85
+ * **Synchronous fast path.** A sync endpoint with no request body and no middleware is matched, bound, executed, serialised and written in one pool work item. No coroutine and no Task object is created for it.
86
+ * **Responses are written from the worker.** Granian's `response_*` calls are thread-safe Rust calls, so sending a response needs no thread hop.
87
+ * **Everything per request is lazy.** Query parsing, the body, the DI scope and the disconnect watch are only set up when something uses them.
88
+
89
+ The standard `app.__rsgi__` interface is still available for portability. In that mode, request I/O is bridged to the asyncio loop thread and costs one loop→pool hop per request.
90
+
91
+ ## Features
92
+
93
+ | | |
94
+ |---|---|
95
+ | Routing | decorators per method, route groups (`Router(prefix, tags, middleware, timeout)`), ASP.NET-style constraints `{id:int}`, `{id:uuid}`, `{path:path}`. Static routes are matched with an O(1) dict lookup, dynamic ones with a segment trie |
96
+ | Parameters | inferred like FastAPI (path → query → body), or explicit with `Path/Query/Header/Cookie/Body/FromServices` (as defaults or in `Annotated`). Conversion uses msgspec. All errors are collected into one 400 response in ASP.NET Core's `ValidationProblemDetails` shape (`errors`: parameter name → messages). The individual errors stay available as `RequestValidationError.details` |
97
+ | JSON | Request bodies must be sent as `application/json` or a `+json` type (415 otherwise, as in ASP.NET Core: JSON read from `text/plain` would skip the browser's CORS preflight). **flpit.json** (`JsonConvert`) for dataclasses and `list[dataclass]`, using the app's `JsonSerializerOptions` (camelCase by default). msgspec for everything else, including msgspec `Struct`s. Encoders and decoders are compiled per route from the annotations |
98
+ | DI | `ServiceCollection` / `ServiceProvider` with singleton, scoped (per request) and transient lifetimes; keyed services; `list[T]`; optional services; validation at build time (missing services, cycles, captive dependencies); disposal in reverse order (sync and async); `create_instance` (ActivatorUtilities) |
99
+ | Proxying | `decorate(IService, Wrapper)`: Scrutor-style decorators that implement the same interface and receive the previous implementation (they stack). `intercept(IService, *interceptors)`: generated dispatch proxies (`isinstance(proxy, IService)` is true) for sync and async methods |
100
+ | Cancellation | `token: CancellationToken` parameter (or `request.cancellation_token`). The token is cancelled when the client disconnects (`HttpContext.RequestAborted`) or when the route timeout elapses. A timeout produces 504, a disconnect produces 499 |
101
+ | Middleware | `async def mw(request, call_next)`. App middleware wraps routing, so it also sees 404/405 and CORS preflight requests. Group and route middleware wrap a single endpoint. Middleware classes get constructor injection. Built in: `CORSMiddleware`, `ConcurrencyLimiter` (flpit `SemaphoreSlim`, FIFO queue, 503), `ServerTimingMiddleware` |
102
+ | Slow-client protection | Request bodies must arrive at a minimum data rate: by default 1 KiB/s after a 10 s grace period. This catches stalled clients and clients trickling data just fast enough to dodge an idle timeout; both get 408 and the connection is closed. A shared once-a-second heartbeat (as in Kestrel) checks the deadlines, so a request pays only a set insert and removal while it waits for body data. Change it with `Stoop(min_body_rate=MinDataRate(...))`, per group or per route; `None` turns it off. Granian already limits header reading to 30 s |
103
+ | Forms and uploads | `Form()` fields and `UploadFile` parameters (single, optional or `list[UploadFile]`) from `multipart/form-data` or `application/x-www-form-urlencoded` bodies. `await request.form()` gives the raw `FormData`. Uploads are held in memory, bounded by the body size limit. A form has at most 1,000 fields and files (Starlette's limit; ASP.NET Core's `FormOptions` allow 1,024 values), and a text field at most 4 MiB (as `FormOptions.ValueLengthLimit`); beyond either, 413. OpenAPI describes them as form bodies |
104
+ | Body size limit | 30 MB by default. Change it with `Stoop(max_body_size=...)`, per group with `Router(max_body_size=...)`, or per route with `@app.post(..., max_body_size=...)`. `UNLIMITED` turns it off. Requests with a larger `Content-Length` are rejected before any body is read; chunked bodies are counted while reading. Either case returns 413 |
105
+ | Results | return values, `Response`, `JSONResponse`, `PlainTextResponse`, `HTMLResponse`, `RedirectResponse`, `FileResponse` (served by Granian from disk), `StreamingResponse` (sync and async iterables, `AsyncFlpIt` queries), `EventStreamResponse` (server-sent events), `Results.*` helpers |
106
+ | Static files | `app.static_files("/static", "wwwroot")` (ASP.NET Core's `UseStaticFiles`), also on a `Router`, with route options. Granian sends the file from disk. Safe by default: nothing outside the directory (`..`, encoded or not, backslashes, drive letters, symlinks leading out), no dotfiles, no directory listings, and only web content types from a fixed table (no `.py`, `.toml`, backups). `ETag`/`Last-Modified` with 304, single byte ranges for media seeking |
107
+ | Errors | RFC 9457 problem details. `HTTPException(status, detail, headers, **extensions)`. Exception handlers (sync or async) are looked up along the exception's MRO. `debug=True` adds tracebacks |
108
+ | WebSockets | `@app.websocket("/ws/{room}")` with the same parameter binding; `accept`, `receive*`, `send_text/bytes/json`, `close`, `async for` |
109
+ | Hosting | `on_startup` / `on_shutdown`; hosted services (`BackgroundService.execute(stopping_token)`); health checks (`/healthz`, run concurrently with `Task.when_all`-style tasks); graceful drain on stop |
110
+ | OpenAPI | `/openapi.json` (OpenAPI 3.1, with schemas generated from flpit's wire types so names follow the naming policy) and Swagger UI at `/docs` |
111
+ | Testing | `flpit.stoop.testing.TestServer` (ASP.NET Core's `TestServer`) drives the real dispatch code with no sockets: `with TestServer(app) as server: client = server.create_client()`. `client.start(...)` plus `.disconnect()` tests cancellation |
112
+
113
+ ### Dependency injection with decorators and proxies
114
+
115
+ ```python
116
+ services = ServiceCollection()
117
+ services.add_singleton(AuditLog)
118
+ services.add_singleton(TodoRepository, InMemoryTodoRepository)
119
+ services.decorate(TodoRepository, AuditingTodoRepository) # __init__(self, inner: TodoRepository, audit: AuditLog)
120
+ services.intercept(TodoRepository, TimingInterceptor) # interceptor types are built through DI too
121
+ services.add_scoped(UnitOfWork) # one per request, disposed after the response
122
+
123
+ app = Stoop(services=services)
124
+
125
+ @app.get("/todos")
126
+ def todos(repo: TodoRepository) -> list[Todo]: # registered types are injected automatically
127
+ return repo.all()
128
+ ```
129
+
130
+ An interceptor is a callable `(invocation) -> result`, or an object with `intercept(invocation)`. Call `invocation.proceed()` to continue the chain. For async methods, `proceed()` returns an awaitable and the interceptor can be `async def`.
131
+
132
+ ### asyncio clients: one per loop
133
+
134
+ Prefer a library's sync client (one shared `httpx.Client`). For libraries that only exist for asyncio, register the client per loop. asyncio clients belong to one event loop, and flpit's asyncio bridge runs several loops, so the container keeps one instance per loop:
135
+
136
+ ```python
137
+ from flpit.asyncio_bridge import PerLoop
138
+ from flpit.task import asyncio_task
139
+
140
+ services.add_per_loop(httpx.AsyncClient, factory=lambda: httpx.AsyncClient(timeout=10), warm=True)
141
+ services.add_singleton(GitHubApi)
142
+
143
+ class GitHubApi:
144
+ def __init__(self, clients: PerLoop[httpx.AsyncClient]) -> None: # not the client itself
145
+ self._clients = clients
146
+
147
+ @asyncio_task
148
+ async def repo(self, name: str, token: CancellationToken) -> dict: # a client disconnect cancels it
149
+ return (await self._clients.current.get(f"https://api.github.com/repos/{name}")).json()
150
+ ```
151
+
152
+ - **Captive check:** a singleton, scoped or transient service that takes the client itself fails when the container is built. It would keep one loop's client; the error points to `PerLoop[...]`. Per-loop services may take it directly.
153
+ - **`warm=True`:** creates the client on every loop before the loop takes work.
154
+ - **Closing:** the clients close with their loop and when the app shuts down.
155
+ - **`Loop[T]` parameters:** `@asyncio_task` functions with `client: Loop[httpx.AsyncClient] = injected` receive the same instances.
156
+ - **Thread-safe async clients:** a client like pyreqwest's `Client` needs none of this. Register it as a plain singleton.
157
+
158
+ ### Cooperative cancellation
159
+
160
+ ```python
161
+ @app.get("/report", timeout=5.0) # 504 after 5 s
162
+ async def report(token: CancellationToken):
163
+ async for row in rows(): # stops as soon as the client goes away
164
+ token.throw_if_cancellation_requested()
165
+ await Task.delay(0.01, token=token)
166
+
167
+ @app.get("/crunch")
168
+ def crunch(token: CancellationToken): # blocking code polls the token
169
+ while not token.is_cancellation_requested:
170
+ step()
171
+ ```
172
+
173
+ The disconnect watch is only started when a handler asks for the token, so endpoints that never use it pay nothing.
174
+
175
+ See [`examples/todo_app.py`](examples/todo_app.py) for an app that uses all of the above.
176
+
177
+ ## Server options
178
+
179
+ ```python
180
+ from flpit.stoop.server import Server
181
+
182
+ with Server(app, host="0.0.0.0", port=8000,
183
+ runtime_threads=2, # tokio I/O threads
184
+ min_workers=16, max_workers=256, # flpit pool (Task.configure)
185
+ http="auto", websockets=True,
186
+ ssl_cert="cert.pem", ssl_key="key.pem") as server:
187
+ ...
188
+ ```
189
+
190
+ `Server.start()` returns once the server is listening. `port=0` picks a free port. `stop()` stops accepting connections, drains requests that are in flight, then runs app shutdown.
191
+
192
+ `STOOP_DISPATCH=task` forces dispatch through the public `Task.run` only (see "Internals used" below).
193
+
194
+ ## Benchmarks
195
+
196
+ ### stoop vs. standard FastAPI
197
+
198
+ `uv run --group bench python bench/compare_fastapi.py` (options and setup in [`bench/README.md`](bench/README.md)) compares stoop with the stack most FastAPI apps run on: `fastapi[standard]` served by uvicorn with uvloop and httptools, which is what `fastapi run` uses. All versions are the latest releases: FastAPI 0.165.0, uvicorn 0.54.0, uvloop 0.23.0, pydantic 2.14.4, starlette 1.10.0.
199
+
200
+ Both apps implement the same endpoints the idiomatic way for each framework (dataclasses for stoop, pydantic models for FastAPI; `def` endpoints for sync, `async def` for async). Access logs are off on both. Each cell is the median of 3 runs of 4 s with 32 keep-alive connections.
201
+
202
+ | req/s · **Python 3.13** | plaintext | json | async | params |
203
+ |---|---:|---:|---:|---:|
204
+ | stoop (direct host) | 34,100 | 35,497 | 20,097 | 33,852 |
205
+ | FastAPI + uvicorn | 5,154 | 3,346 | 10,185 | 2,951 |
206
+ | FastAPI + uvicorn, 2 workers | 11,164 | 3,478 | 16,161 | 7,438 |
207
+ | **stoop ÷ FastAPI (1 worker)** | **6.6×** | **10.6×** | **2.0×** | **11.5×** |
208
+
209
+ | req/s · **Python 3.14t** (free-threaded) | plaintext | json | async | params |
210
+ |---|---:|---:|---:|---:|
211
+ | stoop (direct host) | 33,434 | 30,658 | 19,882 | 28,987 |
212
+ | FastAPI + uvicorn | 6,968 | 4,564 | 9,643 | 3,963 |
213
+ | FastAPI + uvicorn, 2 workers | 8,779 | 4,600 | 15,704 | 4,874 |
214
+ | **stoop ÷ FastAPI (1 worker)** | **4.8×** | **6.7×** | **2.1×** | **7.3×** |
215
+
216
+ The endpoints are: `plaintext` returns a fixed string, `json` returns one object, `async` is an `async def` that returns one object, and `params` is `GET /items/{id}?q=&limit=`, which binds a path parameter and query parameters into an object.
217
+
218
+ * The biggest gaps are on sync `def` endpoints. FastAPI sends each one through anyio's thread pool and back to the event loop. stoop runs them in a single pool work item with no coroutine.
219
+ * On `async def` endpoints FastAPI is at its best, because the request stays on the event loop, and stoop is still about 2× faster.
220
+
221
+ **With a native load generator.** The tables above were measured with the Python load generator. A later run on the same 2-vCPU sandbox used `oha` (Python 3.14t, 64 connections, 3 s, 1 round), with the server pinned to one core and `oha` to the other:
222
+
223
+ | req/s · 1 server core | plaintext | json | async | params |
224
+ |---|---:|---:|---:|---:|
225
+ | flpit-stoop | 54,234 | 43,380 | 25,024 | 34,408 |
226
+ | FastAPI + uvicorn | 5,158 | 3,558 | 9,819 | 2,849 |
227
+
228
+ p99 latency was 2.5–4.9 ms for flpit-stoop and 10–45 ms for FastAPI. For real hardware see [`bench/README.md`](bench/README.md).
229
+
230
+ **Caveats.** These numbers come from a **2-vCPU sandbox**. The Python load generator runs on the same CPUs and tops out at about 35k req/s, so it caps stoop's numbers. Without a network, an in-process microbenchmark of stoop's dispatcher alone reaches about 90–120k req/s. Treat the table as a relative comparison, and rerun it on your own hardware with a native load tool such as `wrk` or `oha` for absolute numbers.
231
+
232
+ ### Host modes
233
+
234
+ `uv run --group bench python bench/run.py` compares stoop's two hosts with FastAPI running on Granian. stoop's RSGI fallback mode sends each request through an asyncio loop first, so it reaches only about 10–11k req/s in this setup, compared with about 30–36k for the direct host.
235
+
236
+ ## Internals used, and known limitations
237
+
238
+ * **Granian internals.** The direct host uses `CallbackScheduler._schedule_fn`, `RSGIWorker(...)`/`serve_mtr`, `WorkerSignal` and the duck-typed loop Granian calls `call_soon*` on. For that reason the Granian dependency is pinned to `>=2.8.9,<2.9`. `app.__rsgi__` uses only public RSGI.
239
+ * **flpit.json** handles dataclasses only, and by default leaves out fields that equal their default value (`JsonDefaultHandling.exclude`). Set `json_options=JsonSerializerOptions(default_handling=JsonDefaultHandling.include)` to include them.
240
+ * **WebSocket close on the RSGI host.** On the RSGI fallback host (`--host-mode rsgi`), the server's WebSocket close frame isn't sent; the client finishes when its own close timeout expires. Plain Granian RSGI apps show the same with uvloop. The direct host isn't affected.
241
+ * Endpoints whose annotations refer to classes defined *inside a function*, combined with `from __future__ import annotations`, cannot be resolved. This is the same limitation FastAPI has.
242
+ * **asyncio libraries in handlers.** The direct host runs no asyncio event loop, so asyncio-based libraries (asyncpg, httpx's async client, redis.asyncio, aiohttp, ...) can't be called directly in a handler ("no running event loop"). Call them through flpit's `@asyncio_task`, with clients registered per loop: see [asyncio clients: one per loop](#asyncio-clients-one-per-loop). Where a library has a sync client, prefer it: sync handlers run on pool workers, in parallel on free-threaded Python.
243
+ * Sync endpoints run on pool workers. Long blocking calls make the pool inject threads, as in .NET.
244
+
245
+ ## Development
246
+
247
+ ```bash
248
+ uv sync
249
+ uv run pytest # free-threaded 3.14t (project default)
250
+ UV_PROJECT_ENVIRONMENT=.venv-3.13 uv run --python 3.13 pytest # GIL build
251
+ uvx ruff check src tests bench
252
+ ```
253
+
254
+ The 118 tests cover the DI container, routing, binding, the app pipeline, OpenAPI, the I/O bridges, the dispatcher, the CLI and the example app. They also include end-to-end socket tests that run against **both** hosts: keep-alive, large bodies, concurrency, streaming, disconnect-driven cancellation, WebSockets, and graceful drain.
@@ -0,0 +1,227 @@
1
+ # flpit-stoop
2
+
3
+ A FastAPI-style web framework that runs on the [flpit](https://pypi.org/project/flpit/) Task runtime and is served by [Granian](https://github.com/emmett-framework/granian), using Kestrel's execution model: **one process, no asyncio event loop in the request path**.
4
+
5
+ *A stoop is the falcon's high-speed dive. The name comes from the kestrel, a falcon, which is also where ASP.NET's Kestrel server got its name.*
6
+
7
+ ```bash
8
+ pip install flpit-stoop # or: uv add flpit-stoop
9
+ ```
10
+
11
+ The distribution is `flpit-stoop`; the code lives in the `flpit.stoop` package next to flpit itself (`from flpit.stoop import Stoop`). It installs a `stoop` command (also available as `flpit-stoop`). Requires flpit ≥ 0.5.0: its package is extensible (`pkgutil.extend_path`), so `flpit.stoop` also imports from editable/dev installs, and it has the public `ThreadPool.queue` stoop dispatches with.
12
+
13
+ ```python
14
+ from dataclasses import dataclass
15
+ from flpit.stoop import Stoop, CancellationToken, Task
16
+
17
+ app = Stoop(title="Shop")
18
+
19
+ @dataclass
20
+ class Item:
21
+ item_id: int
22
+ name: str
23
+
24
+ @app.get("/items/{item_id:int}")
25
+ def get_item(item_id: int, verbose: bool = False) -> Item: # sync: runs on a pool worker
26
+ return Item(item_id, "widget")
27
+
28
+ @app.post("/items", status_code=201)
29
+ async def create(item: Item, token: CancellationToken) -> Item: # cancelled if the client leaves
30
+ await Task.delay(0.1, token=token)
31
+ return item
32
+
33
+ if __name__ == "__main__":
34
+ app.run(port=8000) # Swagger UI at /docs
35
+ ```
36
+
37
+ ```bash
38
+ uv run stoop run myapp:app --port 8000 # loop-free direct host (default)
39
+ uv run stoop run myapp:app --host-mode rsgi # Granian's standard embedded RSGI server
40
+ uv run granian --interface rsgi myapp:app # stock Granian CLI works too
41
+ ```
42
+
43
+ ## How it runs
44
+
45
+ ```
46
+ Granian (Rust / tokio) flpit Task runtime (Python thread pool)
47
+ ────────────────────────────────── ─────────────────────────────────────────
48
+ accept · TLS · HTTP/1 + HTTP/2 · WS ──► schedule(watcher): match route
49
+ ├─ sync route → plain pool work item
50
+ └─ async route → Task.run (one hop)
51
+ body bytes · disconnect · ws frames ──► FlpitLoop.call_soon* → TaskCompletionSource
52
+ response channel ◄── proto.response_*() straight from the worker
53
+ ```
54
+
55
+ * **Single process, threads only.** Granian's `RSGIWorker` runs in multi-threaded runtime mode inside the current process (`flpit.stoop.server.Server`). Granian's processes, workers and asyncio loops are not used.
56
+ * **No event loop in between.** Granian normally sends each request to an asyncio loop. stoop installs its own `CallbackScheduler`, which posts the request straight onto the flpit pool. Granian's future-like objects (request body, `client_disconnect()`, WebSocket `accept`/`receive`) complete through `FlpitLoop`, a loop shim that completes flpit `TaskCompletionSource`s. The awaiting coroutine then resumes on the pool.
57
+ * **Kestrel model.** Granian's Rust threads do the I/O. Application code runs on a thread pool modelled on .NET's: coroutines resume on any worker, and blocking code may run on a worker (the pool injects more threads if workers block). On free-threaded Python (3.14t) the workers run in parallel.
58
+ * **Synchronous fast path.** A sync endpoint with no request body and no middleware is matched, bound, executed, serialised and written in one pool work item. No coroutine and no Task object is created for it.
59
+ * **Responses are written from the worker.** Granian's `response_*` calls are thread-safe Rust calls, so sending a response needs no thread hop.
60
+ * **Everything per request is lazy.** Query parsing, the body, the DI scope and the disconnect watch are only set up when something uses them.
61
+
62
+ The standard `app.__rsgi__` interface is still available for portability. In that mode, request I/O is bridged to the asyncio loop thread and costs one loop→pool hop per request.
63
+
64
+ ## Features
65
+
66
+ | | |
67
+ |---|---|
68
+ | Routing | decorators per method, route groups (`Router(prefix, tags, middleware, timeout)`), ASP.NET-style constraints `{id:int}`, `{id:uuid}`, `{path:path}`. Static routes are matched with an O(1) dict lookup, dynamic ones with a segment trie |
69
+ | Parameters | inferred like FastAPI (path → query → body), or explicit with `Path/Query/Header/Cookie/Body/FromServices` (as defaults or in `Annotated`). Conversion uses msgspec. All errors are collected into one 400 response in ASP.NET Core's `ValidationProblemDetails` shape (`errors`: parameter name → messages). The individual errors stay available as `RequestValidationError.details` |
70
+ | JSON | Request bodies must be sent as `application/json` or a `+json` type (415 otherwise, as in ASP.NET Core: JSON read from `text/plain` would skip the browser's CORS preflight). **flpit.json** (`JsonConvert`) for dataclasses and `list[dataclass]`, using the app's `JsonSerializerOptions` (camelCase by default). msgspec for everything else, including msgspec `Struct`s. Encoders and decoders are compiled per route from the annotations |
71
+ | DI | `ServiceCollection` / `ServiceProvider` with singleton, scoped (per request) and transient lifetimes; keyed services; `list[T]`; optional services; validation at build time (missing services, cycles, captive dependencies); disposal in reverse order (sync and async); `create_instance` (ActivatorUtilities) |
72
+ | Proxying | `decorate(IService, Wrapper)`: Scrutor-style decorators that implement the same interface and receive the previous implementation (they stack). `intercept(IService, *interceptors)`: generated dispatch proxies (`isinstance(proxy, IService)` is true) for sync and async methods |
73
+ | Cancellation | `token: CancellationToken` parameter (or `request.cancellation_token`). The token is cancelled when the client disconnects (`HttpContext.RequestAborted`) or when the route timeout elapses. A timeout produces 504, a disconnect produces 499 |
74
+ | Middleware | `async def mw(request, call_next)`. App middleware wraps routing, so it also sees 404/405 and CORS preflight requests. Group and route middleware wrap a single endpoint. Middleware classes get constructor injection. Built in: `CORSMiddleware`, `ConcurrencyLimiter` (flpit `SemaphoreSlim`, FIFO queue, 503), `ServerTimingMiddleware` |
75
+ | Slow-client protection | Request bodies must arrive at a minimum data rate: by default 1 KiB/s after a 10 s grace period. This catches stalled clients and clients trickling data just fast enough to dodge an idle timeout; both get 408 and the connection is closed. A shared once-a-second heartbeat (as in Kestrel) checks the deadlines, so a request pays only a set insert and removal while it waits for body data. Change it with `Stoop(min_body_rate=MinDataRate(...))`, per group or per route; `None` turns it off. Granian already limits header reading to 30 s |
76
+ | Forms and uploads | `Form()` fields and `UploadFile` parameters (single, optional or `list[UploadFile]`) from `multipart/form-data` or `application/x-www-form-urlencoded` bodies. `await request.form()` gives the raw `FormData`. Uploads are held in memory, bounded by the body size limit. A form has at most 1,000 fields and files (Starlette's limit; ASP.NET Core's `FormOptions` allow 1,024 values), and a text field at most 4 MiB (as `FormOptions.ValueLengthLimit`); beyond either, 413. OpenAPI describes them as form bodies |
77
+ | Body size limit | 30 MB by default. Change it with `Stoop(max_body_size=...)`, per group with `Router(max_body_size=...)`, or per route with `@app.post(..., max_body_size=...)`. `UNLIMITED` turns it off. Requests with a larger `Content-Length` are rejected before any body is read; chunked bodies are counted while reading. Either case returns 413 |
78
+ | Results | return values, `Response`, `JSONResponse`, `PlainTextResponse`, `HTMLResponse`, `RedirectResponse`, `FileResponse` (served by Granian from disk), `StreamingResponse` (sync and async iterables, `AsyncFlpIt` queries), `EventStreamResponse` (server-sent events), `Results.*` helpers |
79
+ | Static files | `app.static_files("/static", "wwwroot")` (ASP.NET Core's `UseStaticFiles`), also on a `Router`, with route options. Granian sends the file from disk. Safe by default: nothing outside the directory (`..`, encoded or not, backslashes, drive letters, symlinks leading out), no dotfiles, no directory listings, and only web content types from a fixed table (no `.py`, `.toml`, backups). `ETag`/`Last-Modified` with 304, single byte ranges for media seeking |
80
+ | Errors | RFC 9457 problem details. `HTTPException(status, detail, headers, **extensions)`. Exception handlers (sync or async) are looked up along the exception's MRO. `debug=True` adds tracebacks |
81
+ | WebSockets | `@app.websocket("/ws/{room}")` with the same parameter binding; `accept`, `receive*`, `send_text/bytes/json`, `close`, `async for` |
82
+ | Hosting | `on_startup` / `on_shutdown`; hosted services (`BackgroundService.execute(stopping_token)`); health checks (`/healthz`, run concurrently with `Task.when_all`-style tasks); graceful drain on stop |
83
+ | OpenAPI | `/openapi.json` (OpenAPI 3.1, with schemas generated from flpit's wire types so names follow the naming policy) and Swagger UI at `/docs` |
84
+ | Testing | `flpit.stoop.testing.TestServer` (ASP.NET Core's `TestServer`) drives the real dispatch code with no sockets: `with TestServer(app) as server: client = server.create_client()`. `client.start(...)` plus `.disconnect()` tests cancellation |
85
+
86
+ ### Dependency injection with decorators and proxies
87
+
88
+ ```python
89
+ services = ServiceCollection()
90
+ services.add_singleton(AuditLog)
91
+ services.add_singleton(TodoRepository, InMemoryTodoRepository)
92
+ services.decorate(TodoRepository, AuditingTodoRepository) # __init__(self, inner: TodoRepository, audit: AuditLog)
93
+ services.intercept(TodoRepository, TimingInterceptor) # interceptor types are built through DI too
94
+ services.add_scoped(UnitOfWork) # one per request, disposed after the response
95
+
96
+ app = Stoop(services=services)
97
+
98
+ @app.get("/todos")
99
+ def todos(repo: TodoRepository) -> list[Todo]: # registered types are injected automatically
100
+ return repo.all()
101
+ ```
102
+
103
+ An interceptor is a callable `(invocation) -> result`, or an object with `intercept(invocation)`. Call `invocation.proceed()` to continue the chain. For async methods, `proceed()` returns an awaitable and the interceptor can be `async def`.
104
+
105
+ ### asyncio clients: one per loop
106
+
107
+ Prefer a library's sync client (one shared `httpx.Client`). For libraries that only exist for asyncio, register the client per loop. asyncio clients belong to one event loop, and flpit's asyncio bridge runs several loops, so the container keeps one instance per loop:
108
+
109
+ ```python
110
+ from flpit.asyncio_bridge import PerLoop
111
+ from flpit.task import asyncio_task
112
+
113
+ services.add_per_loop(httpx.AsyncClient, factory=lambda: httpx.AsyncClient(timeout=10), warm=True)
114
+ services.add_singleton(GitHubApi)
115
+
116
+ class GitHubApi:
117
+ def __init__(self, clients: PerLoop[httpx.AsyncClient]) -> None: # not the client itself
118
+ self._clients = clients
119
+
120
+ @asyncio_task
121
+ async def repo(self, name: str, token: CancellationToken) -> dict: # a client disconnect cancels it
122
+ return (await self._clients.current.get(f"https://api.github.com/repos/{name}")).json()
123
+ ```
124
+
125
+ - **Captive check:** a singleton, scoped or transient service that takes the client itself fails when the container is built. It would keep one loop's client; the error points to `PerLoop[...]`. Per-loop services may take it directly.
126
+ - **`warm=True`:** creates the client on every loop before the loop takes work.
127
+ - **Closing:** the clients close with their loop and when the app shuts down.
128
+ - **`Loop[T]` parameters:** `@asyncio_task` functions with `client: Loop[httpx.AsyncClient] = injected` receive the same instances.
129
+ - **Thread-safe async clients:** a client like pyreqwest's `Client` needs none of this. Register it as a plain singleton.
130
+
131
+ ### Cooperative cancellation
132
+
133
+ ```python
134
+ @app.get("/report", timeout=5.0) # 504 after 5 s
135
+ async def report(token: CancellationToken):
136
+ async for row in rows(): # stops as soon as the client goes away
137
+ token.throw_if_cancellation_requested()
138
+ await Task.delay(0.01, token=token)
139
+
140
+ @app.get("/crunch")
141
+ def crunch(token: CancellationToken): # blocking code polls the token
142
+ while not token.is_cancellation_requested:
143
+ step()
144
+ ```
145
+
146
+ The disconnect watch is only started when a handler asks for the token, so endpoints that never use it pay nothing.
147
+
148
+ See [`examples/todo_app.py`](examples/todo_app.py) for an app that uses all of the above.
149
+
150
+ ## Server options
151
+
152
+ ```python
153
+ from flpit.stoop.server import Server
154
+
155
+ with Server(app, host="0.0.0.0", port=8000,
156
+ runtime_threads=2, # tokio I/O threads
157
+ min_workers=16, max_workers=256, # flpit pool (Task.configure)
158
+ http="auto", websockets=True,
159
+ ssl_cert="cert.pem", ssl_key="key.pem") as server:
160
+ ...
161
+ ```
162
+
163
+ `Server.start()` returns once the server is listening. `port=0` picks a free port. `stop()` stops accepting connections, drains requests that are in flight, then runs app shutdown.
164
+
165
+ `STOOP_DISPATCH=task` forces dispatch through the public `Task.run` only (see "Internals used" below).
166
+
167
+ ## Benchmarks
168
+
169
+ ### stoop vs. standard FastAPI
170
+
171
+ `uv run --group bench python bench/compare_fastapi.py` (options and setup in [`bench/README.md`](bench/README.md)) compares stoop with the stack most FastAPI apps run on: `fastapi[standard]` served by uvicorn with uvloop and httptools, which is what `fastapi run` uses. All versions are the latest releases: FastAPI 0.165.0, uvicorn 0.54.0, uvloop 0.23.0, pydantic 2.14.4, starlette 1.10.0.
172
+
173
+ Both apps implement the same endpoints the idiomatic way for each framework (dataclasses for stoop, pydantic models for FastAPI; `def` endpoints for sync, `async def` for async). Access logs are off on both. Each cell is the median of 3 runs of 4 s with 32 keep-alive connections.
174
+
175
+ | req/s · **Python 3.13** | plaintext | json | async | params |
176
+ |---|---:|---:|---:|---:|
177
+ | stoop (direct host) | 34,100 | 35,497 | 20,097 | 33,852 |
178
+ | FastAPI + uvicorn | 5,154 | 3,346 | 10,185 | 2,951 |
179
+ | FastAPI + uvicorn, 2 workers | 11,164 | 3,478 | 16,161 | 7,438 |
180
+ | **stoop ÷ FastAPI (1 worker)** | **6.6×** | **10.6×** | **2.0×** | **11.5×** |
181
+
182
+ | req/s · **Python 3.14t** (free-threaded) | plaintext | json | async | params |
183
+ |---|---:|---:|---:|---:|
184
+ | stoop (direct host) | 33,434 | 30,658 | 19,882 | 28,987 |
185
+ | FastAPI + uvicorn | 6,968 | 4,564 | 9,643 | 3,963 |
186
+ | FastAPI + uvicorn, 2 workers | 8,779 | 4,600 | 15,704 | 4,874 |
187
+ | **stoop ÷ FastAPI (1 worker)** | **4.8×** | **6.7×** | **2.1×** | **7.3×** |
188
+
189
+ The endpoints are: `plaintext` returns a fixed string, `json` returns one object, `async` is an `async def` that returns one object, and `params` is `GET /items/{id}?q=&limit=`, which binds a path parameter and query parameters into an object.
190
+
191
+ * The biggest gaps are on sync `def` endpoints. FastAPI sends each one through anyio's thread pool and back to the event loop. stoop runs them in a single pool work item with no coroutine.
192
+ * On `async def` endpoints FastAPI is at its best, because the request stays on the event loop, and stoop is still about 2× faster.
193
+
194
+ **With a native load generator.** The tables above were measured with the Python load generator. A later run on the same 2-vCPU sandbox used `oha` (Python 3.14t, 64 connections, 3 s, 1 round), with the server pinned to one core and `oha` to the other:
195
+
196
+ | req/s · 1 server core | plaintext | json | async | params |
197
+ |---|---:|---:|---:|---:|
198
+ | flpit-stoop | 54,234 | 43,380 | 25,024 | 34,408 |
199
+ | FastAPI + uvicorn | 5,158 | 3,558 | 9,819 | 2,849 |
200
+
201
+ p99 latency was 2.5–4.9 ms for flpit-stoop and 10–45 ms for FastAPI. For real hardware see [`bench/README.md`](bench/README.md).
202
+
203
+ **Caveats.** These numbers come from a **2-vCPU sandbox**. The Python load generator runs on the same CPUs and tops out at about 35k req/s, so it caps stoop's numbers. Without a network, an in-process microbenchmark of stoop's dispatcher alone reaches about 90–120k req/s. Treat the table as a relative comparison, and rerun it on your own hardware with a native load tool such as `wrk` or `oha` for absolute numbers.
204
+
205
+ ### Host modes
206
+
207
+ `uv run --group bench python bench/run.py` compares stoop's two hosts with FastAPI running on Granian. stoop's RSGI fallback mode sends each request through an asyncio loop first, so it reaches only about 10–11k req/s in this setup, compared with about 30–36k for the direct host.
208
+
209
+ ## Internals used, and known limitations
210
+
211
+ * **Granian internals.** The direct host uses `CallbackScheduler._schedule_fn`, `RSGIWorker(...)`/`serve_mtr`, `WorkerSignal` and the duck-typed loop Granian calls `call_soon*` on. For that reason the Granian dependency is pinned to `>=2.8.9,<2.9`. `app.__rsgi__` uses only public RSGI.
212
+ * **flpit.json** handles dataclasses only, and by default leaves out fields that equal their default value (`JsonDefaultHandling.exclude`). Set `json_options=JsonSerializerOptions(default_handling=JsonDefaultHandling.include)` to include them.
213
+ * **WebSocket close on the RSGI host.** On the RSGI fallback host (`--host-mode rsgi`), the server's WebSocket close frame isn't sent; the client finishes when its own close timeout expires. Plain Granian RSGI apps show the same with uvloop. The direct host isn't affected.
214
+ * Endpoints whose annotations refer to classes defined *inside a function*, combined with `from __future__ import annotations`, cannot be resolved. This is the same limitation FastAPI has.
215
+ * **asyncio libraries in handlers.** The direct host runs no asyncio event loop, so asyncio-based libraries (asyncpg, httpx's async client, redis.asyncio, aiohttp, ...) can't be called directly in a handler ("no running event loop"). Call them through flpit's `@asyncio_task`, with clients registered per loop: see [asyncio clients: one per loop](#asyncio-clients-one-per-loop). Where a library has a sync client, prefer it: sync handlers run on pool workers, in parallel on free-threaded Python.
216
+ * Sync endpoints run on pool workers. Long blocking calls make the pool inject threads, as in .NET.
217
+
218
+ ## Development
219
+
220
+ ```bash
221
+ uv sync
222
+ uv run pytest # free-threaded 3.14t (project default)
223
+ UV_PROJECT_ENVIRONMENT=.venv-3.13 uv run --python 3.13 pytest # GIL build
224
+ uvx ruff check src tests bench
225
+ ```
226
+
227
+ The 118 tests cover the DI container, routing, binding, the app pipeline, OpenAPI, the I/O bridges, the dispatcher, the CLI and the example app. They also include end-to-end socket tests that run against **both** hosts: keep-alive, large bodies, concurrency, streaming, disconnect-driven cancellation, WebSockets, and graceful drain.
@@ -0,0 +1,83 @@
1
+ [project]
2
+ name = "flpit-stoop"
3
+ version = "0.1.0"
4
+ description = "FastAPI-style web framework on the flpit Task runtime, served by Granian with loop-free Kestrel-style dispatch"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ keywords = [
9
+ "web",
10
+ "framework",
11
+ "api",
12
+ "fastapi",
13
+ "granian",
14
+ "flpit",
15
+ "rsgi",
16
+ "dependency-injection",
17
+ "free-threading",
18
+ ]
19
+ classifiers = [
20
+ "Development Status :: 3 - Alpha",
21
+ "Intended Audience :: Developers",
22
+ "Operating System :: OS Independent",
23
+ "Programming Language :: Python :: 3",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ "Programming Language :: Python :: 3.14",
27
+ "Programming Language :: Python :: 3.15",
28
+ "Programming Language :: Python :: Free Threading :: 2 - Beta",
29
+ "Topic :: Internet :: WWW/HTTP :: HTTP Servers",
30
+ "Topic :: Software Development :: Libraries :: Application Frameworks",
31
+ "Typing :: Typed",
32
+ ]
33
+ requires-python = ">=3.12"
34
+ dependencies = [
35
+ "flpit>=0.5.0,<0.6",
36
+ "granian>=2.8.9,<2.9",
37
+ ]
38
+
39
+ [project.urls]
40
+ Homepage = "https://github.com/riemar/flpit-stoop"
41
+ Repository = "https://github.com/riemar/flpit-stoop"
42
+ Issues = "https://github.com/riemar/flpit-stoop/issues"
43
+
44
+ [project.scripts]
45
+ flpit-stoop = "flpit.stoop.cli:main"
46
+ stoop = "flpit.stoop.cli:main"
47
+
48
+ [tool.uv.build-backend]
49
+ module-name = "flpit.stoop"
50
+
51
+ [tool.pytest.ini_options]
52
+ testpaths = ["tests"]
53
+ timeout = 60
54
+
55
+ [tool.ruff]
56
+ line-length = 120
57
+
58
+ [tool.ruff.lint]
59
+ select = [
60
+ "E",
61
+ "F",
62
+ "W",
63
+ "B",
64
+ "UP",
65
+ "I",
66
+ ]
67
+ ignore = [
68
+ "E501",
69
+ "UP007",
70
+ ]
71
+
72
+ [build-system]
73
+ requires = ["uv_build>=0.11.32,<0.12.0"]
74
+ build-backend = "uv_build"
75
+
76
+ [dependency-groups]
77
+ bench = ["fastapi[standard]>=0.165.0"]
78
+ dev = [
79
+ "httpx>=0.28.1",
80
+ "pytest>=9.2.0",
81
+ "pytest-timeout>=2.4.0",
82
+ "websockets>=17.4",
83
+ ]