blackbull 0.28.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 (72) hide show
  1. blackbull-0.28.0/LICENSE +201 -0
  2. blackbull-0.28.0/PKG-INFO +216 -0
  3. blackbull-0.28.0/README.md +155 -0
  4. blackbull-0.28.0/blackbull/__init__.py +49 -0
  5. blackbull-0.28.0/blackbull/actor.py +59 -0
  6. blackbull-0.28.0/blackbull/app.py +736 -0
  7. blackbull-0.28.0/blackbull/asgi.py +81 -0
  8. blackbull-0.28.0/blackbull/cli.py +381 -0
  9. blackbull-0.28.0/blackbull/client/__init__.py +45 -0
  10. blackbull-0.28.0/blackbull/client/client.py +75 -0
  11. blackbull-0.28.0/blackbull/client/exceptions.py +30 -0
  12. blackbull-0.28.0/blackbull/client/http1.py +545 -0
  13. blackbull-0.28.0/blackbull/client/http2.py +389 -0
  14. blackbull-0.28.0/blackbull/client/response.py +125 -0
  15. blackbull-0.28.0/blackbull/client/scenario.py +327 -0
  16. blackbull-0.28.0/blackbull/client/scenario_oracle.py +235 -0
  17. blackbull-0.28.0/blackbull/client/websocket.py +208 -0
  18. blackbull-0.28.0/blackbull/env.py +422 -0
  19. blackbull-0.28.0/blackbull/event.py +127 -0
  20. blackbull-0.28.0/blackbull/event_aggregator.py +161 -0
  21. blackbull-0.28.0/blackbull/headers.py +101 -0
  22. blackbull-0.28.0/blackbull/logger.py +153 -0
  23. blackbull-0.28.0/blackbull/middleware/__init__.py +67 -0
  24. blackbull-0.28.0/blackbull/middleware/base.py +2 -0
  25. blackbull-0.28.0/blackbull/middleware/cache.py +343 -0
  26. blackbull-0.28.0/blackbull/middleware/compression.py +214 -0
  27. blackbull-0.28.0/blackbull/middleware/cors.py +111 -0
  28. blackbull-0.28.0/blackbull/middleware/proxy.py +96 -0
  29. blackbull-0.28.0/blackbull/middleware/session.py +332 -0
  30. blackbull-0.28.0/blackbull/middleware/static.py +197 -0
  31. blackbull-0.28.0/blackbull/middleware/utils.py +96 -0
  32. blackbull-0.28.0/blackbull/middleware/websocket.py +22 -0
  33. blackbull-0.28.0/blackbull/openapi.py +407 -0
  34. blackbull-0.28.0/blackbull/protocol/__init__.py +0 -0
  35. blackbull-0.28.0/blackbull/protocol/frame.py +159 -0
  36. blackbull-0.28.0/blackbull/protocol/frame_types.py +705 -0
  37. blackbull-0.28.0/blackbull/protocol/hpack_fastpath.py +87 -0
  38. blackbull-0.28.0/blackbull/protocol/rsock.py +338 -0
  39. blackbull-0.28.0/blackbull/protocol/stream.py +240 -0
  40. blackbull-0.28.0/blackbull/py.typed +0 -0
  41. blackbull-0.28.0/blackbull/request.py +39 -0
  42. blackbull-0.28.0/blackbull/response.py +120 -0
  43. blackbull-0.28.0/blackbull/router.py +1027 -0
  44. blackbull-0.28.0/blackbull/server/__init__.py +1 -0
  45. blackbull-0.28.0/blackbull/server/access_log.py +119 -0
  46. blackbull-0.28.0/blackbull/server/connection_actor.py +182 -0
  47. blackbull-0.28.0/blackbull/server/constants.py +27 -0
  48. blackbull-0.28.0/blackbull/server/deadline.py +187 -0
  49. blackbull-0.28.0/blackbull/server/http1_actor.py +846 -0
  50. blackbull-0.28.0/blackbull/server/http2_actor.py +981 -0
  51. blackbull-0.28.0/blackbull/server/http2_messages.py +56 -0
  52. blackbull-0.28.0/blackbull/server/http2_ws.py +92 -0
  53. blackbull-0.28.0/blackbull/server/multiworker.py +264 -0
  54. blackbull-0.28.0/blackbull/server/parser.py +209 -0
  55. blackbull-0.28.0/blackbull/server/permessage_deflate.py +207 -0
  56. blackbull-0.28.0/blackbull/server/recipient.py +728 -0
  57. blackbull-0.28.0/blackbull/server/reload.py +180 -0
  58. blackbull-0.28.0/blackbull/server/response.py +309 -0
  59. blackbull-0.28.0/blackbull/server/sender.py +590 -0
  60. blackbull-0.28.0/blackbull/server/server.py +486 -0
  61. blackbull-0.28.0/blackbull/server/websocket_actor.py +113 -0
  62. blackbull-0.28.0/blackbull/server/worker.py +87 -0
  63. blackbull-0.28.0/blackbull/server/ws_codec.py +143 -0
  64. blackbull-0.28.0/blackbull/utils.py +153 -0
  65. blackbull-0.28.0/blackbull.egg-info/PKG-INFO +216 -0
  66. blackbull-0.28.0/blackbull.egg-info/SOURCES.txt +70 -0
  67. blackbull-0.28.0/blackbull.egg-info/dependency_links.txt +1 -0
  68. blackbull-0.28.0/blackbull.egg-info/entry_points.txt +2 -0
  69. blackbull-0.28.0/blackbull.egg-info/requires.txt +38 -0
  70. blackbull-0.28.0/blackbull.egg-info/top_level.txt +1 -0
  71. blackbull-0.28.0/pyproject.toml +125 -0
  72. blackbull-0.28.0/setup.cfg +4 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,216 @@
1
+ Metadata-Version: 2.4
2
+ Name: blackbull
3
+ Version: 0.28.0
4
+ Summary: From-scratch async ASGI 3.0 framework with native HTTP/1.1, HTTP/2 and WebSocket implementations.
5
+ Author: TOKUJI
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/TOKUJI/BlackBull
8
+ Project-URL: Documentation, https://tokuji.github.io/BlackBull/
9
+ Project-URL: Repository, https://github.com/TOKUJI/BlackBull
10
+ Project-URL: Changelog, https://github.com/TOKUJI/BlackBull/blob/master/CHANGELOG.md
11
+ Project-URL: Issues, https://github.com/TOKUJI/BlackBull/issues
12
+ Keywords: asgi,asyncio,http,http2,websocket,web,framework,server
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Framework :: AsyncIO
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Operating System :: MacOS
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Programming Language :: Python :: Implementation :: CPython
24
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
25
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
26
+ Classifier: Typing :: Typed
27
+ Requires-Python: >=3.11
28
+ Description-Content-Type: text/markdown
29
+ License-File: LICENSE
30
+ Requires-Dist: h2
31
+ Requires-Dist: hpack
32
+ Requires-Dist: beartype
33
+ Provides-Extra: compression
34
+ Requires-Dist: brotli; extra == "compression"
35
+ Requires-Dist: zstandard; extra == "compression"
36
+ Provides-Extra: validation
37
+ Provides-Extra: testing
38
+ Requires-Dist: pytest; extra == "testing"
39
+ Requires-Dist: pytest-asyncio; extra == "testing"
40
+ Requires-Dist: pytest-timeout; extra == "testing"
41
+ Requires-Dist: pytest-cov; extra == "testing"
42
+ Requires-Dist: beartype; extra == "testing"
43
+ Requires-Dist: pytest-beartype; extra == "testing"
44
+ Requires-Dist: httpx[http2]; extra == "testing"
45
+ Requires-Dist: websockets; extra == "testing"
46
+ Requires-Dist: hypothesis; extra == "testing"
47
+ Provides-Extra: docs
48
+ Requires-Dist: mkdocs-material; extra == "docs"
49
+ Requires-Dist: mkdocstrings[python]; extra == "docs"
50
+ Requires-Dist: mkdocs-gen-files; extra == "docs"
51
+ Requires-Dist: mkdocs-literate-nav; extra == "docs"
52
+ Requires-Dist: mkdocs-autorefs; extra == "docs"
53
+ Provides-Extra: speed
54
+ Requires-Dist: uvloop; extra == "speed"
55
+ Provides-Extra: reload
56
+ Requires-Dist: watchfiles; extra == "reload"
57
+ Provides-Extra: benchmark
58
+ Provides-Extra: profiling
59
+ Requires-Dist: py-spy; extra == "profiling"
60
+ Dynamic: license-file
61
+
62
+ # BlackBull
63
+
64
+ > ⚠ **Early Alpha — API may break between MINOR versions.**
65
+ > Readiness evidence: [`docs/ALPHA_READINESS.md`](docs/ALPHA_READINESS.md).
66
+ > Things to know before adopting: [`KNOWN_LIMITATIONS.md`](KNOWN_LIMITATIONS.md).
67
+
68
+ **From-scratch async ASGI 3.0 framework** with native HTTP/1.1, HTTP/2,
69
+ and WebSocket implementations — no `httptools`, no `uvicorn`, no
70
+ `hypercorn` underneath. Pure-Python protocol stack, single
71
+ deployable, zero C-extension footprint outside the standard library.
72
+
73
+ [![PyPI](https://img.shields.io/pypi/v/blackbull.svg)](https://pypi.org/project/blackbull/)
74
+ [![Python](https://img.shields.io/pypi/pyversions/blackbull.svg)](https://pypi.org/project/blackbull/)
75
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
76
+
77
+ ## Why BlackBull
78
+
79
+ - **One package, one process** — the framework *is* the server. No
80
+ separate ASGI runner; `app.run()` opens the socket and serves.
81
+ - **HTTP/1.1 + HTTP/2 + WebSocket** all implemented natively (RFC 9112
82
+ for H/1, RFC 9113 for H/2, RFC 6455 for WebSocket).
83
+ - **Pure-Python identity** — no `httptools`, no `uvloop` dependency
84
+ (uvloop available as an optional `[speed]` extra).
85
+ - **Conformance-tested** against `h2spec`, Autobahn, and a
86
+ differential nginx fuzz corpus.
87
+ - **Modern Python** — requires 3.11+, full type hints, PEP 561 typed
88
+ distribution.
89
+
90
+ ## Install
91
+
92
+ ```bash
93
+ pip install blackbull
94
+ pip install 'blackbull[compression]' # add brotli + zstandard codecs
95
+ pip install 'blackbull[speed]' # add uvloop event loop
96
+ pip install 'blackbull[reload]' # add watchfiles for --reload
97
+ ```
98
+
99
+ ## Hello, world
100
+
101
+ ```python
102
+ from blackbull import BlackBull
103
+
104
+ app = BlackBull()
105
+
106
+ @app.route(path='/')
107
+ async def hello():
108
+ return "Hello, world!"
109
+
110
+ if __name__ == '__main__':
111
+ app.run(port=8000)
112
+ ```
113
+
114
+ Run it:
115
+
116
+ ```bash
117
+ python app.py # HTTP/1.1 on :8000
118
+ ```
119
+
120
+ Or via the bundled CLI:
121
+
122
+ ```bash
123
+ blackbull app:app --bind 0.0.0.0:8000
124
+ ```
125
+
126
+ ## Simplified handlers
127
+
128
+ Route handlers may return a `str`, `bytes`, `dict`, or `Response`;
129
+ path parameters are coerced to the annotation type:
130
+
131
+ ```python
132
+ @app.route(path='/tasks/{task_id:int}')
133
+ async def get_task(task_id: int):
134
+ return {"id": task_id, "title": "..."}
135
+ ```
136
+
137
+ Drop down to full ASGI `(scope, receive, send)` whenever you need it
138
+ — routes accept either shape.
139
+
140
+ ## TLS + HTTP/2
141
+
142
+ ```python
143
+ app.run(port=8443, certfile='cert.pem', keyfile='key.pem')
144
+ ```
145
+
146
+ ALPN negotiates `h2` automatically; HTTP/1.1 clients fall back via
147
+ the same socket.
148
+
149
+ ## WebSocket
150
+
151
+ ```python
152
+ from http import HTTPMethod
153
+ from blackbull.utils import Scheme
154
+
155
+ @app.route(path='/ws', methods=[HTTPMethod.GET], scheme=Scheme.websocket)
156
+ async def ws_echo(scope, receive, send):
157
+ await receive() # websocket.connect
158
+ await send({'type': 'websocket.accept'})
159
+ while True:
160
+ msg = await receive()
161
+ if msg['type'] == 'websocket.disconnect':
162
+ break
163
+ if msg['type'] == 'websocket.receive':
164
+ await send({'type': 'websocket.send',
165
+ 'text': msg.get('text') or ''})
166
+ ```
167
+
168
+ ## Built-in middleware
169
+
170
+ Compose via `app.use(...)` or per-route `middlewares=[...]`:
171
+
172
+ | Middleware | What it does |
173
+ |------------------|---|
174
+ | `Compression` | Negotiates `br` / `zstd` / `gzip` from `Accept-Encoding` |
175
+ | `StaticFiles` | Serves files from a directory under a URL prefix |
176
+ | `Cache` | Per-worker LRU + ETag / `Cache-Control` honouring |
177
+ | `Session` | Signed-cookie sessions (HMAC-SHA256) |
178
+ | `CORS` | Preflight + actual-request header injection |
179
+ | `TrustedProxy` | Rewrites `scope['client']` / `scope['scheme']` from proxy headers |
180
+
181
+ ## OpenAPI / Swagger UI
182
+
183
+ ```python
184
+ app.enable_openapi() # publishes /openapi.json and /docs
185
+ ```
186
+
187
+ Auto-generates an OpenAPI 3.1 spec from route signatures, path-param
188
+ converters, docstrings, and `@dataclass` annotations on body
189
+ parameters. Dataclass-typed bodies are also deserialized at runtime
190
+ — `async def h(body: CreateTask): ...` receives a constructed
191
+ instance, no manual `json.loads`.
192
+
193
+ ## Examples
194
+
195
+ | Example | Demonstrates |
196
+ |---|---|
197
+ | [`examples/SimpleTaskManager/`](examples/SimpleTaskManager/) | REST API + HTML UI, middleware pipeline, route groups, SQLite, Bearer token auth |
198
+ | [`examples/ChatServer/`](examples/ChatServer/) | WebSocket, SSE, long polling side by side; Session + Compression + custom auth |
199
+ | [`examples/typed_routes_ok.py`](examples/typed_routes_ok.py) | `{param:converter}` syntax, `url_path_for` |
200
+
201
+ ## Documentation
202
+
203
+ - **Guide**: [`docs/guide.md`](docs/guide.md)
204
+ - **Architecture**: [`docs/ActorDesign.md`](docs/ActorDesign.md)
205
+ - **Changelog**: [`CHANGELOG.md`](CHANGELOG.md)
206
+
207
+ ## Versioning
208
+
209
+ BlackBull uses [ZeroVer](https://0ver.org/) prior to a 1.0 commitment.
210
+ `MINOR` advances at each sprint close; `PATCH` is for bug fixes and
211
+ harness work between sprints. See [`CHANGELOG.md`](CHANGELOG.md) for
212
+ the full release history.
213
+
214
+ ## License
215
+
216
+ [Apache License 2.0](LICENSE) — © TOKUJI.
@@ -0,0 +1,155 @@
1
+ # BlackBull
2
+
3
+ > ⚠ **Early Alpha — API may break between MINOR versions.**
4
+ > Readiness evidence: [`docs/ALPHA_READINESS.md`](docs/ALPHA_READINESS.md).
5
+ > Things to know before adopting: [`KNOWN_LIMITATIONS.md`](KNOWN_LIMITATIONS.md).
6
+
7
+ **From-scratch async ASGI 3.0 framework** with native HTTP/1.1, HTTP/2,
8
+ and WebSocket implementations — no `httptools`, no `uvicorn`, no
9
+ `hypercorn` underneath. Pure-Python protocol stack, single
10
+ deployable, zero C-extension footprint outside the standard library.
11
+
12
+ [![PyPI](https://img.shields.io/pypi/v/blackbull.svg)](https://pypi.org/project/blackbull/)
13
+ [![Python](https://img.shields.io/pypi/pyversions/blackbull.svg)](https://pypi.org/project/blackbull/)
14
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
15
+
16
+ ## Why BlackBull
17
+
18
+ - **One package, one process** — the framework *is* the server. No
19
+ separate ASGI runner; `app.run()` opens the socket and serves.
20
+ - **HTTP/1.1 + HTTP/2 + WebSocket** all implemented natively (RFC 9112
21
+ for H/1, RFC 9113 for H/2, RFC 6455 for WebSocket).
22
+ - **Pure-Python identity** — no `httptools`, no `uvloop` dependency
23
+ (uvloop available as an optional `[speed]` extra).
24
+ - **Conformance-tested** against `h2spec`, Autobahn, and a
25
+ differential nginx fuzz corpus.
26
+ - **Modern Python** — requires 3.11+, full type hints, PEP 561 typed
27
+ distribution.
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ pip install blackbull
33
+ pip install 'blackbull[compression]' # add brotli + zstandard codecs
34
+ pip install 'blackbull[speed]' # add uvloop event loop
35
+ pip install 'blackbull[reload]' # add watchfiles for --reload
36
+ ```
37
+
38
+ ## Hello, world
39
+
40
+ ```python
41
+ from blackbull import BlackBull
42
+
43
+ app = BlackBull()
44
+
45
+ @app.route(path='/')
46
+ async def hello():
47
+ return "Hello, world!"
48
+
49
+ if __name__ == '__main__':
50
+ app.run(port=8000)
51
+ ```
52
+
53
+ Run it:
54
+
55
+ ```bash
56
+ python app.py # HTTP/1.1 on :8000
57
+ ```
58
+
59
+ Or via the bundled CLI:
60
+
61
+ ```bash
62
+ blackbull app:app --bind 0.0.0.0:8000
63
+ ```
64
+
65
+ ## Simplified handlers
66
+
67
+ Route handlers may return a `str`, `bytes`, `dict`, or `Response`;
68
+ path parameters are coerced to the annotation type:
69
+
70
+ ```python
71
+ @app.route(path='/tasks/{task_id:int}')
72
+ async def get_task(task_id: int):
73
+ return {"id": task_id, "title": "..."}
74
+ ```
75
+
76
+ Drop down to full ASGI `(scope, receive, send)` whenever you need it
77
+ — routes accept either shape.
78
+
79
+ ## TLS + HTTP/2
80
+
81
+ ```python
82
+ app.run(port=8443, certfile='cert.pem', keyfile='key.pem')
83
+ ```
84
+
85
+ ALPN negotiates `h2` automatically; HTTP/1.1 clients fall back via
86
+ the same socket.
87
+
88
+ ## WebSocket
89
+
90
+ ```python
91
+ from http import HTTPMethod
92
+ from blackbull.utils import Scheme
93
+
94
+ @app.route(path='/ws', methods=[HTTPMethod.GET], scheme=Scheme.websocket)
95
+ async def ws_echo(scope, receive, send):
96
+ await receive() # websocket.connect
97
+ await send({'type': 'websocket.accept'})
98
+ while True:
99
+ msg = await receive()
100
+ if msg['type'] == 'websocket.disconnect':
101
+ break
102
+ if msg['type'] == 'websocket.receive':
103
+ await send({'type': 'websocket.send',
104
+ 'text': msg.get('text') or ''})
105
+ ```
106
+
107
+ ## Built-in middleware
108
+
109
+ Compose via `app.use(...)` or per-route `middlewares=[...]`:
110
+
111
+ | Middleware | What it does |
112
+ |------------------|---|
113
+ | `Compression` | Negotiates `br` / `zstd` / `gzip` from `Accept-Encoding` |
114
+ | `StaticFiles` | Serves files from a directory under a URL prefix |
115
+ | `Cache` | Per-worker LRU + ETag / `Cache-Control` honouring |
116
+ | `Session` | Signed-cookie sessions (HMAC-SHA256) |
117
+ | `CORS` | Preflight + actual-request header injection |
118
+ | `TrustedProxy` | Rewrites `scope['client']` / `scope['scheme']` from proxy headers |
119
+
120
+ ## OpenAPI / Swagger UI
121
+
122
+ ```python
123
+ app.enable_openapi() # publishes /openapi.json and /docs
124
+ ```
125
+
126
+ Auto-generates an OpenAPI 3.1 spec from route signatures, path-param
127
+ converters, docstrings, and `@dataclass` annotations on body
128
+ parameters. Dataclass-typed bodies are also deserialized at runtime
129
+ — `async def h(body: CreateTask): ...` receives a constructed
130
+ instance, no manual `json.loads`.
131
+
132
+ ## Examples
133
+
134
+ | Example | Demonstrates |
135
+ |---|---|
136
+ | [`examples/SimpleTaskManager/`](examples/SimpleTaskManager/) | REST API + HTML UI, middleware pipeline, route groups, SQLite, Bearer token auth |
137
+ | [`examples/ChatServer/`](examples/ChatServer/) | WebSocket, SSE, long polling side by side; Session + Compression + custom auth |
138
+ | [`examples/typed_routes_ok.py`](examples/typed_routes_ok.py) | `{param:converter}` syntax, `url_path_for` |
139
+
140
+ ## Documentation
141
+
142
+ - **Guide**: [`docs/guide.md`](docs/guide.md)
143
+ - **Architecture**: [`docs/ActorDesign.md`](docs/ActorDesign.md)
144
+ - **Changelog**: [`CHANGELOG.md`](CHANGELOG.md)
145
+
146
+ ## Versioning
147
+
148
+ BlackBull uses [ZeroVer](https://0ver.org/) prior to a 1.0 commitment.
149
+ `MINOR` advances at each sprint close; `PATCH` is for bug fixes and
150
+ harness work between sprints. See [`CHANGELOG.md`](CHANGELOG.md) for
151
+ the full release history.
152
+
153
+ ## License
154
+
155
+ [Apache License 2.0](LICENSE) — © TOKUJI.
@@ -0,0 +1,49 @@
1
+ """BlackBull — async ASGI 3.0 web framework.
2
+
3
+ **Early Alpha** — API may break between MINOR versions; see
4
+ ``docs/ALPHA_READINESS.md`` and ``KNOWN_LIMITATIONS.md`` before
5
+ building production-shape work on top.
6
+
7
+ Public API exports:
8
+
9
+ - `BlackBull`: the main application object; wraps routing, middleware, and lifespan hooks.
10
+ - `serve`: synchronous entry point that runs any ASGI 3.0 callable (also used by the ``blackbull`` console script).
11
+ - `Response`, `JSONResponse`, `StreamingResponse`, `WebSocketResponse`: response helpers.
12
+ - `Headers`: case-insensitive, ordered, multi-valued HTTP header store.
13
+ - `cookie_header`: builds a ``Set-Cookie`` header tuple.
14
+ - `read_body`: reads and buffers the full request body from the ASGI receive channel.
15
+ - `parse_cookies`: parses the ``Cookie`` header into a plain ``dict``.
16
+ - `CORS`: adds ``Access-Control-*`` headers; handles preflight OPTIONS requests.
17
+ - `as_middleware`: decorator that marks an async function or class as middleware; normalises ``send`` so inner wrappers see only ASGI event dicts.
18
+ - `TrustedProxy`: rewrites ``scope['client']`` / ``scope['scheme']`` from proxy headers.
19
+
20
+ Importing this package does **not** load the server stack
21
+ (``blackbull.server.*``). Use ``ASGIServer`` from ``blackbull.server``
22
+ when you want to embed BlackBull's own server; otherwise pass the
23
+ ``BlackBull`` instance to any external ASGI server (uvicorn, hypercorn,
24
+ granian, …) since ``BlackBull.__call__`` is ASGI 3.0 compliant.
25
+ """
26
+ import logging
27
+ logging.getLogger('blackbull').addHandler(logging.NullHandler())
28
+
29
+ # Single source of truth for the version is pyproject.toml; expose it at
30
+ # runtime via importlib.metadata so the two never drift. Falls back to a
31
+ # sentinel only when blackbull is being imported from a source checkout
32
+ # without `pip install -e .` (the test runners and `bench/app.py` both
33
+ # install editably, so this path is exercised only in unusual setups).
34
+ from importlib.metadata import PackageNotFoundError, version as _pkg_version
35
+
36
+ try:
37
+ __version__ = _pkg_version('blackbull')
38
+ except PackageNotFoundError:
39
+ __version__ = '0.0.0+unknown'
40
+
41
+ from .app import BlackBull, serve
42
+ from .headers import Headers
43
+ from .request import read_body, parse_cookies
44
+ from .response import Response, JSONResponse, StreamingResponse, WebSocketResponse, cookie_header
45
+ from .event import Event, EventHandler
46
+ from .asgi import ResponseStart, ResponseBody, parse_response_event
47
+ from .middleware.cors import CORS
48
+ from .middleware.utils import as_middleware
49
+ from .middleware.proxy import TrustedProxy
@@ -0,0 +1,59 @@
1
+ import asyncio
2
+ from collections.abc import AsyncIterator
3
+ from dataclasses import dataclass, field
4
+
5
+
6
+ @dataclass
7
+ class Message:
8
+ """Base class for all Level A Actor messages.
9
+
10
+ Subclasses are plain dataclasses — add fields with standard dataclass syntax.
11
+ The ``sender`` field is excluded from equality comparison so that message
12
+ identity is determined by payload, not by which Actor sent it.
13
+ """
14
+
15
+ sender: "Actor | None" = field(default=None, compare=False, repr=False)
16
+
17
+
18
+ class Actor:
19
+ """Base class for all BlackBull Actors.
20
+
21
+ Each Actor owns an ``asyncio.Queue`` inbox and is expected to run as an
22
+ ``asyncio.Task`` started by its Supervisor. Actors communicate
23
+ exclusively via :meth:`send`; they never share mutable state.
24
+
25
+ Subclasses must override :meth:`_handle`.
26
+ """
27
+
28
+ def __init__(self) -> None:
29
+ self.__inbox: asyncio.Queue[Message] | None = None
30
+
31
+ @property
32
+ def _inbox(self) -> asyncio.Queue[Message]:
33
+ if self.__inbox is None:
34
+ self.__inbox = asyncio.Queue()
35
+ return self.__inbox
36
+
37
+ async def run(self) -> None:
38
+ """Consume the inbox until the task is cancelled."""
39
+ async for msg in self._inbox_iter():
40
+ await self._handle(msg)
41
+
42
+ async def send(self, msg: Message) -> None:
43
+ """Enqueue *msg* to this Actor's inbox (non-blocking)."""
44
+ await self._inbox.put(msg)
45
+
46
+ async def _inbox_iter(self) -> AsyncIterator[Message]:
47
+ while True:
48
+ yield await self._inbox.get()
49
+
50
+ async def _handle(self, msg: Message) -> None:
51
+ """Dispatch a received message.
52
+
53
+ Raises:
54
+ NotImplementedError: Always — subclasses must override this method.
55
+ """
56
+ raise NotImplementedError(
57
+ f"{type(self).__name__}._handle is not implemented "
58
+ f"for message type {type(msg).__name__}"
59
+ )