http3x 0.1.0__py3-none-any.whl
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.
- http3x/__init__.py +9 -0
- http3x/_core/__init__.py +0 -0
- http3x/_core/base.py +261 -0
- http3x/_core/http3.py +0 -0
- http3x/_core/webtransport.py +283 -0
- http3x/h3.py +0 -0
- http3x/wt.py +15 -0
- http3x-0.1.0.dist-info/METADATA +108 -0
- http3x-0.1.0.dist-info/RECORD +11 -0
- http3x-0.1.0.dist-info/WHEEL +4 -0
- http3x-0.1.0.dist-info/licenses/LICENSE +190 -0
http3x/__init__.py
ADDED
http3x/_core/__init__.py
ADDED
|
File without changes
|
http3x/_core/base.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
"""
|
|
2
|
+
HTTP3X core base module.
|
|
3
|
+
|
|
4
|
+
This module contains the core classes for HTTP3X, including:
|
|
5
|
+
- DropQueue: A queue that drops items when full
|
|
6
|
+
- Signals: Signal classes for internal communication
|
|
7
|
+
- QuicConnection: QUIC connection protocol implementation
|
|
8
|
+
- WebTransportSessionRoutes: WebTransport session route management
|
|
9
|
+
- AppConfiguration: Application configuration class
|
|
10
|
+
- App: Main application class
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
import asyncio, logging, re
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from os.path import abspath
|
|
17
|
+
|
|
18
|
+
from aioquic.asyncio import QuicConnectionProtocol, serve
|
|
19
|
+
from aioquic.h3.connection import H3_ALPN, H3Connection
|
|
20
|
+
from aioquic.h3.events import (
|
|
21
|
+
DatagramReceived,
|
|
22
|
+
H3Event,
|
|
23
|
+
HeadersReceived,
|
|
24
|
+
WebTransportStreamDataReceived,
|
|
25
|
+
)
|
|
26
|
+
from aioquic.quic.configuration import QuicConfiguration
|
|
27
|
+
from aioquic.quic.events import ProtocolNegotiated, QuicEvent
|
|
28
|
+
from aioquic.quic.events import ConnectionTerminated
|
|
29
|
+
|
|
30
|
+
logging.getLogger("aioquic").setLevel(logging.WARNING)
|
|
31
|
+
logging.getLogger("quic").setLevel(logging.WARNING)
|
|
32
|
+
logging.getLogger("aioquic.asyncio").setLevel(logging.WARNING)
|
|
33
|
+
logging.getLogger("aioquic.asyncio.server").setLevel(logging.WARNING)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class DropQueue(asyncio.Queue):
|
|
37
|
+
"""
|
|
38
|
+
A queue that drops items when full.
|
|
39
|
+
|
|
40
|
+
This is used to prevent queue overflow in high-traffic scenarios.
|
|
41
|
+
"""
|
|
42
|
+
def put_nowait(self, item):
|
|
43
|
+
"""
|
|
44
|
+
Put an item into the queue without waiting.
|
|
45
|
+
|
|
46
|
+
If the queue is full, the item is dropped.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
item: The item to put into the queue
|
|
50
|
+
"""
|
|
51
|
+
try:
|
|
52
|
+
asyncio.Queue.put_nowait(self, item)
|
|
53
|
+
except asyncio.queues.QueueFull:
|
|
54
|
+
pass
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class Signals:
|
|
58
|
+
"""
|
|
59
|
+
Signal classes for internal communication.
|
|
60
|
+
"""
|
|
61
|
+
class Ended:
|
|
62
|
+
"""
|
|
63
|
+
Signal indicating that a session or stream has ended.
|
|
64
|
+
"""
|
|
65
|
+
...
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class QuicConnection(QuicConnectionProtocol):
|
|
69
|
+
"""
|
|
70
|
+
QUIC connection protocol implementation for HTTP3X.
|
|
71
|
+
|
|
72
|
+
This class handles QUIC events and manages WebTransport sessions.
|
|
73
|
+
"""
|
|
74
|
+
_app: 'App'
|
|
75
|
+
|
|
76
|
+
def __init__(self, *args, **kwargs):
|
|
77
|
+
"""
|
|
78
|
+
Initialize a QuicConnection.
|
|
79
|
+
|
|
80
|
+
Args:
|
|
81
|
+
*args: Positional arguments for QuicConnectionProtocol
|
|
82
|
+
**kwargs: Keyword arguments for QuicConnectionProtocol
|
|
83
|
+
"""
|
|
84
|
+
QuicConnectionProtocol.__init__(self, *args, **kwargs)
|
|
85
|
+
self._handlers: dict[int, WebTransportSession] = {}
|
|
86
|
+
self._conn: H3Connection = None
|
|
87
|
+
|
|
88
|
+
def quic_event_received(self, event: QuicEvent):
|
|
89
|
+
"""
|
|
90
|
+
Handle QUIC events.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
event: The QUIC event to handle
|
|
94
|
+
"""
|
|
95
|
+
try:
|
|
96
|
+
if isinstance(event, ProtocolNegotiated) and event.alpn_protocol in H3_ALPN:
|
|
97
|
+
self._conn = H3Connection(self._quic, enable_webtransport=True)
|
|
98
|
+
elif isinstance(event, ConnectionTerminated):
|
|
99
|
+
for key, handler in list(self._handlers.items()):
|
|
100
|
+
handler._event_msgs.put_nowait(Signals.Ended)
|
|
101
|
+
self._handlers.pop(key, None)
|
|
102
|
+
if self._conn is not None:
|
|
103
|
+
for event in self._conn.handle_event(event):
|
|
104
|
+
event: H3Event
|
|
105
|
+
try:
|
|
106
|
+
if isinstance(event, HeadersReceived):
|
|
107
|
+
if (session_id := event.stream_id) in self._handlers: return
|
|
108
|
+
if not isinstance(self._conn, H3Connection): return
|
|
109
|
+
headers = dict(event.headers)
|
|
110
|
+
if not (headers[b':method'] == b"CONNECT" and headers[b':protocol'] == b"webtransport"): return
|
|
111
|
+
remote_addr = self._conn._quic._network_paths[0].addr[:2]
|
|
112
|
+
request_path = headers[b':path'].decode('utf-8')
|
|
113
|
+
path = request_path.split('?', 1)[0]
|
|
114
|
+
for pattern, Handler in self._app.wt.route_patterns.values():
|
|
115
|
+
if m := pattern.match(path):
|
|
116
|
+
self._handlers[session_id] = handler = Handler(
|
|
117
|
+
session_id = session_id,
|
|
118
|
+
connection = self,
|
|
119
|
+
remote_addr = remote_addr,
|
|
120
|
+
headers = event.headers,
|
|
121
|
+
request_path = request_path,
|
|
122
|
+
path = path,
|
|
123
|
+
path_params = m.groups(),
|
|
124
|
+
)
|
|
125
|
+
asyncio.create_task(handler._run())
|
|
126
|
+
break
|
|
127
|
+
elif isinstance(event, DatagramReceived):
|
|
128
|
+
self._handlers[event.stream_id]._datagram_msgs.put_nowait(event.data)
|
|
129
|
+
elif isinstance(event, WebTransportStreamDataReceived):
|
|
130
|
+
self._handlers[event.session_id]._event_msgs.put_nowait(event)
|
|
131
|
+
except:
|
|
132
|
+
pass
|
|
133
|
+
except Exception as e:
|
|
134
|
+
logging.exception(f"Error in quic_event_received: {e}")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class WebTransportSessionRoutes:
|
|
138
|
+
"""
|
|
139
|
+
WebTransport session route management.
|
|
140
|
+
|
|
141
|
+
This class manages routes for WebTransport sessions.
|
|
142
|
+
"""
|
|
143
|
+
def __init__(self):
|
|
144
|
+
"""
|
|
145
|
+
Initialize WebTransportSessionRoutes.
|
|
146
|
+
"""
|
|
147
|
+
self.route_patterns: dict[
|
|
148
|
+
str,
|
|
149
|
+
tuple[
|
|
150
|
+
re.Pattern,
|
|
151
|
+
type[WebTransportSession]
|
|
152
|
+
]
|
|
153
|
+
] = {}
|
|
154
|
+
|
|
155
|
+
def add(self, route_pattern: str, handler: type[WebTransportSession]):
|
|
156
|
+
"""
|
|
157
|
+
Add a WebTransport session route.
|
|
158
|
+
|
|
159
|
+
Args:
|
|
160
|
+
route_pattern: The route pattern to match
|
|
161
|
+
handler: The WebTransportSession class to use for matching routes
|
|
162
|
+
"""
|
|
163
|
+
self.route_patterns[route_pattern] = re.compile(route_pattern), handler
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class AppConfiguration(QuicConfiguration):
|
|
167
|
+
"""
|
|
168
|
+
Application configuration class.
|
|
169
|
+
|
|
170
|
+
This class extends QuicConfiguration for HTTP3X applications.
|
|
171
|
+
"""
|
|
172
|
+
...
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class App:
|
|
176
|
+
"""
|
|
177
|
+
Main application class for HTTP3X.
|
|
178
|
+
|
|
179
|
+
This class manages WebTransport session routes and server lifecycle.
|
|
180
|
+
"""
|
|
181
|
+
def __init__(self):
|
|
182
|
+
"""
|
|
183
|
+
Initialize an App instance.
|
|
184
|
+
"""
|
|
185
|
+
self.wt = WebTransportSessionRoutes()
|
|
186
|
+
|
|
187
|
+
async def async_run(
|
|
188
|
+
self,
|
|
189
|
+
host,
|
|
190
|
+
port: int,
|
|
191
|
+
certfile: str|Path,
|
|
192
|
+
keyfile: str|Path,
|
|
193
|
+
*,
|
|
194
|
+
retry: bool=False,
|
|
195
|
+
configuration: AppConfiguration|None=None,
|
|
196
|
+
) -> None:
|
|
197
|
+
"""
|
|
198
|
+
Run the application asynchronously.
|
|
199
|
+
|
|
200
|
+
Args:
|
|
201
|
+
host: The host to listen on
|
|
202
|
+
port: The port to listen on
|
|
203
|
+
certfile: Path to the SSL certificate file
|
|
204
|
+
keyfile: Path to the SSL key file
|
|
205
|
+
retry: Whether to enable QUIC retry
|
|
206
|
+
configuration: Application configuration
|
|
207
|
+
"""
|
|
208
|
+
|
|
209
|
+
class QuicConnection_(QuicConnection):
|
|
210
|
+
_app = self
|
|
211
|
+
|
|
212
|
+
configuration = configuration or AppConfiguration(
|
|
213
|
+
alpn_protocols=["h3"],
|
|
214
|
+
is_client=False,
|
|
215
|
+
)
|
|
216
|
+
configuration.is_client = False
|
|
217
|
+
configuration.load_cert_chain(abspath(str(certfile)), abspath(str(keyfile)))
|
|
218
|
+
self.server = await serve(
|
|
219
|
+
host = host,
|
|
220
|
+
port = port,
|
|
221
|
+
configuration = configuration,
|
|
222
|
+
create_protocol = QuicConnection_,
|
|
223
|
+
retry = retry,
|
|
224
|
+
)
|
|
225
|
+
print(f"http3x running on https://{host}:{port}")
|
|
226
|
+
|
|
227
|
+
def run(
|
|
228
|
+
self,
|
|
229
|
+
host,
|
|
230
|
+
port: int,
|
|
231
|
+
certfile: str|Path,
|
|
232
|
+
keyfile: str|Path,
|
|
233
|
+
*,
|
|
234
|
+
retry: bool=False,
|
|
235
|
+
configuration: AppConfiguration|None=None,
|
|
236
|
+
) -> None:
|
|
237
|
+
"""
|
|
238
|
+
Run the application synchronously.
|
|
239
|
+
|
|
240
|
+
Args:
|
|
241
|
+
host: The host to listen on
|
|
242
|
+
port: The port to listen on
|
|
243
|
+
certfile: Path to the SSL certificate file
|
|
244
|
+
keyfile: Path to the SSL key file
|
|
245
|
+
retry: Whether to enable QUIC retry
|
|
246
|
+
configuration: Application configuration
|
|
247
|
+
"""
|
|
248
|
+
|
|
249
|
+
async def run_forever():
|
|
250
|
+
await self.async_run(host, port, certfile, keyfile, retry=retry, configuration=configuration)
|
|
251
|
+
await asyncio.Event().wait()
|
|
252
|
+
asyncio.run(run_forever())
|
|
253
|
+
|
|
254
|
+
def close(self):
|
|
255
|
+
"""
|
|
256
|
+
Close the server.
|
|
257
|
+
"""
|
|
258
|
+
self.server.close()
|
|
259
|
+
print(f"Http3x server have closed")
|
|
260
|
+
|
|
261
|
+
from .webtransport import WebTransportSession
|
http3x/_core/http3.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
"""
|
|
2
|
+
HTTP3X WebTransport module.
|
|
3
|
+
|
|
4
|
+
This module contains WebTransport session and stream classes for HTTP3X, including:
|
|
5
|
+
- WebTransportStream: Represents a WebTransport stream
|
|
6
|
+
- WebTransportSession: Represents a WebTransport session
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
import asyncio, logging
|
|
11
|
+
|
|
12
|
+
from aioquic.h3.events import WebTransportStreamDataReceived
|
|
13
|
+
|
|
14
|
+
from .base import Signals, QuicConnection, DropQueue
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class WebTransportStream:
|
|
18
|
+
"""
|
|
19
|
+
Represents a WebTransport stream.
|
|
20
|
+
|
|
21
|
+
This class provides methods to send and receive data over a WebTransport stream.
|
|
22
|
+
"""
|
|
23
|
+
def __init__(self, session: WebTransportSession, stream_id: int):
|
|
24
|
+
"""
|
|
25
|
+
Initialize a WebTransportStream.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
session: The WebTransportSession this stream belongs to
|
|
29
|
+
stream_id: The stream ID
|
|
30
|
+
"""
|
|
31
|
+
self.session = session
|
|
32
|
+
self.stream_id = stream_id
|
|
33
|
+
self._stream_msgs: asyncio.Queue[bytes]|DropQueue = asyncio.Queue()
|
|
34
|
+
|
|
35
|
+
async def send(self, data: bytes, end_stream: bool=False, *, flush=True):
|
|
36
|
+
"""
|
|
37
|
+
Send data over the stream.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
data: The data to send
|
|
41
|
+
end_stream: Whether to end the stream after sending
|
|
42
|
+
flush: Whether to flush the connection after sending
|
|
43
|
+
"""
|
|
44
|
+
self.session._conn._quic.send_stream_data(stream_id=self.stream_id, data=data, end_stream=end_stream)
|
|
45
|
+
if flush:
|
|
46
|
+
await self.session.flush()
|
|
47
|
+
|
|
48
|
+
async def __aiter__(self):
|
|
49
|
+
"""
|
|
50
|
+
Asynchronous iterator for receiving data from the stream.
|
|
51
|
+
|
|
52
|
+
Yields:
|
|
53
|
+
bytes: The received data
|
|
54
|
+
"""
|
|
55
|
+
try:
|
|
56
|
+
while True:
|
|
57
|
+
data = await self._stream_msgs.get()
|
|
58
|
+
if type(data) is bytes:
|
|
59
|
+
yield data
|
|
60
|
+
elif data is Signals.Ended:
|
|
61
|
+
break
|
|
62
|
+
except Exception as e:
|
|
63
|
+
logging.exception(f"Error in WebTransportStream.__aiter__: {e}")
|
|
64
|
+
self._stream_msgs = DropQueue(maxsize=1)
|
|
65
|
+
else:
|
|
66
|
+
self.session._streams.pop(self.stream_id, None)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class WebTransportSession:
|
|
70
|
+
"""
|
|
71
|
+
Represents a WebTransport session.
|
|
72
|
+
|
|
73
|
+
This class manages WebTransport streams and handles session lifecycle.
|
|
74
|
+
"""
|
|
75
|
+
def __init__(
|
|
76
|
+
self,
|
|
77
|
+
*,
|
|
78
|
+
session_id: int,
|
|
79
|
+
connection: QuicConnection,
|
|
80
|
+
remote_addr: tuple[str, int],
|
|
81
|
+
headers: list[tuple[bytes, bytes]],
|
|
82
|
+
request_path: str,
|
|
83
|
+
path: str,
|
|
84
|
+
path_params: tuple[str],
|
|
85
|
+
) -> None:
|
|
86
|
+
"""
|
|
87
|
+
Initialize a WebTransportSession.
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
session_id: The session ID
|
|
91
|
+
connection: The QuicConnection this session belongs to
|
|
92
|
+
remote_addr: The remote address (host, port)
|
|
93
|
+
headers: The request headers
|
|
94
|
+
request_path: The full request path
|
|
95
|
+
path: The path without query parameters
|
|
96
|
+
path_params: The path parameters
|
|
97
|
+
"""
|
|
98
|
+
self.session_id = session_id
|
|
99
|
+
self.connection = connection
|
|
100
|
+
self.remote_addr = remote_addr
|
|
101
|
+
self.headers = headers
|
|
102
|
+
self.request_path = request_path
|
|
103
|
+
self.path = path
|
|
104
|
+
self.path_params = path_params
|
|
105
|
+
|
|
106
|
+
self.accepted = False
|
|
107
|
+
self.closed = False
|
|
108
|
+
self._closed_event = asyncio.Event()
|
|
109
|
+
self._event_msgs: asyncio.Queue|DropQueue = asyncio.Queue()
|
|
110
|
+
self._datagram_msgs: asyncio.Queue|DropQueue = asyncio.Queue()
|
|
111
|
+
self._conn = connection._conn
|
|
112
|
+
self._streams: dict[int, WebTransportStream] = {}
|
|
113
|
+
|
|
114
|
+
async def flush(self):
|
|
115
|
+
"""
|
|
116
|
+
Flush the connection.
|
|
117
|
+
|
|
118
|
+
This sends any pending data over the connection.
|
|
119
|
+
"""
|
|
120
|
+
self.connection.transmit()
|
|
121
|
+
|
|
122
|
+
async def authorize(self) -> bool:
|
|
123
|
+
"""
|
|
124
|
+
Authorize the session.
|
|
125
|
+
|
|
126
|
+
Returns:
|
|
127
|
+
bool: True if authorized, False otherwise
|
|
128
|
+
|
|
129
|
+
Example:
|
|
130
|
+
```python
|
|
131
|
+
if dict(self.headers).get(b'authorization') == b'Bearer my-token':
|
|
132
|
+
return True
|
|
133
|
+
else:
|
|
134
|
+
return False
|
|
135
|
+
```
|
|
136
|
+
"""
|
|
137
|
+
return True
|
|
138
|
+
|
|
139
|
+
async def on_connect(self):
|
|
140
|
+
"""
|
|
141
|
+
Called when the session is connected.
|
|
142
|
+
|
|
143
|
+
This method can be overridden to handle connection events.
|
|
144
|
+
"""
|
|
145
|
+
...
|
|
146
|
+
|
|
147
|
+
async def on_close(self):
|
|
148
|
+
"""
|
|
149
|
+
Called when the session is closed.
|
|
150
|
+
|
|
151
|
+
This method can be overridden to handle close events.
|
|
152
|
+
"""
|
|
153
|
+
...
|
|
154
|
+
|
|
155
|
+
async def on_stream(self, stream: WebTransportStream):
|
|
156
|
+
"""
|
|
157
|
+
Called when a new stream is created.
|
|
158
|
+
|
|
159
|
+
This method can be overridden to handle stream events.
|
|
160
|
+
|
|
161
|
+
Args:
|
|
162
|
+
stream: The new WebTransportStream
|
|
163
|
+
"""
|
|
164
|
+
async for data in stream:
|
|
165
|
+
...
|
|
166
|
+
|
|
167
|
+
async def on_datagram(self, data: bytes):
|
|
168
|
+
"""
|
|
169
|
+
Called when a datagram is received.
|
|
170
|
+
|
|
171
|
+
This method can be overridden to handle datagram events.
|
|
172
|
+
|
|
173
|
+
Args:
|
|
174
|
+
data: The received datagram
|
|
175
|
+
"""
|
|
176
|
+
...
|
|
177
|
+
|
|
178
|
+
async def request_close(self):
|
|
179
|
+
"""
|
|
180
|
+
Request to close the session.
|
|
181
|
+
"""
|
|
182
|
+
self._event_msgs.put_nowait(Signals.Ended)
|
|
183
|
+
|
|
184
|
+
async def wait_closed(self):
|
|
185
|
+
"""
|
|
186
|
+
Wait for the session to close.
|
|
187
|
+
"""
|
|
188
|
+
await self._closed_event.wait()
|
|
189
|
+
|
|
190
|
+
async def send_datagram(self, data: bytes, *, flush=True):
|
|
191
|
+
"""
|
|
192
|
+
Send a datagram.
|
|
193
|
+
|
|
194
|
+
Args:
|
|
195
|
+
data: The datagram to send
|
|
196
|
+
flush: Whether to flush the connection after sending
|
|
197
|
+
"""
|
|
198
|
+
self._conn.send_datagram(stream_id=self.session_id, data=data)
|
|
199
|
+
if flush:
|
|
200
|
+
await self.flush()
|
|
201
|
+
|
|
202
|
+
async def create_stream(self) -> WebTransportStream:
|
|
203
|
+
"""
|
|
204
|
+
Create a new bidirectional stream.
|
|
205
|
+
|
|
206
|
+
Returns:
|
|
207
|
+
WebTransportStream: The new stream
|
|
208
|
+
"""
|
|
209
|
+
stream_id = self._conn.create_webtransport_stream(session_id=self.session_id, bidirectional=True)
|
|
210
|
+
stream = self._streams[stream_id] = WebTransportStream(self, stream_id)
|
|
211
|
+
asyncio.create_task(self.on_stream(stream))
|
|
212
|
+
return stream
|
|
213
|
+
|
|
214
|
+
async def _run(self):
|
|
215
|
+
"""
|
|
216
|
+
Run the session.
|
|
217
|
+
|
|
218
|
+
This method handles session lifecycle and events.
|
|
219
|
+
"""
|
|
220
|
+
try:
|
|
221
|
+
self.accepted = bool(await self.authorize())
|
|
222
|
+
if self.accepted:
|
|
223
|
+
try:
|
|
224
|
+
self._conn.send_headers(stream_id=self.session_id, headers=[(b":status", b"200")])
|
|
225
|
+
await self.flush()
|
|
226
|
+
await self.on_connect()
|
|
227
|
+
asyncio.create_task(self._on_datagram_task())
|
|
228
|
+
while True:
|
|
229
|
+
event = await self._event_msgs.get()
|
|
230
|
+
if isinstance(event, WebTransportStreamDataReceived):
|
|
231
|
+
stream_id = event.stream_id
|
|
232
|
+
stream = self._streams.get(stream_id)
|
|
233
|
+
if not stream:
|
|
234
|
+
stream = self._streams[stream_id] = WebTransportStream(self, stream_id)
|
|
235
|
+
asyncio.create_task(self.on_stream(stream))
|
|
236
|
+
stream._stream_msgs.put_nowait(event.data)
|
|
237
|
+
if event.stream_ended:
|
|
238
|
+
stream._stream_msgs.put_nowait(Signals.Ended)
|
|
239
|
+
elif event is Signals.Ended:
|
|
240
|
+
break
|
|
241
|
+
finally:
|
|
242
|
+
self._event_msgs = DropQueue(maxsize=1)
|
|
243
|
+
self._datagram_msgs.put_nowait(Signals.Ended)
|
|
244
|
+
for stream_id, stream in list(self._streams.items()):
|
|
245
|
+
stream._stream_msgs.put_nowait(Signals.Ended)
|
|
246
|
+
self._streams.pop(stream_id, None)
|
|
247
|
+
try:
|
|
248
|
+
await self.flush()
|
|
249
|
+
except Exception as e:
|
|
250
|
+
logging.exception(f"Error flushing connection: {e}")
|
|
251
|
+
self.closed = True
|
|
252
|
+
self._closed_event.set()
|
|
253
|
+
await self.wait_closed()
|
|
254
|
+
await self.on_close()
|
|
255
|
+
else:
|
|
256
|
+
try:
|
|
257
|
+
self._conn.send_headers(stream_id=self.session_id, headers=[(b":status", b"403")])
|
|
258
|
+
self._conn.send_data(stream_id=self.session_id, data=b"", end_stream=True)
|
|
259
|
+
await self.flush()
|
|
260
|
+
finally:
|
|
261
|
+
self.closed = True
|
|
262
|
+
self._closed_event.set()
|
|
263
|
+
finally:
|
|
264
|
+
self.closed = True
|
|
265
|
+
self._closed_event.set()
|
|
266
|
+
self.connection._handlers.pop(self.session_id, None)
|
|
267
|
+
|
|
268
|
+
async def _on_datagram_task(self):
|
|
269
|
+
"""
|
|
270
|
+
Handle datagram events.
|
|
271
|
+
|
|
272
|
+
This method runs in a separate task to handle datagrams.
|
|
273
|
+
"""
|
|
274
|
+
try:
|
|
275
|
+
while True:
|
|
276
|
+
data = await self._datagram_msgs.get()
|
|
277
|
+
if type(data) is bytes:
|
|
278
|
+
await self.on_datagram(data)
|
|
279
|
+
elif data is Signals.Ended:
|
|
280
|
+
break
|
|
281
|
+
except Exception as e:
|
|
282
|
+
logging.exception(f"Error in _on_datagram_task: {e}")
|
|
283
|
+
self._datagram_msgs = DropQueue(maxsize=1)
|
http3x/h3.py
ADDED
|
File without changes
|
http3x/wt.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""
|
|
2
|
+
WebTransport module for HTTP3X.
|
|
3
|
+
|
|
4
|
+
This module provides WebTransport session and stream classes for HTTP3X.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from ._core.webtransport import (
|
|
8
|
+
WebTransportSession, WebTransportStream
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
Session = WebTransportSession
|
|
12
|
+
"""Alias for WebTransportSession"""
|
|
13
|
+
|
|
14
|
+
Stream = WebTransportStream
|
|
15
|
+
"""Alias for WebTransportStream"""
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: http3x
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A modern async server framework for HTTP/3 and WebTransport over QUIC.
|
|
5
|
+
Author-email: 许灿标 <canbiaoxu@outlook.com>
|
|
6
|
+
Requires-Python: >=3.12
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: aioquic
|
|
11
|
+
Requires-Dist: wsproto
|
|
12
|
+
Requires-Dist: starlette
|
|
13
|
+
Requires-Dist: uvicorn
|
|
14
|
+
Requires-Dist: httpx
|
|
15
|
+
Project-URL: Documentation, https://github.com/canbiaoxu/http3x
|
|
16
|
+
Project-URL: Repository, https://github.com/canbiaoxu/http3x
|
|
17
|
+
|
|
18
|
+
# HTTP3X
|
|
19
|
+
|
|
20
|
+
> A WebSocket replacement built on HTTP/3 and QUIC.
|
|
21
|
+
|
|
22
|
+
Async Python server framework for HTTP/3 + WebTransport (QUIC).
|
|
23
|
+
|
|
24
|
+
> What WebSocket would look like if it was designed today.
|
|
25
|
+
|
|
26
|
+
## 🚀 Quick Example
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from http3x import App
|
|
30
|
+
from http3x.wt import Session
|
|
31
|
+
|
|
32
|
+
app = App()
|
|
33
|
+
|
|
34
|
+
class Echo(Session):
|
|
35
|
+
async def on_stream(self, stream):
|
|
36
|
+
async for data in stream:
|
|
37
|
+
await stream.send(data)
|
|
38
|
+
|
|
39
|
+
app.wt.add("/echo", Echo)
|
|
40
|
+
app.run(host='::', port=4433, certfile="cert.pem", keyfile="key.pem")
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Installation
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pip install http3x
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## 🚀 Live Demo
|
|
50
|
+
|
|
51
|
+
Streaming AI-style responses over HTTP/3 (WebTransport):
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
You: hello
|
|
55
|
+
|
|
56
|
+
AI:
|
|
57
|
+
h
|
|
58
|
+
he
|
|
59
|
+
hel
|
|
60
|
+
hell
|
|
61
|
+
hello 👋
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
**This is NOT WebSocket.**
|
|
65
|
+
**This is native HTTP/3 streaming over QUIC.**
|
|
66
|
+
|
|
67
|
+

|
|
68
|
+
|
|
69
|
+
See [demo/wt_demo.py](https://github.com/canbiaoxu/http3x/blob/main/demo/wt_demo.py) and [demo/wt_demo.html](https://github.com/canbiaoxu/http3x/blob/main/demo/wt_demo.html) for the complete example.
|
|
70
|
+
|
|
71
|
+
## ⚡ Why not WebSocket?
|
|
72
|
+
|
|
73
|
+
| Feature | WebSocket | http3x |
|
|
74
|
+
|---------|-----------|--------|
|
|
75
|
+
| Protocol | TCP | QUIC (HTTP/3) |
|
|
76
|
+
| Streams | Single stream | Multiplexed streams |
|
|
77
|
+
| Datagram | No support | Built-in datagram |
|
|
78
|
+
| Head-of-line blocking | Yes | No |
|
|
79
|
+
|
|
80
|
+
## Features
|
|
81
|
+
|
|
82
|
+
- HTTP/3 server (QUIC-based)
|
|
83
|
+
- WebTransport (stream + datagram)
|
|
84
|
+
- Multiplexed streams (no head-of-line blocking)
|
|
85
|
+
- Async/await API
|
|
86
|
+
- Built on aioquic
|
|
87
|
+
|
|
88
|
+
## Documentation
|
|
89
|
+
|
|
90
|
+
- [WebTransport Guide](https://github.com/canbiaoxu/http3x/blob/main/docs/webtransport.md) - Complete documentation for WebTransport functionality
|
|
91
|
+
|
|
92
|
+
More docs coming soon.
|
|
93
|
+
|
|
94
|
+
## Project Links
|
|
95
|
+
|
|
96
|
+
- **Source Code**: [GitHub Repository](https://github.com/canbiaoxu/http3x)
|
|
97
|
+
- **Documentation**: [https://github.com/canbiaoxu/http3x](https://github.com/canbiaoxu/http3x)
|
|
98
|
+
- **PyPI**: [http3x](https://pypi.org/project/http3x)
|
|
99
|
+
- **Contributors**: [GitHub Contributors](https://github.com/canbiaoxu/http3x/graphs/contributors)
|
|
100
|
+
|
|
101
|
+
## Contributing
|
|
102
|
+
|
|
103
|
+
Contributions are welcome! Please visit the [GitHub repository](https://github.com/canbiaoxu/http3x) to contribute code, report issues, or suggest features.
|
|
104
|
+
|
|
105
|
+
## License
|
|
106
|
+
|
|
107
|
+
This project is licensed under the Apache License 2.0. See the [LICENSE](https://github.com/canbiaoxu/http3x/blob/main/LICENSE) file for details.
|
|
108
|
+
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
http3x/__init__.py,sha256=OtWblxoDf2wOVgOBPer7BbP3Yarm1xXVrE0TBgQxvOc,212
|
|
2
|
+
http3x/h3.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
http3x/wt.py,sha256=lwUYXk0QxDMFuOM_bJ9Dc1MCeXtjaU35FWSe5dxBJ94,341
|
|
4
|
+
http3x/_core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
http3x/_core/base.py,sha256=Tr7PbtDpi39aaG1JeMSEmnk8dfzyTn4LXfhXRl_h5Uc,9190
|
|
6
|
+
http3x/_core/http3.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
http3x/_core/webtransport.py,sha256=cAJSFYun6uXBp5eRFhZv3SJUDhA4jbi-8DDPjAU0iQY,9724
|
|
8
|
+
http3x-0.1.0.dist-info/licenses/LICENSE,sha256=-ccY58FIZ7VQUjA9GgwNTZdS44s3kNyi41fxOogLxIY,10948
|
|
9
|
+
http3x-0.1.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
|
|
10
|
+
http3x-0.1.0.dist-info/METADATA,sha256=XKV6OIfiLdzMw44TwXusYynRht--c1HiixtYn7LtC5c,2939
|
|
11
|
+
http3x-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Copyright (c) 2026 Canbiao Xu (许灿标) and contributors
|
|
2
|
+
|
|
3
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
you may not use this file except in compliance with the License.
|
|
5
|
+
You may obtain a copy of the License at
|
|
6
|
+
|
|
7
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
|
|
9
|
+
Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
See the License for the specific language governing permissions and
|
|
13
|
+
limitations under the License.
|
|
14
|
+
|
|
15
|
+
Apache License
|
|
16
|
+
Version 2.0, January 2004
|
|
17
|
+
http://www.apache.org/licenses/
|
|
18
|
+
|
|
19
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
20
|
+
|
|
21
|
+
1. Definitions.
|
|
22
|
+
|
|
23
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
24
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
25
|
+
|
|
26
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
27
|
+
the copyright owner that is granting the License.
|
|
28
|
+
|
|
29
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
30
|
+
other entities that control, are controlled by, or are under common
|
|
31
|
+
control with that entity. For the purposes of this definition,
|
|
32
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
33
|
+
direction or management of such entity, whether by contract or
|
|
34
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
35
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
36
|
+
|
|
37
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
38
|
+
exercising permissions granted by this License.
|
|
39
|
+
|
|
40
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
41
|
+
including but not limited to software source code, documentation
|
|
42
|
+
source, and configuration files.
|
|
43
|
+
|
|
44
|
+
"Object" form shall mean any form resulting from mechanical
|
|
45
|
+
transformation or translation of a Source form, including but
|
|
46
|
+
not limited to compiled object code, generated documentation,
|
|
47
|
+
and conversions to other media types.
|
|
48
|
+
|
|
49
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
50
|
+
Object form, made available under the License, as indicated by a
|
|
51
|
+
copyright notice that is included in or attached to the work
|
|
52
|
+
(an example is provided in the Appendix below).
|
|
53
|
+
|
|
54
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
55
|
+
form, that is based on (or derived from) the Work and for which the
|
|
56
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
57
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
58
|
+
of this License, Derivative Works shall not include works that remain
|
|
59
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
60
|
+
the Work and Derivative Works thereof.
|
|
61
|
+
|
|
62
|
+
"Contribution" shall mean any work of authorship, including
|
|
63
|
+
the original version of the Work and any modifications or additions
|
|
64
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
65
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
66
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
67
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
68
|
+
means any form of electronic, verbal, or written communication sent
|
|
69
|
+
to the Licensor or its representatives, including but not limited to
|
|
70
|
+
communication on electronic mailing lists, source code control systems,
|
|
71
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
72
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
73
|
+
excluding communication that is conspicuously marked or otherwise
|
|
74
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
75
|
+
|
|
76
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
77
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
78
|
+
subsequently incorporated within the Work.
|
|
79
|
+
|
|
80
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
81
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
82
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
83
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
84
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
85
|
+
Work and such Derivative Works in Source or Object form.
|
|
86
|
+
|
|
87
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
88
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
89
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
90
|
+
(except as stated in this section) patent license to make, have made,
|
|
91
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
92
|
+
where such license applies only to those patent claims licensable
|
|
93
|
+
by such Contributor that are necessarily infringed by their
|
|
94
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
95
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
96
|
+
institute patent litigation against any entity (including a
|
|
97
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
98
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
99
|
+
or contributory patent infringement, then any patent licenses
|
|
100
|
+
granted to You under this License for that Work shall terminate
|
|
101
|
+
as of the date such litigation is filed.
|
|
102
|
+
|
|
103
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
104
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
105
|
+
modifications, and in Source or Object form, provided that You
|
|
106
|
+
meet the following conditions:
|
|
107
|
+
|
|
108
|
+
(a) You must give any other recipients of the Work or
|
|
109
|
+
Derivative Works a copy of this License; and
|
|
110
|
+
|
|
111
|
+
(b) You must cause any modified files to carry prominent notices
|
|
112
|
+
stating that You changed the files; and
|
|
113
|
+
|
|
114
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
115
|
+
that You distribute, all copyright, patent, trademark, and
|
|
116
|
+
attribution notices from the Source form of the Work,
|
|
117
|
+
excluding those notices that do not pertain to any part of
|
|
118
|
+
the Derivative Works; and
|
|
119
|
+
|
|
120
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
121
|
+
distribution, then any Derivative Works that You distribute must
|
|
122
|
+
include a readable copy of the attribution notices contained
|
|
123
|
+
within such NOTICE file, excluding those notices that do not
|
|
124
|
+
pertain to any part of the Derivative Works, in at least one
|
|
125
|
+
of the following places: within a NOTICE text file distributed
|
|
126
|
+
as part of the Derivative Works; within the Source form or
|
|
127
|
+
documentation, if provided along with the Derivative Works; or,
|
|
128
|
+
within a display generated by the Derivative Works, if and
|
|
129
|
+
wherever such third-party notices normally appear. The contents
|
|
130
|
+
of the NOTICE file are for informational purposes only and
|
|
131
|
+
do not modify the License. You may add Your own attribution
|
|
132
|
+
notices within Derivative Works that You distribute, alongside
|
|
133
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
134
|
+
that such additional attribution notices cannot be construed
|
|
135
|
+
as modifying the License.
|
|
136
|
+
|
|
137
|
+
You may add Your own copyright statement to Your modifications and
|
|
138
|
+
may provide additional or different license terms and conditions
|
|
139
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
140
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
141
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
142
|
+
the conditions stated in this License.
|
|
143
|
+
|
|
144
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
145
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
146
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
147
|
+
this License, without any additional terms or conditions.
|
|
148
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
149
|
+
the terms of any separate license agreement you may have executed
|
|
150
|
+
with Licensor regarding such Contributions.
|
|
151
|
+
|
|
152
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
153
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
154
|
+
except as required for reasonable and customary use in describing the
|
|
155
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
156
|
+
|
|
157
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
158
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
159
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
160
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
161
|
+
implied, including, without limitation, any warranties or conditions
|
|
162
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
163
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
164
|
+
appropriateness of using or redistributing the Work and assume any
|
|
165
|
+
risks associated with Your exercise of permissions under this License.
|
|
166
|
+
|
|
167
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
168
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
169
|
+
unless required by applicable law (such as deliberate and grossly
|
|
170
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
171
|
+
liable to You for damages, including any direct, indirect, special,
|
|
172
|
+
incidental, or consequential damages of any character arising as a
|
|
173
|
+
result of this License or out of the use or inability to use the
|
|
174
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
175
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
176
|
+
other commercial damages or losses), even if such Contributor
|
|
177
|
+
has been advised of the possibility of such damages.
|
|
178
|
+
|
|
179
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
180
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
181
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
182
|
+
or other liability obligations and/or rights consistent with this
|
|
183
|
+
License. However, in accepting such obligations, You may act only
|
|
184
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
185
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
186
|
+
defend, and hold each Contributor harmless for any liability
|
|
187
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
188
|
+
of your accepting any such warranty or additional liability.
|
|
189
|
+
|
|
190
|
+
END OF TERMS AND CONDITIONS
|