ferronit 0.9.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.
Files changed (42) hide show
  1. ferronit-0.9.0/LICENSE +202 -0
  2. ferronit-0.9.0/PKG-INFO +124 -0
  3. ferronit-0.9.0/README.md +92 -0
  4. ferronit-0.9.0/ferronit/__init__.py +23 -0
  5. ferronit-0.9.0/ferronit/_core.pyi +117 -0
  6. ferronit-0.9.0/ferronit/cli.py +391 -0
  7. ferronit-0.9.0/ferronit/config.py +145 -0
  8. ferronit-0.9.0/ferronit/contrib/__init__.py +1 -0
  9. ferronit-0.9.0/ferronit/contrib/cors.py +41 -0
  10. ferronit-0.9.0/ferronit/contrib/db.py +274 -0
  11. ferronit-0.9.0/ferronit/contrib/health.py +92 -0
  12. ferronit-0.9.0/ferronit/contrib/kafka.py +108 -0
  13. ferronit-0.9.0/ferronit/contrib/llm.py +318 -0
  14. ferronit-0.9.0/ferronit/contrib/pydantic/__init__.py +83 -0
  15. ferronit-0.9.0/ferronit/contrib/pydantic/pydantic_codec.py +44 -0
  16. ferronit-0.9.0/ferronit/contrib/ratelimit.py +58 -0
  17. ferronit-0.9.0/ferronit/contrib/rawdb.py +350 -0
  18. ferronit-0.9.0/ferronit/contrib/rawmodel.py +722 -0
  19. ferronit-0.9.0/ferronit/contrib/security.py +59 -0
  20. ferronit-0.9.0/ferronit/contrib/staticfiles.py +88 -0
  21. ferronit-0.9.0/ferronit/contrib/tracing.py +60 -0
  22. ferronit-0.9.0/ferronit/contrib/vectordb.py +292 -0
  23. ferronit-0.9.0/ferronit/core/__init__.py +0 -0
  24. ferronit-0.9.0/ferronit/core/app.py +366 -0
  25. ferronit-0.9.0/ferronit/core/request.py +365 -0
  26. ferronit-0.9.0/ferronit/core/response.py +151 -0
  27. ferronit-0.9.0/ferronit/db.py +18 -0
  28. ferronit-0.9.0/ferronit/ddd.py +178 -0
  29. ferronit-0.9.0/ferronit/di.py +97 -0
  30. ferronit-0.9.0/ferronit/hexagonal.py +230 -0
  31. ferronit-0.9.0/ferronit/injection.py +261 -0
  32. ferronit-0.9.0/ferronit/middleware.py +49 -0
  33. ferronit-0.9.0/ferronit/openapi.py +157 -0
  34. ferronit-0.9.0/ferronit/py.typed +0 -0
  35. ferronit-0.9.0/ferronit/routing.py +100 -0
  36. ferronit-0.9.0/ferronit/websocket.py +144 -0
  37. ferronit-0.9.0/ferronit-rs/Cargo.lock +1515 -0
  38. ferronit-0.9.0/ferronit-rs/Cargo.toml +32 -0
  39. ferronit-0.9.0/ferronit-rs/README.md +27 -0
  40. ferronit-0.9.0/ferronit-rs/src/db.rs +361 -0
  41. ferronit-0.9.0/ferronit-rs/src/lib.rs +786 -0
  42. ferronit-0.9.0/pyproject.toml +109 -0
ferronit-0.9.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Denis Ivlev
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,124 @@
1
+ Metadata-Version: 2.4
2
+ Name: ferronit
3
+ Version: 0.9.0
4
+ Classifier: Programming Language :: Rust
5
+ Classifier: Programming Language :: Python :: Implementation :: CPython
6
+ Classifier: Topic :: Internet :: WWW/HTTP
7
+ Requires-Dist: sqlalchemy[asyncio]>=2.0 ; extra == 'db'
8
+ Requires-Dist: aiosqlite>=0.20 ; extra == 'db'
9
+ Requires-Dist: pytest>=8 ; extra == 'dev'
10
+ Requires-Dist: pytest-asyncio ; extra == 'dev'
11
+ Requires-Dist: pytest-benchmark ; extra == 'dev'
12
+ Requires-Dist: httpx ; extra == 'dev'
13
+ Requires-Dist: maturin>=1.14,<2 ; extra == 'dev'
14
+ Requires-Dist: ruff>=0.6 ; extra == 'dev'
15
+ Requires-Dist: mypy>=1.11 ; extra == 'dev'
16
+ Requires-Dist: asyncpg>=0.29 ; extra == 'postgres'
17
+ Requires-Dist: msgspec>=0.19 ; extra == 'postgres'
18
+ Requires-Dist: pydantic>=2.0 ; extra == 'pydantic'
19
+ Requires-Dist: granian[reload]>=2.8 ; extra == 'server'
20
+ Requires-Dist: uvicorn[standard]>=0.30 ; extra == 'server'
21
+ Provides-Extra: db
22
+ Provides-Extra: dev
23
+ Provides-Extra: postgres
24
+ Provides-Extra: pydantic
25
+ Provides-Extra: server
26
+ License-File: LICENSE
27
+ Summary: High-performance Python ASGI web framework with a Rust core (routing, JSON, PostgreSQL)
28
+ License-Expression: Apache-2.0
29
+ Requires-Python: >=3.12
30
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
31
+
32
+ # Ferronit
33
+
34
+ Высокопроизводительный Python ASGI-фреймворк с ядром на Rust. Маршрутизация,
35
+ разбор запроса, JSON, gzip и CORS работают в нативном коде; ваши хендлеры —
36
+ обычный Python.
37
+
38
+ **Документация:** [`docs/`](docs/README.md) — быстрый старт, роутинг, запросы,
39
+ инъекция, слой данных (три варианта), DDD/DI, Rust-ядро, бенчмарки, ASVS.
40
+
41
+ ## Установка
42
+
43
+ ```bash
44
+ pip install ferronit # ставит сразу Python-слой и нативное ядро (ferronit._core + ferronit.db)
45
+ ```
46
+
47
+ Ferronit — **один пакет**, собранный [maturin](https://www.maturin.rs)-ом как
48
+ mixed-проект. Ядро (`ferronit._core`) собирается с фичей `abi3-py312` — один wheel
49
+ работает на всех CPython от 3.12 до 3.14+. Внешних runtime-зависимостей нет.
50
+
51
+ ```python
52
+ # app.py
53
+ from ferronit import Ferronit
54
+
55
+ app = Ferronit()
56
+
57
+ @app.route("/hello/{name}")
58
+ async def hello(name: str):
59
+ return {"hello": name}
60
+ ```
61
+
62
+ ```bash
63
+ ferronit dev # dev-сервер (uvicorn, reload)
64
+ ferronit dev --server granian # granian (Rust, ~4× быстрее)
65
+ ferronit run --workers 4 # прод: granian, fallback uvicorn
66
+ ```
67
+
68
+ ## Почему быстро
69
+
70
+ Маршрутизация — Rust `matchit`, фактически O(1): Ferronit не деградирует с ростом
71
+ числа маршрутов, FastAPI теряет до 4× внутри одной таблицы. Методика — только
72
+ `ab` (C-клиент); полный разбор — [`docs/benchmarks.md`](docs/benchmarks.md).
73
+
74
+ | Сценарий | Ferronit | FastAPI | Разрыв |
75
+ |---|---|---|---|
76
+ | uvicorn, 1000 маршрутов | 20 216 req/s | 2 817 req/s | ×7.2 |
77
+ | granian, 1000 маршрутов | 94 873 req/s | 3 416 req/s | **×27.8** |
78
+
79
+ ## Слой данных
80
+
81
+ Три варианта под разные задачи — от «запрос → JSON целиком в Rust» до
82
+ полноценного ORM. Какой выбрать: [`docs/data/overview.md`](docs/data/overview.md).
83
+
84
+ ## Разработка
85
+
86
+ ```bash
87
+ poetry install --all-extras # окружение в .venv + все зависимости
88
+ PYO3_USE_ABI3_FORWARD_COMPATIBILITY=1 poetry run maturin develop --release # Rust-ядро
89
+ ./scripts/check.sh # линт → типы → докстринги → сборка ядра → тесты
90
+ poetry run pytest tests/ -q # 263 теста
91
+ ```
92
+
93
+ Окружение ведёт Poetry (`poetry.toml` — venv внутри проекта), wheel с Rust-ядром собирает
94
+ maturin (см. `[tool.maturin]` в `pyproject.toml`), поэтому сам проект Poetry не ставит.
95
+
96
+ - **AGENTS.md** — инструкция для код-агентов (Claude Code, Codex, Cursor, ...).
97
+ - **`examples/`** — minimal, DI, LLM + SSE, RAG, WebSocket; `examples/app.py` — DDD-пример.
98
+ - Пакет помечен `py.typed`; для Rust-ядра лежит `ferronit/_core.pyi`.
99
+ - `bench/` — измерительный стенд (все цифры выше), не входит в пакет.
100
+
101
+ ## Релиз
102
+
103
+ ```bash
104
+ # версия правится в двух файлах: ferronit/__init__.py и ferronit-rs/Cargo.toml
105
+ git tag -a v0.8.2 -m "Ferronit 0.8.2" && git push origin v0.8.2
106
+ ```
107
+
108
+ Тег `v*` запускает `.github/workflows/release.yml`: проверки и тесты → колёса (Linux glibc/musl,
109
+ macOS, Windows) и sdist → GitHub Release с артефактами → публикация на PyPI (Trusted Publishing).
110
+ Если версия тега не совпадает с `Cargo.toml`/`__init__.py`, workflow падает до публикации.
111
+
112
+ ## Docker
113
+
114
+ ```bash
115
+ docker build -t ferronit:0.9.0 .
116
+ docker run --rm -p 8000:8000 ferronit:0.9.0
117
+ ```
118
+
119
+ ## Лицензия
120
+
121
+ Apache License 2.0 — см. [LICENSE](LICENSE). Использование, изменение и распространение
122
+ разрешены, включая коммерческое; сохраняются уведомления об авторстве и патентная оговорка.
123
+
124
+
@@ -0,0 +1,92 @@
1
+ # Ferronit
2
+
3
+ Высокопроизводительный Python ASGI-фреймворк с ядром на Rust. Маршрутизация,
4
+ разбор запроса, JSON, gzip и CORS работают в нативном коде; ваши хендлеры —
5
+ обычный Python.
6
+
7
+ **Документация:** [`docs/`](docs/README.md) — быстрый старт, роутинг, запросы,
8
+ инъекция, слой данных (три варианта), DDD/DI, Rust-ядро, бенчмарки, ASVS.
9
+
10
+ ## Установка
11
+
12
+ ```bash
13
+ pip install ferronit # ставит сразу Python-слой и нативное ядро (ferronit._core + ferronit.db)
14
+ ```
15
+
16
+ Ferronit — **один пакет**, собранный [maturin](https://www.maturin.rs)-ом как
17
+ mixed-проект. Ядро (`ferronit._core`) собирается с фичей `abi3-py312` — один wheel
18
+ работает на всех CPython от 3.12 до 3.14+. Внешних runtime-зависимостей нет.
19
+
20
+ ```python
21
+ # app.py
22
+ from ferronit import Ferronit
23
+
24
+ app = Ferronit()
25
+
26
+ @app.route("/hello/{name}")
27
+ async def hello(name: str):
28
+ return {"hello": name}
29
+ ```
30
+
31
+ ```bash
32
+ ferronit dev # dev-сервер (uvicorn, reload)
33
+ ferronit dev --server granian # granian (Rust, ~4× быстрее)
34
+ ferronit run --workers 4 # прод: granian, fallback uvicorn
35
+ ```
36
+
37
+ ## Почему быстро
38
+
39
+ Маршрутизация — Rust `matchit`, фактически O(1): Ferronit не деградирует с ростом
40
+ числа маршрутов, FastAPI теряет до 4× внутри одной таблицы. Методика — только
41
+ `ab` (C-клиент); полный разбор — [`docs/benchmarks.md`](docs/benchmarks.md).
42
+
43
+ | Сценарий | Ferronit | FastAPI | Разрыв |
44
+ |---|---|---|---|
45
+ | uvicorn, 1000 маршрутов | 20 216 req/s | 2 817 req/s | ×7.2 |
46
+ | granian, 1000 маршрутов | 94 873 req/s | 3 416 req/s | **×27.8** |
47
+
48
+ ## Слой данных
49
+
50
+ Три варианта под разные задачи — от «запрос → JSON целиком в Rust» до
51
+ полноценного ORM. Какой выбрать: [`docs/data/overview.md`](docs/data/overview.md).
52
+
53
+ ## Разработка
54
+
55
+ ```bash
56
+ poetry install --all-extras # окружение в .venv + все зависимости
57
+ PYO3_USE_ABI3_FORWARD_COMPATIBILITY=1 poetry run maturin develop --release # Rust-ядро
58
+ ./scripts/check.sh # линт → типы → докстринги → сборка ядра → тесты
59
+ poetry run pytest tests/ -q # 263 теста
60
+ ```
61
+
62
+ Окружение ведёт Poetry (`poetry.toml` — venv внутри проекта), wheel с Rust-ядром собирает
63
+ maturin (см. `[tool.maturin]` в `pyproject.toml`), поэтому сам проект Poetry не ставит.
64
+
65
+ - **AGENTS.md** — инструкция для код-агентов (Claude Code, Codex, Cursor, ...).
66
+ - **`examples/`** — minimal, DI, LLM + SSE, RAG, WebSocket; `examples/app.py` — DDD-пример.
67
+ - Пакет помечен `py.typed`; для Rust-ядра лежит `ferronit/_core.pyi`.
68
+ - `bench/` — измерительный стенд (все цифры выше), не входит в пакет.
69
+
70
+ ## Релиз
71
+
72
+ ```bash
73
+ # версия правится в двух файлах: ferronit/__init__.py и ferronit-rs/Cargo.toml
74
+ git tag -a v0.8.2 -m "Ferronit 0.8.2" && git push origin v0.8.2
75
+ ```
76
+
77
+ Тег `v*` запускает `.github/workflows/release.yml`: проверки и тесты → колёса (Linux glibc/musl,
78
+ macOS, Windows) и sdist → GitHub Release с артефактами → публикация на PyPI (Trusted Publishing).
79
+ Если версия тега не совпадает с `Cargo.toml`/`__init__.py`, workflow падает до публикации.
80
+
81
+ ## Docker
82
+
83
+ ```bash
84
+ docker build -t ferronit:0.9.0 .
85
+ docker run --rm -p 8000:8000 ferronit:0.9.0
86
+ ```
87
+
88
+ ## Лицензия
89
+
90
+ Apache License 2.0 — см. [LICENSE](LICENSE). Использование, изменение и распространение
91
+ разрешены, включая коммерческое; сохраняются уведомления об авторстве и патентная оговорка.
92
+
@@ -0,0 +1,23 @@
1
+ """Ferronit — High-performance ASGI web framework with DDD support."""
2
+
3
+ from ferronit import db
4
+ from ferronit.core.app import Ferronit
5
+ from ferronit.core.request import Request, UploadedFile
6
+ from ferronit.core.response import JSONResponse, Response, StreamingResponse, TextResponse
7
+ from ferronit.injection import Header
8
+ from ferronit.websocket import WebSocket, WebSocketState
9
+
10
+ __all__ = [
11
+ "Ferronit",
12
+ "Header",
13
+ "JSONResponse",
14
+ "Request",
15
+ "Response",
16
+ "StreamingResponse",
17
+ "TextResponse",
18
+ "UploadedFile",
19
+ "WebSocket",
20
+ "WebSocketState",
21
+ "db",
22
+ ]
23
+ __version__ = "0.9.0"
@@ -0,0 +1,117 @@
1
+ """Type stubs for the Ferronit Rust core (``ferronit._core``).
2
+
3
+ Собирается maturin-ом вместе с расширением: файл попадает в wheel, поэтому mypy
4
+ и IDE видят типы нативного ядра, а не только расширение без аннотаций.
5
+ """
6
+
7
+ from typing import Any
8
+
9
+ __all__ = ["FerronitApp", "Request", "Response", "Router", "db"]
10
+
11
+ # Вложенный модуль данных (PostgreSQL → JSON в Rust): connect / query_json.
12
+ db: Any
13
+
14
+ class Router:
15
+ """Conflict-free router over method+path patterns (matchit under the hood)."""
16
+
17
+ def __init__(self) -> None: ...
18
+ def add(self, method: str, pattern: str, handler: Any) -> None:
19
+ """Register ``handler`` for ``"{METHOD} {pattern}"``; raises ValueError on a bad pattern."""
20
+
21
+ def lookup(
22
+ self, method: str, path: str
23
+ ) -> tuple[Any, dict[str, str] | None] | None:
24
+ """Return ``(handler, params)`` or ``None``.
25
+
26
+ ``params`` is ``None`` when the route has no path parameters — the common
27
+ case, which avoids allocating a dict per request.
28
+ """
29
+
30
+ class Request:
31
+ """Parsed request: method/path/query are Rust-side, headers are parsed lazily."""
32
+
33
+ def __init__(self, method: str, path: str, query_string: str) -> None: ...
34
+ @property
35
+ def method(self) -> str: ...
36
+ @property
37
+ def path(self) -> str: ...
38
+ @property
39
+ def query_string(self) -> str: ...
40
+ @property
41
+ def headers(self) -> dict[str, str]:
42
+ """Lowercased header name → value; built on first access."""
43
+
44
+ @property
45
+ def query(self) -> dict[str, list[str]]:
46
+ """URL-decoded query params; every value is a list (repeated keys accumulate)."""
47
+
48
+ def set_headers(self, raw_headers: list[tuple[bytes, bytes]]) -> None:
49
+ """Store raw header bytes without parsing (fast path)."""
50
+
51
+ def get_header(self, name: str) -> str | None:
52
+ """Case-insensitive lookup over raw bytes; `None` when absent."""
53
+
54
+ def set_body(self, body: bytes) -> None: ...
55
+ def json(self) -> Any:
56
+ """Parse the body as JSON; raises ValueError on malformed input."""
57
+
58
+ def parse_multipart(
59
+ self, boundary: str
60
+ ) -> tuple[dict[str, list[str]], dict[str, list[tuple[str, str, bytes]]]]:
61
+ """Parse a multipart/form-data body: (fields, files)."""
62
+
63
+ class Response:
64
+ """Rust-built response: status, body bytes and content type."""
65
+
66
+ def __init__(self, body: bytes, status: int, content_type: str) -> None: ...
67
+ @property
68
+ def status(self) -> int: ...
69
+ @property
70
+ def body(self) -> bytes: ...
71
+ @property
72
+ def content_type(self) -> str: ...
73
+ @staticmethod
74
+ def json(data: Any, status: int | None = ...) -> Response:
75
+ """Serialize ``data`` with serde_json, escaping HTML-significant characters."""
76
+
77
+ @staticmethod
78
+ def text(text: str, status: int | None = ...) -> Response: ...
79
+
80
+ class FerronitApp:
81
+ """Owns the router and CORS config; resolves routes for the Python ASGI layer."""
82
+
83
+ def __init__(self) -> None: ...
84
+ def set_cors(
85
+ self,
86
+ origins: str | None,
87
+ methods: str | None,
88
+ headers: str | None,
89
+ max_age: str | None,
90
+ ) -> None:
91
+ """Configure CORS; ``origins`` is a comma-separated list, empty means ``"*"``."""
92
+
93
+ def cors_allows(self, origin: str) -> bool: ...
94
+ def cors_is_wildcard(self) -> bool: ...
95
+ def add_route(self, method: str, path: str, handler: Any) -> None: ...
96
+ def resolve(
97
+ self, method: str, path: str
98
+ ) -> tuple[Any, dict[str, str] | None] | None:
99
+ """Look up a handler for ``method``/``path``."""
100
+
101
+ def has_cors(self) -> bool: ...
102
+ def cors_preflight_headers(self, origin: str) -> dict[str, str] | None:
103
+ """Preflight headers when ``origin`` is allowed, else ``None``."""
104
+
105
+ def cors_origin(self, origin: str) -> str | None:
106
+ """``Access-Control-Allow-Origin`` value for allowed origins, else ``None``."""
107
+
108
+ def gzip_compress(self, data: bytes) -> bytes: ...
109
+ def handle_request(
110
+ self,
111
+ method: str,
112
+ path: str,
113
+ query_string: str,
114
+ raw_headers: list[tuple[bytes, bytes]],
115
+ body: bytes,
116
+ ) -> Response:
117
+ """Route one request and call the Python handler directly (used by benchmarks)."""