py2axum 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.
Files changed (102) hide show
  1. py2axum-0.1.0/.gitignore +16 -0
  2. py2axum-0.1.0/CHANGELOG.md +26 -0
  3. py2axum-0.1.0/CONTRIBUTING.md +66 -0
  4. py2axum-0.1.0/LICENSE +202 -0
  5. py2axum-0.1.0/NOTICE +5 -0
  6. py2axum-0.1.0/PKG-INFO +151 -0
  7. py2axum-0.1.0/README.md +116 -0
  8. py2axum-0.1.0/docs/conformance.md +56 -0
  9. py2axum-0.1.0/docs/docker.md +75 -0
  10. py2axum-0.1.0/docs/how-it-works.md +71 -0
  11. py2axum-0.1.0/docs/supported.md +243 -0
  12. py2axum-0.1.0/examples/notes/Dockerfile +32 -0
  13. py2axum-0.1.0/examples/notes/README.md +20 -0
  14. py2axum-0.1.0/examples/notes/app/__init__.py +0 -0
  15. py2axum-0.1.0/examples/notes/app/db.py +23 -0
  16. py2axum-0.1.0/examples/notes/app/main.py +88 -0
  17. py2axum-0.1.0/examples/notes/app/models.py +32 -0
  18. py2axum-0.1.0/examples/notes/app/schemas.py +44 -0
  19. py2axum-0.1.0/examples/notes/docker-compose.yml +24 -0
  20. py2axum-0.1.0/examples/notes/schema.sql +13 -0
  21. py2axum-0.1.0/fixtures/dynapp/__init__.py +0 -0
  22. py2axum-0.1.0/fixtures/dynapp/aio.py +101 -0
  23. py2axum-0.1.0/fixtures/dynapp/amqp.py +60 -0
  24. py2axum-0.1.0/fixtures/dynapp/bgloop.py +146 -0
  25. py2axum-0.1.0/fixtures/dynapp/colls.py +49 -0
  26. py2axum-0.1.0/fixtures/dynapp/coltypes.py +60 -0
  27. py2axum-0.1.0/fixtures/dynapp/composite.py +148 -0
  28. py2axum-0.1.0/fixtures/dynapp/db.py +26 -0
  29. py2axum-0.1.0/fixtures/dynapp/decos.py +230 -0
  30. py2axum-0.1.0/fixtures/dynapp/dunders.py +268 -0
  31. py2axum-0.1.0/fixtures/dynapp/enums.py +22 -0
  32. py2axum-0.1.0/fixtures/dynapp/lazydata.py +17 -0
  33. py2axum-0.1.0/fixtures/dynapp/lazyimp.py +40 -0
  34. py2axum-0.1.0/fixtures/dynapp/libs.py +780 -0
  35. py2axum-0.1.0/fixtures/dynapp/main.py +1114 -0
  36. py2axum-0.1.0/fixtures/dynapp/models.py +84 -0
  37. py2axum-0.1.0/fixtures/dynapp/pk.py +94 -0
  38. py2axum-0.1.0/fixtures/dynapp/rds.py +61 -0
  39. py2axum-0.1.0/fixtures/dynapp/retrying.py +133 -0
  40. py2axum-0.1.0/fixtures/dynapp/schemas.py +256 -0
  41. py2axum-0.1.0/fixtures/dynapp/templates/email/base.html +5 -0
  42. py2axum-0.1.0/fixtures/dynapp/templates/email/hello.html +7 -0
  43. py2axum-0.1.0/fixtures/dynapp/test_alembic.ini +10 -0
  44. py2axum-0.1.0/fixtures/factoryapp/__init__.py +0 -0
  45. py2axum-0.1.0/fixtures/factoryapp/main.py +111 -0
  46. py2axum-0.1.0/fixtures/factoryapp/middleware.py +45 -0
  47. py2axum-0.1.0/py2axum/__init__.py +0 -0
  48. py2axum-0.1.0/py2axum/__main__.py +81 -0
  49. py2axum-0.1.0/py2axum/body.py +1180 -0
  50. py2axum-0.1.0/py2axum/codegen.py +493 -0
  51. py2axum-0.1.0/py2axum/dyn.py +5370 -0
  52. py2axum-0.1.0/py2axum/frontend.py +812 -0
  53. py2axum-0.1.0/py2axum/ir.py +180 -0
  54. py2axum-0.1.0/py2axum/libmap.py +559 -0
  55. py2axum-0.1.0/py2axum/modules.py +249 -0
  56. py2axum-0.1.0/py2axum/report.py +234 -0
  57. py2axum-0.1.0/py2axum/runtime/Cargo.lock +4421 -0
  58. py2axum-0.1.0/py2axum/runtime/dynrt/aio.rs +224 -0
  59. py2axum-0.1.0/py2axum/runtime/dynrt/asgi.rs +534 -0
  60. py2axum-0.1.0/py2axum/runtime/dynrt/auth.rs +335 -0
  61. py2axum-0.1.0/py2axum/runtime/dynrt/decimal.rs +474 -0
  62. py2axum-0.1.0/py2axum/runtime/dynrt/dt.rs +484 -0
  63. py2axum-0.1.0/py2axum/runtime/dynrt/email.rs +276 -0
  64. py2axum-0.1.0/py2axum/runtime/dynrt/fernet.rs +106 -0
  65. py2axum-0.1.0/py2axum/runtime/dynrt/files.rs +150 -0
  66. py2axum-0.1.0/py2axum/runtime/dynrt/google.rs +206 -0
  67. py2axum-0.1.0/py2axum/runtime/dynrt/http.rs +586 -0
  68. py2axum-0.1.0/py2axum/runtime/dynrt/ini.rs +141 -0
  69. py2axum-0.1.0/py2axum/runtime/dynrt/itsd.rs +207 -0
  70. py2axum-0.1.0/py2axum/runtime/dynrt/jose.rs +422 -0
  71. py2axum-0.1.0/py2axum/runtime/dynrt/libs.rs +669 -0
  72. py2axum-0.1.0/py2axum/runtime/dynrt/mail.rs +537 -0
  73. py2axum-0.1.0/py2axum/runtime/dynrt/methods.rs +1941 -0
  74. py2axum-0.1.0/py2axum/runtime/dynrt/mod.rs +570 -0
  75. py2axum-0.1.0/py2axum/runtime/dynrt/ops.rs +1572 -0
  76. py2axum-0.1.0/py2axum/runtime/dynrt/orm.rs +3747 -0
  77. py2axum-0.1.0/py2axum/runtime/dynrt/pathio.rs +395 -0
  78. py2axum-0.1.0/py2axum/runtime/dynrt/pickle.rs +904 -0
  79. py2axum-0.1.0/py2axum/runtime/dynrt/pyd.rs +1706 -0
  80. py2axum-0.1.0/py2axum/runtime/dynrt/rds.rs +337 -0
  81. py2axum-0.1.0/py2axum/runtime/dynrt/resp.rs +482 -0
  82. py2axum-0.1.0/py2axum/runtime/dynrt/rmq.rs +332 -0
  83. py2axum-0.1.0/py2axum/runtime/dynrt/stdlib.rs +1526 -0
  84. py2axum-0.1.0/py2axum/runtime/dynrt/sysmon.rs +121 -0
  85. py2axum-0.1.0/py2axum/runtime/dynrt/tenacity.rs +570 -0
  86. py2axum-0.1.0/py2axum/runtime/dynrt/thread.rs +481 -0
  87. py2axum-0.1.0/py2axum/runtime/dynrt/types.rs +209 -0
  88. py2axum-0.1.0/py2axum/runtime/dynrt/v.rs +790 -0
  89. py2axum-0.1.0/py2axum/runtime/dynrt/web.rs +1015 -0
  90. py2axum-0.1.0/py2axum/runtime/dynrt/webpush.rs +280 -0
  91. py2axum-0.1.0/py2axum/runtime/rt.rs +826 -0
  92. py2axum-0.1.0/pyproject.toml +58 -0
  93. py2axum-0.1.0/tests/conformance.py +151 -0
  94. py2axum-0.1.0/tests/push_sink.py +96 -0
  95. py2axum-0.1.0/tests/scenarios/__init__.py +0 -0
  96. py2axum-0.1.0/tests/scenarios/app.py +72 -0
  97. py2axum-0.1.0/tests/scenarios/dynapp.py +628 -0
  98. py2axum-0.1.0/tests/scenarios/factoryapp.py +39 -0
  99. py2axum-0.1.0/tests/scenarios/notes.py +42 -0
  100. py2axum-0.1.0/tests/test_rejects.py +155 -0
  101. py2axum-0.1.0/tests/test_rejects_dyn.py +434 -0
  102. py2axum-0.1.0/tests/test_report.py +147 -0
@@ -0,0 +1,16 @@
1
+ target/
2
+ __pycache__/
3
+ .pytest_cache/
4
+ *.tar.gz
5
+ *.bundle
6
+ .venv/
7
+ .cargo/
8
+ .cache/
9
+ logs/
10
+ reports/
11
+ # generated crates, except the typed backend's committed reference output
12
+ generated/*
13
+ !generated/app_axum/
14
+ storage-test/
15
+ dist/
16
+ *.egg-info/
@@ -0,0 +1,26 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/).
5
+
6
+ ## [Unreleased]
7
+
8
+ - aio-pika 10: connect, channels, durable queues, publishing with confirms, `queue.get()`.
9
+ - `json.loads` accepts bytes (UTF-8/16/32 detection, like CPython).
10
+ - `importlib.import_module` of a literal project module (module objects), `callable()`.
11
+ - `collections.defaultdict` (builtin type factories), `string.Formatter().vformat/format`; `str.format`
12
+ gains `!r`/`!s` and CPython's error messages.
13
+ - tenacity 9 (`@retry` and its strategies). `g`/`e`/`G`/`E`/`X`/`o`/`b` presentations and `#` in `format()`
14
+ and `%`; `ConnectionError` and its subclasses; `logging` level constants and `Logger.log`.
15
+
16
+ ## [0.1.0] — first public release
17
+
18
+ - Ahead-of-time compilation of FastAPI + SQLAlchemy 2.0 (async, PostgreSQL) + Pydantic v2 applications to
19
+ Rust (axum, tokio, sqlx): the **dyn** backend (general) and the **typed** backend (simple CRUD).
20
+ - Runtime reproducing CPython, Pydantic v2, SQLAlchemy and Starlette semantics, plus a closed list of
21
+ standard and third-party libraries ([docs/supported.md](docs/supported.md)).
22
+ - `--report`: per-route coverage report with the first blocking construct (`file:line`).
23
+ - `--python-side`: paths and `lifespan` left to the Python application, relayed by the binary when
24
+ `PY2AXUM_PYTHON_URL` is set.
25
+ - Differential conformance harness (`tests/conformance.py`) and reference applications.
26
+ - `pip install`-able package with a `py2axum` command; example application with a multi-stage Dockerfile.
@@ -0,0 +1,66 @@
1
+ # Contributing to py2axum
2
+
3
+ Thanks for helping! The most useful contributions are **real constructs that do not translate yet** and
4
+ **behaviours that differ from Python**.
5
+
6
+ ## Reporting a construct or a difference
7
+
8
+ Open an issue with:
9
+
10
+ 1. the smallest Python snippet that shows it (a route is ideal);
11
+ 2. what FastAPI answers (status, headers, body) and what the binary answers, or py2axum's error message;
12
+ 3. the versions involved (Python, FastAPI, Pydantic, SQLAlchemy — or your `uv.lock`).
13
+
14
+ `py2axum <package> --root <root> --report coverage.md` lists, per route, the first blocking construct with
15
+ `file:line`: attach the relevant lines.
16
+
17
+ ## Development setup
18
+
19
+ ```bash
20
+ uv venv && uv pip install -e ".[dev,conformance]"
21
+ python -m pytest # transpiler tests (rejections, report)
22
+ ```
23
+
24
+ Conformance suites need PostgreSQL (and Redis and RabbitMQ for `dynapp`):
25
+
26
+ ```bash
27
+ createdb py2axum_dyn
28
+ export DATABASE_URL=postgresql://postgres@127.0.0.1/py2axum_dyn
29
+ python -m py2axum fixtures/dynapp --root . --backend dyn --python-side '/dunders/proxied/{name}' \
30
+ -o generated/dynapp_axum --name dynapp_axum
31
+ (cd generated/dynapp_axum && RUSTFLAGS="-D warnings" cargo build --release)
32
+ python -c "from tests.scenarios import dynapp; dynapp.reset('$DATABASE_URL')"
33
+ ./scripts_start_dyn.sh
34
+ python tests/conformance.py http://127.0.0.1:8200 http://127.0.0.1:8280 --scenario dynapp
35
+ ```
36
+
37
+ ## The rules of the project
38
+
39
+ 1. **Observable equivalence.** A translated construct behaves like Python: status, headers, content type and
40
+ body bytes (JSON key order, Pydantic error details). Every new behaviour comes with a conformance case in
41
+ a fixture app (`fixtures/`) compared against FastAPI.
42
+ 2. **Refuse rather than guess.** What the runtime cannot reproduce is refused at compile time with a
43
+ `TranspileError` pointing at `file:line`, and a test in `tests/test_rejects_dyn.py`. Never translate a
44
+ construct approximately and silently.
45
+ 3. **Document every difference** in [docs/supported.md](docs/supported.md).
46
+ 4. **Library behaviour follows the project's locked version** (`uv.lock`) when it changed across versions.
47
+ 5. The generated crate must build with `RUSTFLAGS="-D warnings"`; never edit generated code by hand — fix the
48
+ transpiler or the runtime.
49
+
50
+ ## Where things are
51
+
52
+ - `py2axum/dyn.py` — the compiler of project code (dyn backend); `libmap.py` — the library map.
53
+ - `py2axum/runtime/dynrt/*.rs` — the runtime (one module per area or library).
54
+ - `fixtures/dynapp/` — the reference app; add your case to the module that fits (or a new router) and a
55
+ request to `tests/scenarios/dynapp.py`.
56
+
57
+ ## Pull requests
58
+
59
+ Keep them focused, describe the Python behaviour you reproduce (with the library version), and include the
60
+ conformance result. By contributing you agree that your contribution is licensed under the Apache License 2.0.
61
+
62
+ ## Releasing
63
+
64
+ 1. Update `version` in `pyproject.toml` and `CHANGELOG.md`; tag `vX.Y.Z` and create the GitHub release.
65
+ 2. Run the **Publish to PyPI** workflow on that tag (Trusted Publishing: the PyPI project's trusted
66
+ publisher names this repository, `release.yml` and the `pypi` environment).
py2axum-0.1.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 [yyyy] [name of copyright owner]
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.
py2axum-0.1.0/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ py2axum
2
+ Copyright 2026 Larry Motalavigne
3
+
4
+ This product includes software developed as part of the py2axum project
5
+ (https://github.com/larrymotalavigne/py2axum), licensed under the Apache License, Version 2.0.
py2axum-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,151 @@
1
+ Metadata-Version: 2.5
2
+ Name: py2axum
3
+ Version: 0.1.0
4
+ Summary: Ahead-of-time compiler from FastAPI + SQLAlchemy + Pydantic applications to Rust (axum), with response-level conformance testing
5
+ Project-URL: Homepage, https://github.com/larrymotalavigne/py2axum
6
+ Project-URL: Issues, https://github.com/larrymotalavigne/py2axum/issues
7
+ Author: Larry Motalavigne
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ License-File: NOTICE
11
+ Keywords: axum,compiler,fastapi,performance,pydantic,rust,sqlalchemy,transpiler
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Framework :: FastAPI
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Programming Language :: Rust
21
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
22
+ Classifier: Topic :: Software Development :: Compilers
23
+ Requires-Python: >=3.12
24
+ Provides-Extra: conformance
25
+ Requires-Dist: fastapi>=0.115; extra == 'conformance'
26
+ Requires-Dist: httpx>=0.27; extra == 'conformance'
27
+ Requires-Dist: psycopg[binary]>=3.2; extra == 'conformance'
28
+ Requires-Dist: pydantic[email]>=2.9; extra == 'conformance'
29
+ Requires-Dist: sqlalchemy[asyncio]>=2.0; extra == 'conformance'
30
+ Requires-Dist: uvicorn[standard]>=0.30; extra == 'conformance'
31
+ Provides-Extra: dev
32
+ Requires-Dist: pytest>=8; extra == 'dev'
33
+ Requires-Dist: ruff>=0.6; extra == 'dev'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # py2axum
37
+
38
+ **Compile a FastAPI + SQLAlchemy + Pydantic application ahead of time into a Rust ([axum](https://github.com/tokio-rs/axum)) binary — and prove, response by response, that it behaves like the Python app.**
39
+
40
+ You keep writing, testing and debugging your API in idiomatic Python. `py2axum` reads the source (it never imports or runs it), compiles every route and the project code it reaches into Rust over a small runtime that reproduces CPython, Pydantic v2, SQLAlchemy 2.0 (async) and Starlette semantics, and produces a self-contained binary for production.
41
+
42
+ ```
43
+ app/ (FastAPI) ──py2axum──▶ Rust crate (axum + tokio + sqlx) ──cargo──▶ one static-ish binary
44
+ ```
45
+
46
+ On the bundled example ([`examples/notes`](examples/notes)), same machine (Apple M1 Pro), same PostgreSQL, 4 uvicorn workers vs 4 tokio threads, 64 connections:
47
+
48
+ | Endpoint | FastAPI + uvicorn | py2axum binary | |
49
+ |---|---:|---:|---:|
50
+ | `GET /notes/1` (1 SELECT + relationship) | 4 276 req/s, p99 40 ms | **17 674 req/s, p99 4.1 ms** | ×4.1 |
51
+ | `GET /notes?limit=20` | 3 149 req/s, p99 47 ms | **11 822 req/s, p99 6.9 ms** | ×3.8 |
52
+ | `GET /health` | 76 712 req/s | **130 105 req/s** | ×1.7 |
53
+
54
+ The binary used 19 MB of RSS under load. Gains depend on how much of your request time is Python (validation, serialization, ORM) versus the database: measure your own app with `bench/`.
55
+
56
+ > **Status: alpha.** py2axum translates a *closed, growing subset* of Python and of a list of libraries. Anything outside it is **refused at compile time with `file:line`** — never approximated silently. A per-route coverage report tells you what blocks and what each fix would unlock.
57
+
58
+ ## Why
59
+
60
+ - **Equivalence you can check.** Every supported behaviour is verified by differential testing: the same requests are sent to FastAPI and to the binary, and status, headers, content type and bodies must match **byte for byte** (JSON key order, Pydantic 422 error details and messages included). The project's own suites run 350+ such requests.
61
+ - **No rewrite, no fork.** The Python app stays the source of truth: unit tests, debugging, local development and the OpenAPI docs keep working as before.
62
+ - **Incremental.** Routes or ASGI apps that cannot be translated can stay in Python (`--python-side`): the binary relays them to a Python process, so one deployment serves both.
63
+
64
+ ## Quick start
65
+
66
+ ```bash
67
+ pip install git+https://github.com/larrymotalavigne/py2axum # Python ≥ 3.12, no dependencies (PyPI soon)
68
+
69
+ # what would translate, route by route (nothing is generated)
70
+ py2axum examples/notes/app --root examples/notes --report coverage.md
71
+
72
+ # generate the Rust crate, build it, run it
73
+ py2axum examples/notes/app --root examples/notes --backend dyn -o build/notes --name notes
74
+ cargo build --release --manifest-path build/notes/Cargo.toml
75
+ DATABASE_URL=postgresql://postgres@localhost/notes PORT=8080 ./build/notes/target/release/notes
76
+ ```
77
+
78
+ The binary reads `DATABASE_URL`, `HOST` (`0.0.0.0`), `PORT` (`8080`), plus whatever your code reads from the environment (`os.environ`, pydantic-settings). It does not create tables: run your migrations as usual.
79
+
80
+ Run the transpiler on a Python **at least as recent** as the one your app targets (the parser only knows its own syntax). Library behaviours that changed between versions (Starlette's CORS, Pydantic error URLs, CPython messages) follow the versions pinned in your project's `uv.lock`.
81
+
82
+ ## In a Dockerfile
83
+
84
+ ```dockerfile
85
+ FROM python:3.13-slim AS transpile
86
+ RUN pip install --no-cache-dir git+https://github.com/larrymotalavigne/py2axum
87
+ WORKDIR /src
88
+ COPY . .
89
+ RUN py2axum app --root . --backend dyn -o /crate --name api
90
+
91
+ FROM rust:1-bookworm AS build
92
+ WORKDIR /crate
93
+ COPY --from=transpile /crate .
94
+ RUN cargo build --release
95
+
96
+ FROM debian:bookworm-slim
97
+ RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/*
98
+ COPY --from=build /crate/target/release/api /usr/local/bin/api
99
+ EXPOSE 8080
100
+ CMD ["api"]
101
+ ```
102
+
103
+ See [docs/docker.md](docs/docker.md) for caching the cargo build, the hybrid setup (binary + Python sidecar for `--python-side` routes) and a docker-compose file.
104
+
105
+ ## Verify your own app
106
+
107
+ ```bash
108
+ # reference and candidate on the same database, reset between runs
109
+ python tests/conformance.py http://127.0.0.1:8000 http://127.0.0.1:8080 --scenario myapp
110
+ ```
111
+
112
+ A scenario is a list of requests plus a `reset()` function ([docs/conformance.md](docs/conformance.md), [`tests/scenarios/notes.py`](tests/scenarios/notes.py)). The harness prints every difference with both responses.
113
+
114
+ ## What is supported
115
+
116
+ A summary — the full list, with every documented difference from CPython, is in [docs/supported.md](docs/supported.md).
117
+
118
+ - **FastAPI / Starlette**: routes and routers (prefixes, factories, conditional registration), path/query/header/body/form/file parameters with FastAPI's exact 422 errors, dependencies (`Depends`, `yield`, per-request cache, `Annotated` aliases, OAuth2/HTTPBearer), `response_model` filtering, returned `Response` objects, `StreamingResponse`/SSE, `BackgroundTasks`, exception handlers, the middleware stack (`CORSMiddleware`, `GZipMiddleware`, `BaseHTTPMiddleware`, `@app.middleware("http")`), Starlette routing (405, trailing-slash redirects).
119
+ - **Pydantic v2**: lax-mode validation with pydantic-core's error types and messages, unions, enums, `Field` constraints and aliases, validators (`field_validator`/`model_validator`, before/after), computed defaults, `model_dump`/`model_validate`/`model_copy`, `TypeAdapter`, frozen models, URL and email types, `BaseSettings`.
120
+ - **SQLAlchemy 2.0 async**: declarative models (composite keys, `Identity`, JSON/JSONB, enums, `Numeric`, `TypeDecorator`), sessions (identity map, autoflush, `expire_on_commit`, savepoints, refresh, rollback), relationships and loader strategies, `select`/`update`/`delete`/`insert ... on conflict`, joins, aliases, subqueries, aggregates, `case`, `text()`.
121
+ - **Python**: functions, closures, decorators, classes (with `__eq__`/`__str__`/`__aenter__`...), dataclasses, exceptions, comprehensions, generators, `match`, coroutines and `asyncio` (`gather`, tasks, locks), `threading`, `pickle` (CPython-compatible bytes), `datetime`/`decimal`/`uuid`/`re`/`json`/`csv`/`base64`/`hashlib`/`hmac`/`math`/`urllib.parse`...
122
+ - **Libraries**: httpx and aiohttp clients, redis.asyncio, python-jose (HMAC), bcrypt, pyotp, itsdangerous, cryptography's Fernet, jinja2 + `email` + aiosmtplib, pywebpush, google-auth id tokens, alembic config, psutil.
123
+
124
+ Not translated (stay in Python with `--python-side`, or refused): WebSockets, `lifespan`, other libraries, arbitrary `eval`/reflection, C extensions.
125
+
126
+ ## How it works
127
+
128
+ 1. **Frontend** — indexes the package's modules and imports statically (`ast`), finds the FastAPI app(s), routers, routes, models and schemas.
129
+ 2. **Backends** — a *typed* backend emits idiomatic statically-typed Rust for simple CRUD handlers; the *dyn* backend (the general one) compiles every reachable project function to Rust over a dynamic value type with CPython semantics. Library calls go through a closed map (`py2axum/libmap.py`): anything unlisted is refused.
130
+ 3. **Runtime** — `py2axum/runtime/dynrt/` (Rust, copied into each generated crate): values and operators, Pydantic validation and serialization, the SQLAlchemy session and SQL compiler (on sqlx/PostgreSQL), Starlette's middleware and routing, and the supported libraries.
131
+
132
+ Details: [docs/how-it-works.md](docs/how-it-works.md).
133
+
134
+ ## Project layout
135
+
136
+ ```
137
+ py2axum/ the transpiler (Python, stdlib only) and the Rust runtime it embeds
138
+ examples/notes/ a small API + Dockerfile, translated in full
139
+ fixtures/ reference apps exercising the supported subset (used by the test suites)
140
+ tests/ conformance harness and scenarios, rejection tests
141
+ bench/ throughput / latency / memory benchmarks
142
+ docs/ documentation
143
+ ```
144
+
145
+ ## Contributing
146
+
147
+ Contributions are welcome — especially failing constructs from real applications. See [CONTRIBUTING.md](CONTRIBUTING.md). The rule that keeps the project honest: every new behaviour comes with a conformance case comparing it to the Python reference, and every unsupported case is refused with a test.
148
+
149
+ ## License
150
+
151
+ Apache License 2.0 — see [LICENSE](LICENSE).
@@ -0,0 +1,116 @@
1
+ # py2axum
2
+
3
+ **Compile a FastAPI + SQLAlchemy + Pydantic application ahead of time into a Rust ([axum](https://github.com/tokio-rs/axum)) binary — and prove, response by response, that it behaves like the Python app.**
4
+
5
+ You keep writing, testing and debugging your API in idiomatic Python. `py2axum` reads the source (it never imports or runs it), compiles every route and the project code it reaches into Rust over a small runtime that reproduces CPython, Pydantic v2, SQLAlchemy 2.0 (async) and Starlette semantics, and produces a self-contained binary for production.
6
+
7
+ ```
8
+ app/ (FastAPI) ──py2axum──▶ Rust crate (axum + tokio + sqlx) ──cargo──▶ one static-ish binary
9
+ ```
10
+
11
+ On the bundled example ([`examples/notes`](examples/notes)), same machine (Apple M1 Pro), same PostgreSQL, 4 uvicorn workers vs 4 tokio threads, 64 connections:
12
+
13
+ | Endpoint | FastAPI + uvicorn | py2axum binary | |
14
+ |---|---:|---:|---:|
15
+ | `GET /notes/1` (1 SELECT + relationship) | 4 276 req/s, p99 40 ms | **17 674 req/s, p99 4.1 ms** | ×4.1 |
16
+ | `GET /notes?limit=20` | 3 149 req/s, p99 47 ms | **11 822 req/s, p99 6.9 ms** | ×3.8 |
17
+ | `GET /health` | 76 712 req/s | **130 105 req/s** | ×1.7 |
18
+
19
+ The binary used 19 MB of RSS under load. Gains depend on how much of your request time is Python (validation, serialization, ORM) versus the database: measure your own app with `bench/`.
20
+
21
+ > **Status: alpha.** py2axum translates a *closed, growing subset* of Python and of a list of libraries. Anything outside it is **refused at compile time with `file:line`** — never approximated silently. A per-route coverage report tells you what blocks and what each fix would unlock.
22
+
23
+ ## Why
24
+
25
+ - **Equivalence you can check.** Every supported behaviour is verified by differential testing: the same requests are sent to FastAPI and to the binary, and status, headers, content type and bodies must match **byte for byte** (JSON key order, Pydantic 422 error details and messages included). The project's own suites run 350+ such requests.
26
+ - **No rewrite, no fork.** The Python app stays the source of truth: unit tests, debugging, local development and the OpenAPI docs keep working as before.
27
+ - **Incremental.** Routes or ASGI apps that cannot be translated can stay in Python (`--python-side`): the binary relays them to a Python process, so one deployment serves both.
28
+
29
+ ## Quick start
30
+
31
+ ```bash
32
+ pip install git+https://github.com/larrymotalavigne/py2axum # Python ≥ 3.12, no dependencies (PyPI soon)
33
+
34
+ # what would translate, route by route (nothing is generated)
35
+ py2axum examples/notes/app --root examples/notes --report coverage.md
36
+
37
+ # generate the Rust crate, build it, run it
38
+ py2axum examples/notes/app --root examples/notes --backend dyn -o build/notes --name notes
39
+ cargo build --release --manifest-path build/notes/Cargo.toml
40
+ DATABASE_URL=postgresql://postgres@localhost/notes PORT=8080 ./build/notes/target/release/notes
41
+ ```
42
+
43
+ The binary reads `DATABASE_URL`, `HOST` (`0.0.0.0`), `PORT` (`8080`), plus whatever your code reads from the environment (`os.environ`, pydantic-settings). It does not create tables: run your migrations as usual.
44
+
45
+ Run the transpiler on a Python **at least as recent** as the one your app targets (the parser only knows its own syntax). Library behaviours that changed between versions (Starlette's CORS, Pydantic error URLs, CPython messages) follow the versions pinned in your project's `uv.lock`.
46
+
47
+ ## In a Dockerfile
48
+
49
+ ```dockerfile
50
+ FROM python:3.13-slim AS transpile
51
+ RUN pip install --no-cache-dir git+https://github.com/larrymotalavigne/py2axum
52
+ WORKDIR /src
53
+ COPY . .
54
+ RUN py2axum app --root . --backend dyn -o /crate --name api
55
+
56
+ FROM rust:1-bookworm AS build
57
+ WORKDIR /crate
58
+ COPY --from=transpile /crate .
59
+ RUN cargo build --release
60
+
61
+ FROM debian:bookworm-slim
62
+ RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/*
63
+ COPY --from=build /crate/target/release/api /usr/local/bin/api
64
+ EXPOSE 8080
65
+ CMD ["api"]
66
+ ```
67
+
68
+ See [docs/docker.md](docs/docker.md) for caching the cargo build, the hybrid setup (binary + Python sidecar for `--python-side` routes) and a docker-compose file.
69
+
70
+ ## Verify your own app
71
+
72
+ ```bash
73
+ # reference and candidate on the same database, reset between runs
74
+ python tests/conformance.py http://127.0.0.1:8000 http://127.0.0.1:8080 --scenario myapp
75
+ ```
76
+
77
+ A scenario is a list of requests plus a `reset()` function ([docs/conformance.md](docs/conformance.md), [`tests/scenarios/notes.py`](tests/scenarios/notes.py)). The harness prints every difference with both responses.
78
+
79
+ ## What is supported
80
+
81
+ A summary — the full list, with every documented difference from CPython, is in [docs/supported.md](docs/supported.md).
82
+
83
+ - **FastAPI / Starlette**: routes and routers (prefixes, factories, conditional registration), path/query/header/body/form/file parameters with FastAPI's exact 422 errors, dependencies (`Depends`, `yield`, per-request cache, `Annotated` aliases, OAuth2/HTTPBearer), `response_model` filtering, returned `Response` objects, `StreamingResponse`/SSE, `BackgroundTasks`, exception handlers, the middleware stack (`CORSMiddleware`, `GZipMiddleware`, `BaseHTTPMiddleware`, `@app.middleware("http")`), Starlette routing (405, trailing-slash redirects).
84
+ - **Pydantic v2**: lax-mode validation with pydantic-core's error types and messages, unions, enums, `Field` constraints and aliases, validators (`field_validator`/`model_validator`, before/after), computed defaults, `model_dump`/`model_validate`/`model_copy`, `TypeAdapter`, frozen models, URL and email types, `BaseSettings`.
85
+ - **SQLAlchemy 2.0 async**: declarative models (composite keys, `Identity`, JSON/JSONB, enums, `Numeric`, `TypeDecorator`), sessions (identity map, autoflush, `expire_on_commit`, savepoints, refresh, rollback), relationships and loader strategies, `select`/`update`/`delete`/`insert ... on conflict`, joins, aliases, subqueries, aggregates, `case`, `text()`.
86
+ - **Python**: functions, closures, decorators, classes (with `__eq__`/`__str__`/`__aenter__`...), dataclasses, exceptions, comprehensions, generators, `match`, coroutines and `asyncio` (`gather`, tasks, locks), `threading`, `pickle` (CPython-compatible bytes), `datetime`/`decimal`/`uuid`/`re`/`json`/`csv`/`base64`/`hashlib`/`hmac`/`math`/`urllib.parse`...
87
+ - **Libraries**: httpx and aiohttp clients, redis.asyncio, python-jose (HMAC), bcrypt, pyotp, itsdangerous, cryptography's Fernet, jinja2 + `email` + aiosmtplib, pywebpush, google-auth id tokens, alembic config, psutil.
88
+
89
+ Not translated (stay in Python with `--python-side`, or refused): WebSockets, `lifespan`, other libraries, arbitrary `eval`/reflection, C extensions.
90
+
91
+ ## How it works
92
+
93
+ 1. **Frontend** — indexes the package's modules and imports statically (`ast`), finds the FastAPI app(s), routers, routes, models and schemas.
94
+ 2. **Backends** — a *typed* backend emits idiomatic statically-typed Rust for simple CRUD handlers; the *dyn* backend (the general one) compiles every reachable project function to Rust over a dynamic value type with CPython semantics. Library calls go through a closed map (`py2axum/libmap.py`): anything unlisted is refused.
95
+ 3. **Runtime** — `py2axum/runtime/dynrt/` (Rust, copied into each generated crate): values and operators, Pydantic validation and serialization, the SQLAlchemy session and SQL compiler (on sqlx/PostgreSQL), Starlette's middleware and routing, and the supported libraries.
96
+
97
+ Details: [docs/how-it-works.md](docs/how-it-works.md).
98
+
99
+ ## Project layout
100
+
101
+ ```
102
+ py2axum/ the transpiler (Python, stdlib only) and the Rust runtime it embeds
103
+ examples/notes/ a small API + Dockerfile, translated in full
104
+ fixtures/ reference apps exercising the supported subset (used by the test suites)
105
+ tests/ conformance harness and scenarios, rejection tests
106
+ bench/ throughput / latency / memory benchmarks
107
+ docs/ documentation
108
+ ```
109
+
110
+ ## Contributing
111
+
112
+ Contributions are welcome — especially failing constructs from real applications. See [CONTRIBUTING.md](CONTRIBUTING.md). The rule that keeps the project honest: every new behaviour comes with a conformance case comparing it to the Python reference, and every unsupported case is refused with a test.
113
+
114
+ ## License
115
+
116
+ Apache License 2.0 — see [LICENSE](LICENSE).
@@ -0,0 +1,56 @@
1
+ # Checking that the binary behaves like your application
2
+
3
+ `tests/conformance.py` sends the same requests to two servers — the FastAPI application (reference) and the
4
+ binary (candidate) — on a database reset before each run, and compares, for every request: status, content
5
+ type, encoding, `Allow`/`Location`/`WWW-Authenticate`, cookies, middleware headers (CORS, `Vary`...) and the
6
+ body (JSON compared after parsing with key order kept, other bodies byte for byte).
7
+
8
+ ## Write a scenario
9
+
10
+ A scenario is a module in `tests/scenarios/`:
11
+
12
+ ```python
13
+ # tests/scenarios/myapp.py
14
+ SETTLE = 0.2 # optional: pause after writes (FastAPI commits after the response)
15
+
16
+ STEPS = [
17
+ ("GET", "/health", None),
18
+ ("POST", "/items", {"name": "a"}), # JSON body
19
+ ("POST", "/upload", b"raw", {"content-type": "text/plain"}), # bytes body + headers
20
+ ("GET", "/items?limit=0", None), # a 422
21
+ ]
22
+
23
+ def reset(db: str) -> None:
24
+ """Bring the database (DATABASE_URL) back to the initial state, e.g. TRUNCATE ... RESTART IDENTITY."""
25
+
26
+ def normalize(body): # optional: mask values that legitimately differ (random tokens, timestamps)
27
+ return body
28
+ ```
29
+
30
+ `HEADER_MASKS` and `COOKIE_MASKS` mask header or cookie values that are random on both sides.
31
+
32
+ ## Run it
33
+
34
+ ```bash
35
+ export DATABASE_URL=postgresql://postgres@127.0.0.1/myapp_conformance # a dedicated database
36
+ uvicorn app.main:app --port 8000 & # reference
37
+ PORT=8080 ./target/release/api & # candidate
38
+ python tests/conformance.py http://127.0.0.1:8000 http://127.0.0.1:8080 --scenario myapp
39
+ ```
40
+
41
+ The output lists every step (`ok` / `DIFF` with both responses) and ends with `N/N identical responses`.
42
+ Options: `--ignore-encoding` (compare bodies regardless of gzip). Datetimes generated at request time are
43
+ masked automatically.
44
+
45
+ ## The repository's own suites
46
+
47
+ | Scenario | Application | Requests |
48
+ |---|---|---:|
49
+ | `dynapp` | `fixtures/dynapp`: the dyn backend's reference app (every supported construct) | 418 |
50
+ | `factoryapp` | `fixtures/factoryapp`: app factory, middleware stack, exception handlers | 25 |
51
+ | `notes` | `examples/notes` | 24 |
52
+ | `app` | `app/`: the typed backend's reference app | 40 |
53
+
54
+ `dynapp` needs PostgreSQL, Redis (database 13 is flushed), RabbitMQ (`BROKER_DSN`, default
55
+ `amqp://guest:guest@localhost:5672/`; its `py2axum_test_*` queues are deleted) and the web-push sink (`tests/push_sink.py`,
56
+ started by `scripts_start_dyn.sh`).