From 55f94a5516e2edda722d512dd86abfd988ea24dc Mon Sep 17 00:00:00 2001 From: JsNcAr Date: Wed, 14 Oct 2026 11:25:13 -0500 Subject: [PATCH 1/2] chore(deps): SQLAlchemy 2.1.4 with the asyncio extra The <2.1 constraint existed because 2.1 had no wheels, then because 2.1 is a new minor. SQLModel 0.0.48 added 2.1 support, and 2.1 is the first SQLAlchemy with a Python 3.15 wheel, so 2.0 ran as pure Python since the move to 3.15. Declared as sqlalchemy[asyncio]: 2.1 installs greenlet only through that extra. The lock changes one version; greenlet stays at 3.5.6. Checked against the 2.1 migration guide: asyncpg is named in the URL (the psycopg default does not apply), no named types, unconditional autoflush is harmless here. Full suite passes on 3.15 with SADeprecationWarning, SAWarning and SQLModel DeprecationWarnings as errors; lint, mypy and pip-audit clean. Removes the Known Issues entry about the pure wheel. Co-Authored-By: Claude Fable 5.1 --- AGENTS.md | 2 +- CHANGELOG.md | 9 +++ docs/known_issues.md | 14 ---- poetry.lock | 166 ++++++++++++++++++++++++------------------- pyproject.toml | 9 ++- 5 files changed, 105 insertions(+), 95 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 435f846..937ad97 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -62,5 +62,5 @@ docs/ # setup, authentication, api, schemas, releasing, known_issue * **Dependencies**: `poetry add ` (dev tools: `--group dev`), then `poetry install`. Ranges in `pyproject.toml` are open to the next major; `poetry.lock` is the pin. Update with `poetry update` (or `poetry lock --regenerate` for every transitive - package) and run the suite. SQLAlchemy is held below 2.1 until it ships wheels. + package) and run the suite. * **Test database**: `createdb basic_api_test_db` and the `DB_*` variables diff --git a/CHANGELOG.md b/CHANGELOG.md index c9458d1..2a1d60b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,15 @@ notes (see [docs/releasing.md](docs/releasing.md)). pycparser from the dependency tree; HS256 needs none of them (#9). ### Dependencies +- SQLAlchemy 2.0.54 to 2.1.4, declared as `sqlalchemy[asyncio]` because 2.1 + installs greenlet, which the asyncio extension needs, only through that + extra. 2.1 ships a Python 3.15 wheel, so the Cython speedups are back on + 3.15. Of the 2.1 behaviour changes, none reaches this code: the database + URL names `asyncpg` explicitly (2.1 defaults `postgresql://` to psycopg 3), + there are no PostgreSQL named types, and autoflush now also runs before + Core statements such as the health check's `SELECT 1`, which never has + pending changes. The suite passes with every SQLAlchemy warning as an error. + SQLModel 0.0.48 added 2.1 support (#21). - Refresh before the move to Python 3.15: pydantic 2.13.5 to 2.14.1 with pydantic-core 2.50.1, the first release with Python 3.15 wheels; FastAPI 0.142.2 to 0.143.1; Starlette 1.7.0 to 1.8.0; Black 26.10.0 to 26.10.1 and diff --git a/docs/known_issues.md b/docs/known_issues.md index a4b2a35..b244943 100644 --- a/docs/known_issues.md +++ b/docs/known_issues.md @@ -252,20 +252,6 @@ healthy service with its database down. ## Dependencies -### SQLAlchemy 2.0 runs without its C extensions on Python 3.15 - -**Where:** `pyproject.toml` (`sqlalchemy (>=2.0.54,<2.1)`). - -SQLAlchemy 2.0.x publishes compiled wheels up to Python 3.14 only, so on 3.15 -pip installs the pure Python wheel and the Cython speedups (row processing, -result collections) are replaced by their Python implementations. Everything -works and the suite passes; result processing is slower than on 3.14 with the -compiled wheel. SQLAlchemy 2.1.x ships Python 3.15 wheels. - -**Fix:** move to SQLAlchemy 2.1 (a new minor with behaviour changes, read its -migration notes first; SQLModel 0.0.48 allows `<2.2`) and drop the `<2.1` -constraint in `pyproject.toml`. - ### slowapi calls an asyncio API removed in Python 3.16 **Where:** `slowapi/extension.py` (version 0.1.10), surfaced by `pytest.ini`. diff --git a/poetry.lock b/poetry.lock index f851646..55fb4dc 100644 --- a/poetry.lock +++ b/poetry.lock @@ -740,7 +740,6 @@ description = "Lightweight in-process concurrent programming" optional = false python-versions = ">=3.10" groups = ["main"] -markers = "platform_machine == \"aarch64\" or platform_machine == \"ppc64le\" or platform_machine == \"x86_64\" or platform_machine == \"amd64\" or platform_machine == \"AMD64\" or platform_machine == \"win32\" or platform_machine == \"WIN32\"" files = [ {file = "greenlet-3.5.6-cp310-cp310-macosx_11_0_universal2.whl", hash = "sha256:95e7c44d072db623a1aab04ce488cf9533294a77ed9d072cd503a3596f4106ac"}, {file = "greenlet-3.5.6-cp310-cp310-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b7d501d5eb5d4f67207df364752ad697465b834268744be7581c18d81d35d41d"}, @@ -1965,98 +1964,115 @@ files = [ [[package]] name = "sqlalchemy" -version = "2.0.54" +version = "2.1.4" description = "Database Abstraction Library" optional = false -python-versions = ">=3.7" +python-versions = ">=3.11" groups = ["main"] files = [ - {file = "sqlalchemy-2.0.54-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:24ae093dec196ba37fc2beb0316de53e7871d3d246a50faecbbb53034e41ded2"}, - {file = "sqlalchemy-2.0.54-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f8cc6532f930c27974e9239e5ce5abebe7600ba9807cea4fcf42f1b6cab18fe7"}, - {file = "sqlalchemy-2.0.54-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0e7a76d5dce712ce50435d0f97181eb955ec27d138c004176f01282e063bac52"}, - {file = "sqlalchemy-2.0.54-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:f5c09090b1a7c4d389d1431f820931e8df318f82caafc53f9a72c872fef467c5"}, - {file = "sqlalchemy-2.0.54-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:762cfe4d340c56368256d936a98b620a9a5650e49c1c84eba51d6edd17ffefb2"}, - {file = "sqlalchemy-2.0.54-cp310-cp310-win32.whl", hash = "sha256:6b6d4e601c4f6d85e99bb3416107cc9418c5603ca73d4ee0f5f8d79c2a1ed9e8"}, - {file = "sqlalchemy-2.0.54-cp310-cp310-win_amd64.whl", hash = "sha256:03cbf8d9a67da618bd65500a5eb3ddac89caf4c61e99b2f03fa4a1952a0725a9"}, - {file = "sqlalchemy-2.0.54-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7d03084f3352dd92048cb19c71d90f116d076c9c7937e0ebc7752c4685de6d38"}, - {file = "sqlalchemy-2.0.54-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:92622fbbda1b1fe1632f3402a6e516a93c0e41d9158839c6b3dfb12117f26b72"}, - {file = "sqlalchemy-2.0.54-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5800ddea045c2c860ef1d359a07a3066c7c0c426f45e3abc3874e116cb3c6937"}, - {file = "sqlalchemy-2.0.54-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1019abef05a4b5eafc8eae6fb483167fa28a4dbe5f518d577b744f31a5276a37"}, - {file = "sqlalchemy-2.0.54-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b67749f7da3985a529cefbb1474783cb91ef44371cb9713630bade3de908760d"}, - {file = "sqlalchemy-2.0.54-cp311-cp311-win32.whl", hash = "sha256:2f61a70b3b82e2ec7ad6a4f2301422b9ca93ff06917983e41317bcae878bddf6"}, - {file = "sqlalchemy-2.0.54-cp311-cp311-win_amd64.whl", hash = "sha256:1d887fbd5d248e250807bd801e697fc73e3b44866ce5f093dbc90512e75bde25"}, - {file = "sqlalchemy-2.0.54-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ffba7eb2d67c7505e82a0902aa854d8824b74c28a183820d6a8bd3cfd0f812c2"}, - {file = "sqlalchemy-2.0.54-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:63cae7210fea9899e0bf35c1f1ae55d3ddd9c6d47cae8b6b43d945afa79dd65b"}, - {file = "sqlalchemy-2.0.54-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:68d994e9b0d0423a02a20039631fa6fcbb7fa829a992f7605025774940305d19"}, - {file = "sqlalchemy-2.0.54-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3de32cc6721eb42c3aad35bcfb244bb7a18f66c00f3582aae6281d6287a339b5"}, - {file = "sqlalchemy-2.0.54-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:d31a2bc06a854ee52dd86b455be4df7c750b28817e2d1b884e31fff126c4fd7b"}, - {file = "sqlalchemy-2.0.54-cp312-cp312-win32.whl", hash = "sha256:32de6deded25e8b9b11d07428d496ff24dfbc882b8e990c177266948cb5f3d9e"}, - {file = "sqlalchemy-2.0.54-cp312-cp312-win_amd64.whl", hash = "sha256:d65f8ca742ef1e1e14bc417ef59dc2ddf207a7b66b30cfdc6152447314e030cf"}, - {file = "sqlalchemy-2.0.54-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:b374e3bc91e246a942592a98ba6a23be76fff21358b00546ac8c0ebc0fd0e00b"}, - {file = "sqlalchemy-2.0.54-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:31d5458672a6f72db2c087f4a5098b3c8503ea0254186ff29205d63afa9401a4"}, - {file = "sqlalchemy-2.0.54-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cad78d04254967bdbcccbed5e631d88fe4868530946ab0929aa45e9032849518"}, - {file = "sqlalchemy-2.0.54-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:48611087a75d26d798003645c688c7d3cfc26b89dbe4a2c568d6b378d330deae"}, - {file = "sqlalchemy-2.0.54-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:d6adf80277372a89910a0f3ccfe960b846d279dc55b366dd5c5ec07f41c84758"}, - {file = "sqlalchemy-2.0.54-cp313-cp313-win32.whl", hash = "sha256:264460333ed0b177cbb1956355d0ee4e0cab83fb415c934ce12a25db2e7be39c"}, - {file = "sqlalchemy-2.0.54-cp313-cp313-win_amd64.whl", hash = "sha256:cf89e92bf0d4204a6afcc17af27b9271ed9c7e34e17d6f80c085d431ea4a1747"}, - {file = "sqlalchemy-2.0.54-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:abd6b21bc58e91c1932eb5d6d7f1bd44a551dfec7b6a7f517c3638ccd67233a0"}, - {file = "sqlalchemy-2.0.54-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5417322b3c025dd82918725d3bf09ec105fac95efc195722b8b06e1d9c381139"}, - {file = "sqlalchemy-2.0.54-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6f84099e4b04a5c2d44500a2a8302eee5af4bc6fee63e8c6e9cf6786e747280e"}, - {file = "sqlalchemy-2.0.54-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a0956dc754d3884da7fe60097110ec7a8a105d26afa2f0844468f4b1598c6912"}, - {file = "sqlalchemy-2.0.54-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:87ba8834318b0d8dc94fc6f405d071b5c08be32a6c3fd68107fd6952ee949615"}, - {file = "sqlalchemy-2.0.54-cp314-cp314-win32.whl", hash = "sha256:842540e4382472f23c79589995752648d14696a8200d0807ed8c5c59c92ade44"}, - {file = "sqlalchemy-2.0.54-cp314-cp314-win_amd64.whl", hash = "sha256:f4e8f955d13af83fb4e35c3472e5377ee22d3445eada1e5e48199588edb69835"}, - {file = "sqlalchemy-2.0.54-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:ca05f4e7852cf48083b0cf157e4f9504b7068780422a50fa82f45353b8c5e14a"}, - {file = "sqlalchemy-2.0.54-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:18a8b6417cbb7b735cf91c2b59453c2a554cefa0a8d7bd15aa35740739410d77"}, - {file = "sqlalchemy-2.0.54-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4e55a0b96a1577a1e108c91ccdeeb9cd92768f28ce206597311c3bf6d6423abd"}, - {file = "sqlalchemy-2.0.54-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:69cab115c40fd02c5a22c68e4ee630fa6ef9a1650f1de944419aab1f7096fc4f"}, - {file = "sqlalchemy-2.0.54-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:e08397c6c42f53b2488acde9108b8bfefd52d7afd1bf2f03d2ffcab7a204aceb"}, - {file = "sqlalchemy-2.0.54-cp314-cp314t-win32.whl", hash = "sha256:b9086b8ad48280ef6a7ba68262d5e44f7db1c4cb1973e8cdae8a9f467ae66f51"}, - {file = "sqlalchemy-2.0.54-cp314-cp314t-win_amd64.whl", hash = "sha256:b67c1744e453af833667fc1b84de07adb4a64f3536ef52a8ec5ac2b941d43970"}, - {file = "sqlalchemy-2.0.54-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:330d35f9ce815d35cb1daab038d4d7ec0e907f4d7ed0fc8bcb2411d1f23d0b50"}, - {file = "sqlalchemy-2.0.54-cp38-cp38-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e1f455db400289f77ba2f7b62fffafe8875153812d0e3777aa4ff2b34a0fc1f7"}, - {file = "sqlalchemy-2.0.54-cp38-cp38-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4e8a4afcc7d714cc3c8a57facdff4c3529f5f93d71e54b7da1e03e022c9089c9"}, - {file = "sqlalchemy-2.0.54-cp38-cp38-musllinux_1_2_aarch64.whl", hash = "sha256:34e10af7d274a5c4b7cd0fced5e7361008c5e07d97dd48a93852d5b2f1142a1c"}, - {file = "sqlalchemy-2.0.54-cp38-cp38-musllinux_1_2_x86_64.whl", hash = "sha256:7108f410f596c5ac22fe43ba467e864d27c4e1477ae89e90c6c87120b2c1be23"}, - {file = "sqlalchemy-2.0.54-cp38-cp38-win32.whl", hash = "sha256:c1a3455a88f66e4851792bedb098ed942912253d31caed1dbc58afbfa9e875cd"}, - {file = "sqlalchemy-2.0.54-cp38-cp38-win_amd64.whl", hash = "sha256:f3ea33bcf0aa599c1511fe5c9fb126f45aa450419084c4823f786155fe4c79f1"}, - {file = "sqlalchemy-2.0.54-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:b6c419c83a87fd901f0b1b5338ffcb82471c3ac32a86bb8883688c18f8eb85d3"}, - {file = "sqlalchemy-2.0.54-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:415239eb2ddbbc508ba4cac97affb91c0f210548fd1731edda6e529b0bb93015"}, - {file = "sqlalchemy-2.0.54-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:279bde5bfedb0f3e0f1bdbcffa2daa39c6c54d90f9408ef3b1802001597199f0"}, - {file = "sqlalchemy-2.0.54-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:7b973e4facc2f80e42f5a27b841feb7e202661881a6320580abbe597a28a007f"}, - {file = "sqlalchemy-2.0.54-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:deeab253fe01a770f634c7007c73702df2324c868a79ae756507a9a1a76294fe"}, - {file = "sqlalchemy-2.0.54-cp39-cp39-win32.whl", hash = "sha256:d566099d60cded87d175d4171dc899b9613d2e3b663573364565ca1b27ccd241"}, - {file = "sqlalchemy-2.0.54-cp39-cp39-win_amd64.whl", hash = "sha256:744fb219a390561a57dbbd59cd69a22b5b5b2facfde794c1f79236dd847fa67a"}, - {file = "sqlalchemy-2.0.54-py3-none-any.whl", hash = "sha256:7e33a631ab1474f8fe6b910bd1a07b7b8009c4c78cdd3fb18001b03e3bc2e1d2"}, - {file = "sqlalchemy-2.0.54.tar.gz", hash = "sha256:baa8521e8ee9f24e75dfc7aaabc08020e551ef0d48d7c3e3536f5cddf277586b"}, + {file = "sqlalchemy-2.1.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:a6d147c31e189541ae7cd990482c4f960f9e8abce186551225fa355856dbf1a5"}, + {file = "sqlalchemy-2.1.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:55072780d1aae84dea443ce27edeb745f6cc4d19ad89416abbb6b49712080e7c"}, + {file = "sqlalchemy-2.1.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:343a0493a81278bfe30be1ec81214a55f2f44aaa4662d230be359ab2aa18cc2a"}, + {file = "sqlalchemy-2.1.4-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8080022e101afb17565dc5a358a165ff4a20cd97b20b4db49ebed66315b3c733"}, + {file = "sqlalchemy-2.1.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:948dff080b5ac00c8e63bf9e59fa70e386cca1476f55c672a72b6ec12e5cdb05"}, + {file = "sqlalchemy-2.1.4-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:12642e105b4e0cb2ca8428037368c1cbcded7b9d0344174607174d82b700e1eb"}, + {file = "sqlalchemy-2.1.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:976bd3fecfcfa58d69eab67e76325f564ed775aa0c0accf138ae17324b461431"}, + {file = "sqlalchemy-2.1.4-cp311-cp311-win32.whl", hash = "sha256:e2ace725a430e5b303fc3c422196966328ce77fb4fd053ad85572b46ed5fb71a"}, + {file = "sqlalchemy-2.1.4-cp311-cp311-win_amd64.whl", hash = "sha256:3c998d70e60fc95e93e5971395818c50f8a34396a6352075256fefac6b5cf81b"}, + {file = "sqlalchemy-2.1.4-cp311-cp311-win_arm64.whl", hash = "sha256:d045e63095828d2f1fd84d499936e6791522c15c390373fc755f118e4040393a"}, + {file = "sqlalchemy-2.1.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f953be9ba26039a24a5205c65d33518b608ce6f4f0f4e9b9c14eaf42a10dfc52"}, + {file = "sqlalchemy-2.1.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1ac64fce94c5b389062d2e3806db5dc780447591e0dfd5ead218c884f0703f2e"}, + {file = "sqlalchemy-2.1.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3e5045fb6aadbb0f978ab9b9d8822f7b7a97d2281814e7d13d791155664eace3"}, + {file = "sqlalchemy-2.1.4-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e3a026436c51f296aa1d01243909a3b76490950e927824b10899a083cc26e7c3"}, + {file = "sqlalchemy-2.1.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:71040390ef01c85e9d26e5c83cb0c5942dcc8725c49186430af160ce2f54234d"}, + {file = "sqlalchemy-2.1.4-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:07c60abaffb980b7382f2c75be8a5279c2b5df2626a0f5d751dd942799bf3b5c"}, + {file = "sqlalchemy-2.1.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a577e2127e52b0fe2bc54c73abb375a20ffe6f59fbc5568ccafc233f5bfcf8ef"}, + {file = "sqlalchemy-2.1.4-cp312-cp312-win32.whl", hash = "sha256:6c79e0c824d51c586757ecd342160bbdede9010df04bb71b9bbfffd5c7b6ee29"}, + {file = "sqlalchemy-2.1.4-cp312-cp312-win_amd64.whl", hash = "sha256:dffa69d2f3ba1933c1c1882dbef8fb3231b33eb19263e8b8c5cea24995071f06"}, + {file = "sqlalchemy-2.1.4-cp312-cp312-win_arm64.whl", hash = "sha256:e30524ae24e31d83e1b5f734862882c442f4158e3566f2c5f5e9bd3c659bb517"}, + {file = "sqlalchemy-2.1.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:70006e9e6157200b795beeee04bd5cb15bccb40a14de595eb9f5dcf5945ed244"}, + {file = "sqlalchemy-2.1.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3341ddc430733cd961bc064889f42712a0b4056733a21c83176842aad67d12a6"}, + {file = "sqlalchemy-2.1.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:98f7a4bfeaed3722804f737ae2bd4077b35e57d6f4531fe612bac8160cda5acd"}, + {file = "sqlalchemy-2.1.4-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ec5d079935f67febe0ab8a3a203ad591b99508adc34ae0027f696dcb20373537"}, + {file = "sqlalchemy-2.1.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3d675b0856b6703b29d023517a4c19fecfbb55214ff5c72cd813527e40aed9b4"}, + {file = "sqlalchemy-2.1.4-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:a0bb9ee6a38cb36240dc88da11888348f61506047be54de3f09496c3b0ead6f5"}, + {file = "sqlalchemy-2.1.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:61a2c48771cf314b6613d327c795902bbc0eb6d6169deb23b35004ba6ad6cc0d"}, + {file = "sqlalchemy-2.1.4-cp313-cp313-win32.whl", hash = "sha256:3fd608a06bafa768ad5711df4e17eb058bdc490e9df7d39b12a90947471e8712"}, + {file = "sqlalchemy-2.1.4-cp313-cp313-win_amd64.whl", hash = "sha256:b756d74527c56a7e4cfae297f7930c1d75bdf4b23f214c8c13779746d28060cb"}, + {file = "sqlalchemy-2.1.4-cp313-cp313-win_arm64.whl", hash = "sha256:a64d54015233f824f171009977bfbb6b08bd0347b700cf17cb047ffb94c4148f"}, + {file = "sqlalchemy-2.1.4-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:7a2f6164c0527cd8fc4cea79a5c9d8369ffee417b8ba444a42342f36b91deb75"}, + {file = "sqlalchemy-2.1.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6929a11ad26a91a4efd891c1252b373c2e88f056910b83ec6030ed3f2cbcb734"}, + {file = "sqlalchemy-2.1.4-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:14528d37d7d46a92f2a483f188f7fecd86cdd789254a0412b960c9fc5e9efd6d"}, + {file = "sqlalchemy-2.1.4-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d2cb669c6bd1f19caf51db6e3c4fdd4cbb76f9db3ef81c3aeb5e288d9bae101b"}, + {file = "sqlalchemy-2.1.4-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:63dc25b21fd9a41dc09b7aada4b3b0d97cf4b6414f74bced6ac45326bc799ac9"}, + {file = "sqlalchemy-2.1.4-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:308f96d24e773d64609a2a0d1161a068f9f6e9165523bc4e07aa9c45f0c4213f"}, + {file = "sqlalchemy-2.1.4-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:93b9416b9011a3b7689a933e04ac9f61d15686b6cb1948ebc1f41467153116c3"}, + {file = "sqlalchemy-2.1.4-cp314-cp314-win32.whl", hash = "sha256:89db94855287fdac98d74595cf13ea59fbffa608d6400ff972b0fd4c036d873f"}, + {file = "sqlalchemy-2.1.4-cp314-cp314-win_amd64.whl", hash = "sha256:080f8d853aac5bb5620f0ae6f46527397cf18dce0ec2b478b478469ef3cae2c4"}, + {file = "sqlalchemy-2.1.4-cp314-cp314-win_arm64.whl", hash = "sha256:64d41be1dd88f184de1931f0173f4827122a1b49fd1150656641200c0bdf640c"}, + {file = "sqlalchemy-2.1.4-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:84272f329c15081a1e09b4a7261118b4e8a547f43e00fca98e55bbdf19eff3be"}, + {file = "sqlalchemy-2.1.4-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7b3f58bd26fc010ea28976d401845e4e6ce02e1b7c0288b3ea9c9a3c396f0bcc"}, + {file = "sqlalchemy-2.1.4-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:82d728075d42bd457d09655cf22e99d772a648c6f67e86743a4f05b7d063ca18"}, + {file = "sqlalchemy-2.1.4-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0970394ec5d9e397aafc5bc5fa2b7f8b58cb191f2703006b19a96ef4bf00b8d9"}, + {file = "sqlalchemy-2.1.4-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:6005f2f5fcd67fdd721446128e6a2a1d18f77387a604fbd26b0006a086b33096"}, + {file = "sqlalchemy-2.1.4-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:0e01a3e199ae219381c4889993c5584b1b905fffe6830f639adb6770036a8913"}, + {file = "sqlalchemy-2.1.4-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:22129e7d00ac66b291840c4dc83a9c497456ab5bffa682dcbfdc2356f9e49e5a"}, + {file = "sqlalchemy-2.1.4-cp314-cp314t-win32.whl", hash = "sha256:bc33d3e59d4e84b8866cc9ba13732585e37212dbe3542cb09f232682b36f47a5"}, + {file = "sqlalchemy-2.1.4-cp314-cp314t-win_amd64.whl", hash = "sha256:346d144e8912ae087b10d3c2081657cb634728600693eee6dbb71d7eb4768101"}, + {file = "sqlalchemy-2.1.4-cp314-cp314t-win_arm64.whl", hash = "sha256:3e5de57c71b3460e2ca6137e82cd3cb8c9f711f301f50d5c77156fdb9c822999"}, + {file = "sqlalchemy-2.1.4-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:418786f05387ddb66ee683a1d016c5a8d9bf7be921e6ee8f285c7b6ac961a731"}, + {file = "sqlalchemy-2.1.4-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:283914efed30e4d44301e36ac90ad048570538b8a70f072fe01578d9b205d09c"}, + {file = "sqlalchemy-2.1.4-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3d2eacdbeb990b80235763860923c60a8393745b66f7149a734980c65896da72"}, + {file = "sqlalchemy-2.1.4-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e43fca5fdd5f34a3f8c54107a3648d3139de8bbf596a189f3f0de94bd84949bb"}, + {file = "sqlalchemy-2.1.4-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:2e1b5343d315b10a4a71da481729f66f830a561595e02b61e8a5a65d658325ac"}, + {file = "sqlalchemy-2.1.4-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:42c37c06adcecf444e8c981f7e9237a41bdd445c83da0df9e08b4ad958becbbc"}, + {file = "sqlalchemy-2.1.4-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:bab7f51d38766d6a64da2b41976f1b3f9cc2ff37d3f2f63bdbac876199f3a48e"}, + {file = "sqlalchemy-2.1.4-cp315-cp315-win32.whl", hash = "sha256:1541ba5bf0f232cd61f9ef3df78c93977c72ba6031506a0e6d057b2a3ddb76e9"}, + {file = "sqlalchemy-2.1.4-cp315-cp315-win_amd64.whl", hash = "sha256:596a95611c217cb19c21f02f43c637cb507cab71dcf0467c5c7d98fcdd703007"}, + {file = "sqlalchemy-2.1.4-cp315-cp315-win_arm64.whl", hash = "sha256:0d1ca95e42ce3c18818f170b741d30a33b292c6f6b9a202ffd717e28fc99b8c7"}, + {file = "sqlalchemy-2.1.4-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:0f672ed6972164fec94a8f0b21dcf8545080d0727866335fb8adf9f4764ce6ec"}, + {file = "sqlalchemy-2.1.4-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:72e3fa41d1fdab87d4e88bbdd69c9522e2795549fbe7b07bcf4ae9ec175f4b11"}, + {file = "sqlalchemy-2.1.4-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cb2cb98d056e63e353ed697750004e07c79b054d73059ba3184ca3bb07296bea"}, + {file = "sqlalchemy-2.1.4-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:1d66fdcc5506e0f8bb8d3f4f95125220a7cd6c46e8b1762750f01e9639973dd8"}, + {file = "sqlalchemy-2.1.4-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:81f802c96dbf96e59c6982fa1b87da7868920fb0c27b9b81e560a62f57c2ccfb"}, + {file = "sqlalchemy-2.1.4-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:acf8982c70471a68aa90d1aba08b48860c55b3357ec84ccb0f09368ead2ce099"}, + {file = "sqlalchemy-2.1.4-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:778094c83e36c430756a7e1a1ac66fc3cffb2c6a1067958fe6b920abcec7bc5a"}, + {file = "sqlalchemy-2.1.4-cp315-cp315t-win32.whl", hash = "sha256:963348422b22f760e9462e56bc32bf4d95d224cc5b8c79a3c6e3b786d3d2a2b2"}, + {file = "sqlalchemy-2.1.4-cp315-cp315t-win_amd64.whl", hash = "sha256:fba3500e170d25f581e053009edeb0b158116084d91d465de218718d336b67c3"}, + {file = "sqlalchemy-2.1.4-cp315-cp315t-win_arm64.whl", hash = "sha256:0a9a464bc360856b7ea9bf8aa26aab92ca115dd08149cb0e004063d5db13584b"}, + {file = "sqlalchemy-2.1.4-py3-none-any.whl", hash = "sha256:0b96edcc2cd60fe1e35f67a46f4eb076e57297841b9eae949ac5f196593f00a7"}, + {file = "sqlalchemy-2.1.4.tar.gz", hash = "sha256:7bd7ad604487daa7eab8716471c29a7185f17b5287ce73bb7bc79fea050d8cfd"}, ] [package.dependencies] -greenlet = {version = ">=1", markers = "platform_machine == \"aarch64\" or platform_machine == \"ppc64le\" or platform_machine == \"x86_64\" or platform_machine == \"amd64\" or platform_machine == \"AMD64\" or platform_machine == \"win32\" or platform_machine == \"WIN32\""} +greenlet = {version = ">=1", optional = true, markers = "extra == \"asyncio\""} typing-extensions = ">=4.6.0" [package.extras] -aiomysql = ["aiomysql (>=0.2.0)", "greenlet (>=1)"] -aioodbc = ["aioodbc", "greenlet (>=1)"] -aiosqlite = ["aiosqlite", "greenlet (>=1)", "typing_extensions (!=3.10.0.1)"] +aiomysql = ["aiomysql", "sqlalchemy[asyncio]"] +aioodbc = ["aioodbc", "sqlalchemy[asyncio]"] +aiosqlite = ["aiosqlite", "sqlalchemy[asyncio]"] asyncio = ["greenlet (>=1)"] -asyncmy = ["asyncmy (>=0.2.12)", "greenlet (>=1)"] +asyncmy = ["asyncmy (>=0.2.12)", "sqlalchemy[asyncio]"] +cymysql = ["cymysql"] mariadb-connector = ["mariadb (>=1.0.1,!=1.1.2,!=1.1.5,!=1.1.10)"] mssql = ["pyodbc"] mssql-pymssql = ["pymssql"] mssql-pyodbc = ["pyodbc"] -mypy = ["mypy (>=0.910)"] +mssql-python = ["mssql-python (>=1.9.0)"] +mypy = ["mypy (>=2.4)", "types-greenlet (>=2)"] mysql = ["mysqlclient (>=1.4.0)"] mysql-connector = ["mysql-connector-python"] -oracle = ["cx_oracle (>=8)"] -oracle-oracledb = ["oracledb (>=1.0.1)"] -postgresql = ["psycopg2 (>=2.7)"] -postgresql-asyncpg = ["asyncpg", "greenlet (>=1)"] -postgresql-pg8000 = ["pg8000 (>=1.29.1)"] -postgresql-psycopg = ["psycopg (>=3.0.7)"] +oracle = ["oracledb (>=2.0.1)"] +oracle-cxoracle = ["cx_oracle (>=8)"] +oracle-oracledb = ["oracledb (>=2.0.1)"] +postgresql = ["psycopg (>=3.0.7,!=3.1.15)"] +postgresql-asyncpg = ["asyncpg", "sqlalchemy[asyncio]"] +postgresql-pg8000 = ["pg8000 (>=1.29.3)"] +postgresql-psycopg = ["psycopg (>=3.0.7,!=3.1.15)"] postgresql-psycopg2binary = ["psycopg2-binary"] postgresql-psycopg2cffi = ["psycopg2cffi"] -postgresql-psycopgbinary = ["psycopg[binary] (>=3.0.7)"] +postgresql-psycopgbinary = ["psycopg[binary] (>=3.0.7,!=3.1.15)"] pymysql = ["pymysql"] sqlcipher = ["sqlcipher3_binary"] @@ -2366,4 +2382,4 @@ dev = ["pytest", "setuptools"] [metadata] lock-version = "2.1" python-versions = ">=3.15,<4.0" -content-hash = "8ad3f3642c695b4a9f8fe1268bbb9d8af7c05c66aa262a97d2a78ecdf1d61a3e" +content-hash = "bb8bc1047dfb66a611a81db09089653527e6a791d6b1cb0ad9416b98387c62f0" diff --git a/pyproject.toml b/pyproject.toml index 74a73ff..1a4aaea 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -17,11 +17,10 @@ dependencies = [ "python-multipart (>=0.0.32,<1.0)", "pydantic[email] (>=2.13.5,<3.0)", "sqlmodel (>=0.0.48,<1.0)", - # SQLAlchemy is SQLModel's dependency; constrained here because 2.1 is a new - # minor with behaviour changes (SQLModel allows up to <2.2), so moving to it is - # its own change. 2.1.x ships wheels for Python 3.11 to 3.15; 2.0.x stops at 3.14 - # and installs as pure Python on 3.15. - "sqlalchemy (>=2.0.54,<2.1)", + # Declared although SQLModel depends on it: database.py and services import + # SQLAlchemy directly, and since 2.1 greenlet, which the asyncio extension + # needs, is only installed through the [asyncio] extra. + "sqlalchemy[asyncio] (>=2.1.4,<3.0)", "asyncpg (>=0.32.0,<1.0)", "slowapi (>=0.1.10,<1.0)", "pyjwt (>=2.15.1,<3)", From 23cb90c305d316f79326625e6b460079376be05e Mon Sep 17 00:00:00 2001 From: JsNcAr Date: Wed, 14 Oct 2026 11:31:37 -0500 Subject: [PATCH 2/2] feat(limiter): rate limiting on limits directly, slowapi removed slowapi 0.1.10 calls asyncio.iscoroutinefunction, removed in Python 3.16, and the fix has sat in open upstream pull requests since 2025. The limiter is now built on limits (the library slowapi wraps, already installed): MemoryStorage, FixedWindowRateLimiter, parse_many, so the configuration syntax and the fixed-window behaviour are unchanged. A limited route declares Depends(limiter.limit(...)) instead of a decorator plus request and response parameters it never used; the dependency counts the request, writes X-RateLimit-Limit, -Remaining and -Reset onto the response and raises RateLimitExceeded, which main.py maps to the same 429 body and Retry-After as before. New: the 429 also carries the X-RateLimit headers, X-RateLimit-Reset is a whole number of seconds, and counters are keyed by method and route path. The pytest.ini filter for slowapi's warning is gone: the suite passes with -W error. Tests cover the handler, the headers, the 429, per-route counters and the disabled limiter without a database. Co-Authored-By: Claude Fable 5.1 --- .env.example | 2 +- CHANGELOG.md | 9 ++ README.md | 2 +- docs/api.md | 3 +- docs/known_issues.md | 25 +----- poetry.lock | 20 +---- pyproject.toml | 2 +- pytest.ini | 6 +- src/basic_api/config.py | 2 +- src/basic_api/limiter.py | 158 ++++++++++++++++++++++++++++----- src/basic_api/main.py | 17 ++-- src/basic_api/routers/users.py | 8 +- tests/test_limiter.py | 89 ++++++++++++++----- tests/test_rate_limit.py | 2 +- 14 files changed, 238 insertions(+), 107 deletions(-) diff --git a/.env.example b/.env.example index 7cf8bf0..5685a35 100644 --- a/.env.example +++ b/.env.example @@ -60,6 +60,6 @@ BCRYPT_ROUNDS=12 # Largest request body in bytes; larger requests get 413 before any route runs MAX_REQUEST_BODY_BYTES=1048576 -# --- Rate limits (per client IP, slowapi/limits syntax: 10/minute, 100/hour) --- +# --- Rate limits (per client IP, `limits` syntax: 10/minute, 100/hour) --- RATE_LIMIT_LOGIN=60/minute RATE_LIMIT_REGISTER=10/minute diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a1d60b..f7e5db5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -80,6 +80,15 @@ notes (see [docs/releasing.md](docs/releasing.md)). `RequestBodyLimitMiddleware` answers 413 before any route runs (#13). ### Changed +- The rate limiter is built directly on `limits` (fixed window, in-process + memory) instead of slowapi, whose `asyncio.iscoroutinefunction` call is + removed in Python 3.16 and unfixed upstream. A limited route now declares + `Depends(limiter.limit(...))` instead of a decorator plus `request` and + `response` parameters it never used. Same limits, same per-IP and per-route + counting, same `429` body and `Retry-After`; the `429` now also carries the + `X-RateLimit` headers, and `X-RateLimit-Reset` is a whole number of seconds. + The `pytest.ini` warning filter for slowapi is gone, so the suite runs with + no filtered warnings (#22). - Python 3.15: `.python-version` says `3.15`, `requires-python` is `>=3.15,<4.0`, Black targets `py315`, mypy checks against 3.15 and the GitLab pipeline runs on `python:3.15-slim`. Every dependency ships a 3.15 wheel or is diff --git a/README.md b/README.md index ff324e3..015aaef 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ configuration right. That work is done here, tested, and documented. time and return the same body - Passwords hashed with bcrypt over a SHA-256 pre-hash, off the event loop - Client API key as a declared OpenAPI security scheme on every `/api` route -- Rate limits per client IP on login and registration (slowapi) +- Rate limits per client IP on login and registration (`limits`) - User self-service: read, update, change password and delete the own account - Async PostgreSQL through SQLModel and asyncpg; health check that pings it - One `config.py` reads and validates every environment variable at startup diff --git a/docs/api.md b/docs/api.md index 16df81f..6fa2a40 100644 --- a/docs/api.md +++ b/docs/api.md @@ -30,7 +30,8 @@ same id; quote it when reporting a problem. **Rate limits**: `POST /token` and `POST /api/users/` answer with `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset` (Unix -time at which the window resets); over the limit, a `429` with `Retry-After`. +time at which the window resets); over the limit, a `429` with `Retry-After` +and the same three headers with nothing remaining. **Auth** column: `key` is the `X-API-Key` header, `token` is `Authorization: Bearer `. See [Authentication](authentication.md) for the diff --git a/docs/known_issues.md b/docs/known_issues.md index b244943..33b25a8 100644 --- a/docs/known_issues.md +++ b/docs/known_issues.md @@ -24,7 +24,6 @@ looks like. Remove an entry in the same change that fixes it. | Code | [Startup validation and the login limit are untested](#startup-validation-and-the-login-limit-are-untested) | Low | | Code | [Application code detects the test runner](#application-code-detects-the-test-runner) | Low | | Code | [The root banner reports healthy without checking](#the-root-banner-reports-healthy-without-checking) | Low | -| Dependencies | [slowapi calls an asyncio API removed in Python 3.16](#slowapi-calls-an-asyncio-api-removed-in-python-316) | Low | --- @@ -152,8 +151,8 @@ effective limit; a restart resets it. Behind a reverse proxy on another host, uvicorn must be told to trust its forwarded headers (`--forwarded-allow-ips`), or every client shares one bucket. -**Fix:** shared storage for the counts (slowapi supports Redis) when running -more than one worker. +**Fix:** shared storage for the counts (`limits` has Redis, Memcached and +MongoDB storages) when running more than one worker. ### No metrics, tracing or error tracking @@ -247,23 +246,3 @@ healthy service with its database down. **Fix:** drop the `status` field from the banner, or have it call the same `ping()` as `/health`. - ---- - -## Dependencies - -### slowapi calls an asyncio API removed in Python 3.16 - -**Where:** `slowapi/extension.py` (version 0.1.10), surfaced by `pytest.ini`. - -On Python 3.14 and 3.15 the test run reports `DeprecationWarning: 'asyncio.iscoroutinefunction' -is deprecated and slated for removal in Python 3.16; use -inspect.iscoroutinefunction()`, raised from slowapi when it wraps a rate-limited -route. Nothing is wrong today; on Python 3.16 the rate limiter would stop -working unless slowapi releases a fix. `pytest.ini` filters this one warning -for the `slowapi` module only, so the summary stays readable; the filter must go -when slowapi fixes it or when this project replaces slowapi. - -**Fix:** upgrade slowapi once a release uses `inspect.iscoroutinefunction`, then -remove the filter; if none appears before 3.16 matters, replace slowapi (the -limiter lives in one module, `limiter.py`). diff --git a/poetry.lock b/poetry.lock index 55fb4dc..42f3a2f 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1932,24 +1932,6 @@ pygments = ">=2.13.0,<3.0.0" [package.extras] jupyter = ["ipywidgets (>=7.5.1,<9)"] -[[package]] -name = "slowapi" -version = "0.1.10" -description = "A rate limiting extension for Starlette and Fastapi" -optional = false -python-versions = "<4.0,>=3.7" -groups = ["main"] -files = [ - {file = "slowapi-0.1.10-py3-none-any.whl", hash = "sha256:3acb61561dc9d687e3d3669362ff6a439de9ba44e2fed3a9c165da26b4b83e28"}, - {file = "slowapi-0.1.10.tar.gz", hash = "sha256:d320d5bc04d9f171a77fb16700faf3036d85b00f420f22924c8a225f95bd14f9"}, -] - -[package.dependencies] -limits = ">=2.3" - -[package.extras] -redis = ["redis (>=3.4.1,<4.0.0)"] - [[package]] name = "sortedcontainers" version = "2.4.0" @@ -2382,4 +2364,4 @@ dev = ["pytest", "setuptools"] [metadata] lock-version = "2.1" python-versions = ">=3.15,<4.0" -content-hash = "bb8bc1047dfb66a611a81db09089653527e6a791d6b1cb0ad9416b98387c62f0" +content-hash = "4fdb9494d859134b0b7a63e5ec67f9d23c698553f406f5bb950395ee69db778a" diff --git a/pyproject.toml b/pyproject.toml index 1a4aaea..74ca940 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -22,7 +22,7 @@ dependencies = [ # needs, is only installed through the [asyncio] extra. "sqlalchemy[asyncio] (>=2.1.4,<3.0)", "asyncpg (>=0.32.0,<1.0)", - "slowapi (>=0.1.10,<1.0)", + "limits (>=5.8.0,<6.0)", "pyjwt (>=2.15.1,<3)", ] diff --git a/pytest.ini b/pytest.ini index 5a0add5..d724d8e 100644 --- a/pytest.ini +++ b/pytest.ini @@ -4,9 +4,7 @@ addopts = -ra -q testpaths = tests pythonpath = src python_files = test_*.py -# Third-party only, tracked in docs/known_issues.md (slowapi and Python 3.16). -# Never a blanket ignore: a new deprecation in our own code must stay visible. -filterwarnings = - ignore:'asyncio.iscoroutinefunction' is deprecated:DeprecationWarning:slowapi +# No warning filters: a deprecation in our code or a dependency stays visible +# in the summary and is dealt with (or recorded in docs/known_issues.md). asyncio_mode = auto asyncio_default_fixture_loop_scope = function diff --git a/src/basic_api/config.py b/src/basic_api/config.py index cba1c6b..56ac0c0 100644 --- a/src/basic_api/config.py +++ b/src/basic_api/config.py @@ -253,7 +253,7 @@ def minimum_secret_bytes(algorithm: str) -> int: raise RuntimeError("MAX_REQUEST_BODY_BYTES must be a positive integer") # --- Rate limits ------------------------------------------------------------- -# slowapi/limits syntax, e.g. "10/minute", "100/hour"; validated in limiter.py. +# `limits` syntax, e.g. "10/minute", "100/hour"; validated in limiter.py. # Per client IP and per process (each uvicorn worker keeps its own count). RATE_LIMIT_LOGIN = os.getenv("RATE_LIMIT_LOGIN", "60/minute") RATE_LIMIT_REGISTER = os.getenv("RATE_LIMIT_REGISTER", "10/minute") diff --git a/src/basic_api/limiter.py b/src/basic_api/limiter.py index 486a941..ad950e8 100644 --- a/src/basic_api/limiter.py +++ b/src/basic_api/limiter.py @@ -1,25 +1,30 @@ """ Rate limiting shared by the app and its routers. -The Limiter lives in its own module because main.py imports the routers; a -router importing it from main.py would be a circular import. +Built on the `limits` library: a fixed window per client IP and per route, +counted in this process's memory. The Limiter lives in its own module because +main.py imports the routers; a router importing it from main.py would be a +circular import. Limits are per client IP, as uvicorn sees it (behind a reverse proxy, make sure uvicorn trusts the proxy's forwarded headers), and per process: with several workers each keeps its own count, so the effective limit is multiplied. -A limited route answers with X-RateLimit-Limit, X-RateLimit-Remaining and -X-RateLimit-Reset (Unix time), so a client can pace itself before a 429. slowapi -writes them onto the route's `response: Response` parameter, which is why the -limited routes declare one they never touch. +A limited route declares `Depends(limiter.limit("10/minute"))`. The dependency +counts the request, writes X-RateLimit-Limit, X-RateLimit-Remaining and +X-RateLimit-Reset (Unix time) onto the response so a client can pace itself +before a 429, and raises RateLimitExceeded over the limit; main.py maps that to +the 429 built by rate_limit_exceeded_handler. """ -from fastapi import Request +import math +from collections.abc import Awaitable, Callable + +from fastapi import Request, Response from fastapi.responses import JSONResponse -from limits import parse_many -from slowapi import Limiter -from slowapi.errors import RateLimitExceeded -from slowapi.util import get_remote_address +from limits import RateLimitItem, parse_many +from limits.storage import MemoryStorage +from limits.strategies import FixedWindowRateLimiter from .config import RATE_LIMIT_LOGIN, RATE_LIMIT_REGISTER @@ -33,30 +38,143 @@ except ValueError as e: raise RuntimeError(f"{_name}={_value!r} is not a valid rate limit: {e}") -limiter = Limiter(key_func=get_remote_address, headers_enabled=True) + +class RateLimitExceeded(Exception): + """ + A request went over one of its route's limits. + + Attributes: + limit: The limit that was hit. + reset_time: Unix time at which that limit's window resets. + """ + + def __init__(self, limit: RateLimitItem, reset_time: float) -> None: + super().__init__(f"rate limit exceeded: {limit}") + self.limit = limit + self.reset_time = reset_time + + +def client_address(request: Request) -> str: + """ + Key requests by client IP. + + Args: + request: The incoming request. + + Returns: + The peer address uvicorn reports, or "unknown" when there is none (an + in-process test client, for instance). + """ + return request.client.host if request.client else "unknown" + + +def route_scope(request: Request) -> str: + """ + Name the counter a request belongs to: its method and route path. + + The route's path template (`/api/users/`) rather than the request URL, so a + route with path parameters still has one counter. + + Args: + request: The incoming request, already matched to a route. + + Returns: + A string such as "POST /api/users/". + """ + route = request.scope.get("route") + path = getattr(route, "path", request.url.path) + return f"{request.method} {path}" + + +class Limiter: + """ + Fixed-window counters per client and per route, in this process's memory. + + Attributes: + enabled: False makes every limit a no-op that writes no headers. The + test suite turns it off because every test client shares one IP. + key_func: Maps a request to its client key; client_address by default. + """ + + def __init__( + self, + key_func: Callable[[Request], str] = client_address, + *, + enabled: bool = True, + ) -> None: + self.enabled = enabled + self.key_func = key_func + self._storage = MemoryStorage() + self._strategy = FixedWindowRateLimiter(self._storage) + + def reset(self) -> None: + """Forget every count.""" + self._storage.reset() + + def limit(self, value: str) -> Callable[[Request, Response], Awaitable[None]]: + """ + Build the dependency that enforces `value` on the route declaring it. + + Args: + value: One or more limits in `limits` syntax ("10/minute", + "100/hour;1000/day"), each of which must hold. + + Returns: + A dependency for the route's `dependencies=[Depends(...)]`. It + raises RateLimitExceeded when a limit is hit; otherwise it writes + the X-RateLimit headers of the limit with the least budget left. + """ + items = parse_many(value) + + async def enforce(request: Request, response: Response) -> None: + if not self.enabled: + return + key = self.key_func(request) + scope = route_scope(request) + for item in items: + if not self._strategy.hit(item, key, scope): + stats = self._strategy.get_window_stats(item, key, scope) + raise RateLimitExceeded(item, stats.reset_time) + item, stats = min( + ((i, self._strategy.get_window_stats(i, key, scope)) for i in items), + key=lambda pair: pair[1].remaining, + ) + response.headers["X-RateLimit-Limit"] = str(item.amount) + response.headers["X-RateLimit-Remaining"] = str(stats.remaining) + response.headers["X-RateLimit-Reset"] = str(math.ceil(stats.reset_time)) + + return enforce + + +limiter = Limiter() def rate_limit_exceeded_handler(request: Request, exc: Exception) -> JSONResponse: """ Answer a limit hit in the API's usual error shape, with a Retry-After. - slowapi's default handler returns {"error": ...}; clients read {"detail": - ...} like every other error. The wait is the limit's window, the longest a - client has to wait under the default fixed-window strategy. + Clients read {"detail": ...} like every other error. The wait is the + limit's window, the longest a client has to wait under the fixed-window + strategy; the X-RateLimit headers say when the window actually resets. Args: request: The request that hit the limit. - exc: The RateLimitExceeded raised by slowapi (typed as Exception + exc: The RateLimitExceeded raised by the limiter (typed as Exception because that is Starlette's handler signature). Returns: - A 429 JSON response with a Retry-After header in seconds. + A 429 JSON response with a Retry-After header in seconds and the + X-RateLimit headers with no budget left. """ assert isinstance(exc, RateLimitExceeded) - wrapper = exc.limit - retry_after = wrapper.limit.get_expiry() if wrapper is not None else 60 + retry_after = exc.limit.get_expiry() return JSONResponse( status_code=429, content={"detail": f"Too many requests. Try again in {retry_after} seconds."}, - headers={"Retry-After": str(retry_after)}, + headers={ + "Retry-After": str(retry_after), + "X-RateLimit-Limit": str(exc.limit.amount), + "X-RateLimit-Remaining": "0", + "X-RateLimit-Reset": str(math.ceil(exc.reset_time)), + }, ) diff --git a/src/basic_api/main.py b/src/basic_api/main.py index 11fae8b..46e756a 100644 --- a/src/basic_api/main.py +++ b/src/basic_api/main.py @@ -24,11 +24,10 @@ from datetime import timedelta from typing import Annotated -from fastapi import Depends, FastAPI, Query, Request, Response +from fastapi import Depends, FastAPI, Query, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from fastapi.security import OAuth2PasswordRequestForm -from slowapi.errors import RateLimitExceeded from starlette.middleware.body_limit import RequestBodyLimitMiddleware from .auth import access_token_lifetime, authenticate_user, create_access_token @@ -45,7 +44,12 @@ from .database import engine, init_db, ping from .dependencies import CurrentUserDep, SessionDep from .exceptions import IdentifierTakenError, PasswordVerificationError -from .limiter import RATE_LIMIT_LOGIN, limiter, rate_limit_exceeded_handler +from .limiter import ( + RATE_LIMIT_LOGIN, + RateLimitExceeded, + limiter, + rate_limit_exceeded_handler, +) from .logging_config import configure_logging from .request_id import REQUEST_ID_HEADER, RequestIdMiddleware from .routers import auth, users @@ -90,7 +94,6 @@ async def lifespan(app: FastAPI): openapi_url="/openapi.json" if ENABLE_DOCS else None, ) -app.state.limiter = limiter app.add_exception_handler(RateLimitExceeded, rate_limit_exceeded_handler) @@ -178,11 +181,9 @@ async def health_check(): "/token", response_model=TokenResponse, responses=error_responses(401, 403, 413, 429), + dependencies=[Depends(limiter.limit(RATE_LIMIT_LOGIN))], ) -@limiter.limit(RATE_LIMIT_LOGIN) async def login( - request: Request, - response: Response, # slowapi writes the X-RateLimit headers onto it form_data: Annotated[OAuth2PasswordRequestForm, Depends()], session: SessionDep, expires_delta: Annotated[ @@ -203,8 +204,6 @@ async def login( `username` may be a username, an email address or a phone number. Args: - request: Needed by the rate limiter (injected). - response: Receives the X-RateLimit headers from the limiter (injected). form_data: OAuth2 password form with `username` and `password` fields. expires_delta: Requested token lifetime (query parameter); the server caps it, see access_token_lifetime. diff --git a/src/basic_api/routers/users.py b/src/basic_api/routers/users.py index 2bab673..8e38300 100644 --- a/src/basic_api/routers/users.py +++ b/src/basic_api/routers/users.py @@ -7,7 +7,7 @@ import logging -from fastapi import APIRouter, HTTPException, Request, Response +from fastapi import APIRouter, Depends, HTTPException from ..dependencies import CurrentUserDep, SessionDep from ..exceptions import AppError @@ -33,11 +33,9 @@ response_model=SuccessResponse[UserResponseSchema], status_code=201, responses=error_responses(409, 413, 429), + dependencies=[Depends(limiter.limit(RATE_LIMIT_REGISTER))], ) -@limiter.limit(RATE_LIMIT_REGISTER) async def create_user( - request: Request, - response: Response, # slowapi writes the X-RateLimit headers onto it user_create: UserCreateSchema, session: SessionDep, ): @@ -45,8 +43,6 @@ async def create_user( Register a user. Rate-limited per client IP (RATE_LIMIT_REGISTER). Args: - request: Needed by the rate limiter (injected). - response: Receives the X-RateLimit headers from the limiter (injected). user_create: Registration payload; `username` and `password` required. session: Database session. diff --git a/tests/test_limiter.py b/tests/test_limiter.py index d2c1071..50e17a8 100644 --- a/tests/test_limiter.py +++ b/tests/test_limiter.py @@ -1,51 +1,63 @@ """ -The rate-limit error response and the budget headers. No database. +The rate limiter: budget headers, the 429, per-route counters. No database. """ import json -from types import SimpleNamespace +import time -from fastapi import FastAPI, Request, Response +from fastapi import Depends, FastAPI from httpx import ASGITransport, AsyncClient from limits import parse -from slowapi.errors import RateLimitExceeded -from basic_api.limiter import limiter, rate_limit_exceeded_handler +from basic_api.limiter import ( + RateLimitExceeded, + limiter, + rate_limit_exceeded_handler, +) def test_rate_limit_response_uses_detail_and_retry_after(): - # slowapi's own handler answers {"error": ...}; clients read "detail" like - # every other error, and need to know how long to wait. - exc = RateLimitExceeded( - SimpleNamespace(limit=parse("10/minute"), error_message=None) - ) + # Clients read "detail" like every other error, need to know how long to + # wait, and get the budget headers with nothing left. + reset_time = time.time() + 42 + exc = RateLimitExceeded(parse("10/minute"), reset_time) response = rate_limit_exceeded_handler(None, exc) # type: ignore[arg-type] assert response.status_code == 429 assert response.headers["Retry-After"] == "60" + assert response.headers["X-RateLimit-Limit"] == "10" + assert response.headers["X-RateLimit-Remaining"] == "0" + assert int(response.headers["X-RateLimit-Reset"]) >= int(reset_time) assert json.loads(response.body) == { "detail": "Too many requests. Try again in 60 seconds." } -async def test_a_limited_route_reports_its_budget_in_headers(): - # The same Limiter the app uses, on a throwaway app: the route returns a - # plain object, so slowapi needs the `response: Response` parameter to - # carry the headers (the reason the app's limited routes declare one). +def _app() -> FastAPI: + # The same Limiter the app uses, on a throwaway app wired like main.py. + # The routes take no request or response parameter: the dependency alone + # counts the call and writes the headers. app = FastAPI() - app.state.limiter = limiter + app.add_exception_handler(RateLimitExceeded, rate_limit_exceeded_handler) + + @app.get("/limited", dependencies=[Depends(limiter.limit("3/minute"))]) + async def limited(): + return {"ok": True} - @app.get("/limited") - @limiter.limit("3/minute") - async def limited(request: Request, response: Response): + @app.get("/other", dependencies=[Depends(limiter.limit("3/minute"))]) + async def other(): return {"ok": True} + return app + + +async def test_a_limited_route_reports_its_budget_in_headers(): limiter.enabled = True limiter.reset() try: async with AsyncClient( - transport=ASGITransport(app=app), base_url="http://test" + transport=ASGITransport(app=_app()), base_url="http://test" ) as client: first = await client.get("/limited") second = await client.get("/limited") @@ -53,7 +65,44 @@ async def limited(request: Request, response: Response): limiter.enabled = False limiter.reset() + assert first.status_code == 200 assert first.headers["X-RateLimit-Limit"] == "3" assert first.headers["X-RateLimit-Remaining"] == "2" assert second.headers["X-RateLimit-Remaining"] == "1" - assert float(first.headers["X-RateLimit-Reset"]) > 0 # Unix time + assert int(first.headers["X-RateLimit-Reset"]) > time.time() # Unix time + + +async def test_the_request_over_the_limit_gets_a_429_and_other_routes_do_not(): + limiter.enabled = True + limiter.reset() + try: + async with AsyncClient( + transport=ASGITransport(app=_app()), base_url="http://test" + ) as client: + statuses = [(await client.get("/limited")).status_code for _ in range(3)] + refused = await client.get("/limited") + other = await client.get("/other") + finally: + limiter.enabled = False + limiter.reset() + + assert statuses == [200, 200, 200] + assert refused.status_code == 429 + assert refused.headers["Retry-After"] == "60" + assert refused.headers["X-RateLimit-Remaining"] == "0" + assert refused.json()["detail"].startswith("Too many requests") + # Counters are per route: the same limit on another route is untouched. + assert other.status_code == 200 + assert other.headers["X-RateLimit-Remaining"] == "2" + + +async def test_a_disabled_limiter_counts_nothing_and_writes_no_headers(): + limiter.enabled = False + limiter.reset() + async with AsyncClient( + transport=ASGITransport(app=_app()), base_url="http://test" + ) as client: + responses = [await client.get("/limited") for _ in range(5)] + + assert [r.status_code for r in responses] == [200] * 5 + assert "X-RateLimit-Limit" not in responses[0].headers diff --git a/tests/test_rate_limit.py b/tests/test_rate_limit.py index 7acab1e..1ac8f1e 100644 --- a/tests/test_rate_limit.py +++ b/tests/test_rate_limit.py @@ -29,7 +29,7 @@ async def test_registration_is_limited_per_client(client): async def test_limited_responses_report_the_remaining_budget(client): - """slowapi's headers: the limit, what is left of it, and when it resets.""" + """The budget headers: the limit, what is left of it, and when it resets.""" limiter.enabled = True limiter.reset() try: