path
stringlengths
9
117
type
stringclasses
2 values
project
stringclasses
10 values
commit_hash
stringlengths
40
40
commit_message
stringlengths
1
137
ground_truth
stringlengths
0
2.74k
main_code
stringlengths
102
3.37k
context
stringlengths
0
14.7k
aioquic.h3.connection/H3Connection.handle_event
Modified
aiortc~aioquic
9eb461b8adda4addeeb45ba75f47a59e92a775ee
[http3] separate uni / bidi stream handling
<5>:<add> if isinstance(event, aioquic.quic.events.StreamDataReceived): <add> stream_id = event.stream_id <add> if stream_id not in self._stream: <add> self._stream[stream_id] = H3Stream() <add> if stream_id % 4 == 0: <add> return self._receive_stream_data_bidi( <add> stream_id, event.data, event.end_stream <add> ) <add> elif stream_is_unidirectional(stream_id): <add> return self._receive_stream_data_uni(stream_id, event.data) <add> return [] <del> http_events: List[Event] = [] <7>:<del> if isinstance(event, aioquic.quic.events.StreamDataReceived): <8>:<del> http_events.extend( <9>:<del> self._receive_stream_data(event.stream_id, event.data, event.end_stream) <10>:<del> ) <11>:<del> <12>:<del> return http_events <13>:<del>
# module: aioquic.h3.connection class H3Connection: def handle_event(self, event: aioquic.quic.events.Event) -> List[Event]: <0> """ <1> Handle a QUIC event and return a list of HTTP events. <2> <3> :param event: The QUIC event to handle. <4> """ <5> http_events: List[Event] = [] <6> <7> if isinstance(event, aioquic.quic.events.StreamDataReceived): <8> http_events.extend( <9> self._receive_stream_data(event.stream_id, event.data, event.end_stream) <10> ) <11> <12> return http_events <13>
===========unchanged ref 0=========== at: aioquic.h3.connection H3Stream() at: aioquic.h3.connection.H3Connection _receive_stream_data_bidi(stream_id: int, data: bytes, stream_ended: bool) -> List[Event] at: aioquic.h3.connection.H3Connection.__init__ self._stream: Dict[int, H3Stream] = {} at: aioquic.h3.events Event() at: aioquic.quic.events Event() StreamDataReceived(data: bytes, end_stream: bool, stream_id: int) at: typing List = _alias(list, 1, inst=False, name='List')
tests.test_h3/H3ConnectionTest.test_blocked_stream
Modified
aiortc~aioquic
9eb461b8adda4addeeb45ba75f47a59e92a775ee
[http3] separate uni / bidi stream handling
<5>:<add> h3_client.handle_event( <add> StreamDataReceived( <add> stream_id=3, <add> data=binascii.unhexlify( <add> "0004170150000680020000074064091040bcc0000000faceb00c" <add> ), <add> end_stream=False, <del> h3_client._receive_stream_data( <6>:<add> ) <del> 3, <7>:<del> binascii.unhexlify("0004170150000680020000074064091040bcc0000000faceb00c"), <8>:<del> False, <10>:<add> h3_client.handle_event( <add> StreamDataReceived(stream_id=7, data=b"\x02", end_stream=False) <add> ) <add> h3_client.handle_event( <add> StreamDataReceived(stream_id=11, data=b"\x03", end_stream=False) <add> ) <add> h3_client.handle_event( <add> StreamDataReceived( <add> stream_id=0, data=binascii.unhexlify("01040280d910"), end_stream=False <del> h3_client._receive_stream_data(7, b"\x02", False) <11>:<del> h3_client._receive_stream_data(11, b"\x03", False) <12>:<del> h3_client._receive_stream_data(0, binascii.unhexlify("01040280d910"), False) <13>:<del> h3_client._receive_stream_data( <14>:<add> ) <del> 0, <15>:<add> ) <add> h3_
# module: tests.test_h3 class H3ConnectionTest(TestCase): def test_blocked_stream(self): <0> quic_client = FakeQuicConnection( <1> configuration=QuicConfiguration(is_client=True) <2> ) <3> h3_client = H3Connection(quic_client) <4> <5> h3_client._receive_stream_data( <6> 3, <7> binascii.unhexlify("0004170150000680020000074064091040bcc0000000faceb00c"), <8> False, <9> ) <10> h3_client._receive_stream_data(7, b"\x02", False) <11> h3_client._receive_stream_data(11, b"\x03", False) <12> h3_client._receive_stream_data(0, binascii.unhexlify("01040280d910"), False) <13> h3_client._receive_stream_data( <14> 0, <15> binascii.unhexlify( <16> "00408d796f752072656163686564206d766673742e6e65742c20726561636820" <17> "746865202f6563686f20656e64706f696e7420666f7220616e206563686f2072" <18> "6573706f6e7365207175657279202f3c6e756d6265723e20656e64706f696e74" <19> "7320666f722061207661726961626c652073697a6520726573706f6e73652077" <20> "6974682072616e646f6d206279746573" <21> ), <22> True, <23> ) <24> self.assertEqual( <25> h3_client._receive_stream_data( <26> 7, <27> binascii.unhexlify( <28> "3fe101c696d</s>
===========below chunk 0=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_blocked_stream(self): # offset: 1 ), False, ), [ ResponseReceived( headers=[ (b":status", b"200"), (b"date", b"Mon, 22 Jul 2019 06:33:33 GMT"), ], stream_id=0, stream_ended=False, ), DataReceived( data=( b"you reached mvfst.net, reach the /echo endpoint for an " b"echo response query /<number> endpoints for a variable " b"size response with random bytes" ), stream_id=0, stream_ended=True, ), ], ) ===========unchanged ref 0=========== at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection handle_event(event: aioquic.quic.events.Event) -> List[Event] at: aioquic.h3.events ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.h3.events.ResponseReceived headers: Headers stream_id: int stream_ended: bool at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.quic.events StreamDataReceived(data: bytes, end_stream: bool, stream_id: int) at: aioquic.quic.events.StreamDataReceived data: bytes end_stream: bool ===========unchanged ref 1=========== stream_id: int at: binascii unhexlify(hexstr: _Ascii, /) -> bytes at: tests.test_h3 FakeQuicConnection(configuration) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.h3.connection class H3Connection: def handle_event(self, event: aioquic.quic.events.Event) -> List[Event]: """ Handle a QUIC event and return a list of HTTP events. :param event: The QUIC event to handle. """ + if isinstance(event, aioquic.quic.events.StreamDataReceived): + stream_id = event.stream_id + if stream_id not in self._stream: + self._stream[stream_id] = H3Stream() + if stream_id % 4 == 0: + return self._receive_stream_data_bidi( + stream_id, event.data, event.end_stream + ) + elif stream_is_unidirectional(stream_id): + return self._receive_stream_data_uni(stream_id, event.data) + return [] - http_events: List[Event] = [] - if isinstance(event, aioquic.quic.events.StreamDataReceived): - http_events.extend( - self._receive_stream_data(event.stream_id, event.data, event.end_stream) - ) - - return http_events - ===========changed ref 1=========== # module: aioquic.h3.connection class H3Connection: + def _receive_stream_data_bidi( + self, stream_id: int, data: bytes, stream_ended: bool + ) -> List[Event]: + """ + Client-initiated bidirectional streams carry requests and responses. + """ + http_events: List[Event] = [] + + stream = self._stream[stream_id] + stream.buffer += data + if stream_ended: + stream.ended = True + if stream.blocked: + return http_events + + buf = Buffer(data=stream.buffer) + consumed = 0 + unblocked_streams: Set[int] = set() + + # some peers (e.g. f5) end the stream with no data + if stream_ended and buf.eof(): + http_events.append( + DataReceived(data=b"", stream_id=stream_id, stream_ended=True) + ) + return http_events + + while not buf.eof(): + # fetch next frame + try: + frame_type = buf.pull_uint_var() + frame_length = buf.pull_uint_var() + frame_data = buf.pull_bytes(frame_length) + except BufferReadError: + break + consumed = buf.tell() + + if frame_type == FrameType.DATA: + http_events.append( + DataReceived( + data=frame_data, + stream_id=stream_id, + stream_ended=stream_ended and buf.eof(), + ) + ) + elif frame_type == FrameType.HEADERS: + try: + decoder, headers = self._decoder.feed_header(stream_id, frame_data) + except StreamBlocked: + stream.blocked = True + break + self._quic.send_stream_data(self._local_decoder_stream</s> ===========changed ref 2=========== # module: aioquic.h3.connection class H3Connection: + def _receive_stream_data_bidi( + self, stream_id: int, data: bytes, stream_ended: bool + ) -> List[Event]: # offset: 1 <s> stream.blocked = True + break + self._quic.send_stream_data(self._local_decoder_stream_id, decoder) + cls = ResponseReceived if self._is_client else RequestReceived + http_events.append( + cls( + headers=headers, + stream_id=stream_id, + stream_ended=stream_ended and buf.eof(), + ) + ) + + # remove processed data from buffer + stream.buffer = stream.buffer[consumed:] + + return http_events +
aioquic.h3.connection/H3Stream.__init__
Modified
aiortc~aioquic
aeb34b62eb25cc0215739aef3a44ce4d7afbd47b
[http3] return DATA chunks as they arrive
<3>:<add> self.frame_size: Optional[int] = None <add> self.frame_type: Optional[int] = None
# module: aioquic.h3.connection class H3Stream: def __init__(self) -> None: <0> self.blocked = False <1> self.buffer = b"" <2> self.ended = False <3> self.stream_type: Optional[int] = None <4>
aioquic.h3.connection/H3Connection._receive_stream_data_bidi
Modified
aiortc~aioquic
aeb34b62eb25cc0215739aef3a44ce4d7afbd47b
[http3] return DATA chunks as they arrive
<12>:<add> # shortcut DATA frame bits <add> if ( <add> stream.frame_size is not None <add> and stream.frame_type == FrameType.DATA <add> and len(stream.buffer) < stream.frame_size <add> ): <add> http_events.append( <add> DataReceived( <add> data=stream.buffer, stream_id=stream_id, stream_ended=False <add> ) <add> ) <add> stream.frame_size -= len(stream.buffer) <add> stream.buffer = b"" <add> return http_events <del> buf = Buffer(data=stream.buffer) <13>:<del> consumed = 0 <14>:<del> unblocked_streams: Set[int] = set() <17>:<add> if stream_ended and not stream.buffer: <del> if stream_ended and buf.eof(): <23>:<add> buf = Buffer(data=stream.buffer) <add> consumed = 0 <add> <24>:<add> # fetch next frame header <del> # fetch next frame <25>:<add> if stream.frame_size is None: <add> try: <del> try: <26>:<add> stream.frame_type = buf.pull_uint_var() <del> frame_type = buf.pull_uint_var() <27>:<add> stream.frame_size = buf.
# module: aioquic.h3.connection class H3Connection: def _receive_stream_data_bidi( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: <0> """ <1> Client-initiated bidirectional streams carry requests and responses. <2> """ <3> http_events: List[Event] = [] <4> <5> stream = self._stream[stream_id] <6> stream.buffer += data <7> if stream_ended: <8> stream.ended = True <9> if stream.blocked: <10> return http_events <11> <12> buf = Buffer(data=stream.buffer) <13> consumed = 0 <14> unblocked_streams: Set[int] = set() <15> <16> # some peers (e.g. f5) end the stream with no data <17> if stream_ended and buf.eof(): <18> http_events.append( <19> DataReceived(data=b"", stream_id=stream_id, stream_ended=True) <20> ) <21> return http_events <22> <23> while not buf.eof(): <24> # fetch next frame <25> try: <26> frame_type = buf.pull_uint_var() <27> frame_length = buf.pull_uint_var() <28> frame_data = buf.pull_bytes(frame_length) <29> except BufferReadError: <30> break <31> consumed = buf.tell() <32> <33> if frame_type == FrameType.DATA: <34> http_events.append( <35> DataReceived( <36> data=frame_data, <37> stream_id=stream_id, <38> stream_ended=stream_ended and buf.eof(), <39> ) <40> ) <41> elif frame_type == FrameType.HEADERS: <42> try: <43> decoder, headers = self._decoder.feed_header(stream_id, frame_data) <44> except StreamBlocked: <45> stream.blocked = True <46> break <47> self._quic.send_stream_data(self._local_decoder_stream_id,</s>
===========below chunk 0=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data_bidi( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: # offset: 1 cls = ResponseReceived if self._is_client else RequestReceived http_events.append( cls( headers=headers, stream_id=stream_id, stream_ended=stream_ended and buf.eof(), ) ) # remove processed data from buffer stream.buffer = stream.buffer[consumed:] return http_events ===========unchanged ref 0=========== at: aioquic._buffer BufferReadError(*args: object) Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer eof() -> bool tell() -> int pull_bytes(length: int) -> bytes pull_uint_var() -> int at: aioquic.h3.connection FrameType(x: Union[str, bytes, bytearray], base: int) FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: aioquic.h3.connection.H3Connection.__init__ self._stream: Dict[int, H3Stream] = {} at: aioquic.h3.connection.H3Stream.__init__ self.blocked = False self.buffer = b"" self.ended = False self.frame_size: Optional[int] = None self.frame_type: Optional[int] = None at: aioquic.h3.events Event() DataReceived(data: bytes, stream_id: int, stream_ended: bool) at: aioquic.h3.events.DataReceived data: bytes stream_id: int stream_ended: bool at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.h3.connection class H3Stream: def __init__(self) -> None: self.blocked = False self.buffer = b"" self.ended = False + self.frame_size: Optional[int] = None + self.frame_type: Optional[int] = None self.stream_type: Optional[int] = None
tests.test_h3/H3ConnectionTest.test_fragmented_frame
Modified
aiortc~aioquic
aeb34b62eb25cc0215739aef3a44ce4d7afbd47b
[http3] return DATA chunks as they arrive
# module: tests.test_h3 class H3ConnectionTest(TestCase): def test_fragmented_frame(self): <0> quic_client = FakeQuicConnection( <1> configuration=QuicConfiguration(is_client=True) <2> ) <3> quic_server = FakeQuicConnection( <4> configuration=QuicConfiguration(is_client=False) <5> ) <6> <7> h3_client = H3Connection(quic_client) <8> h3_server = H3Connection(quic_server) <9> <10> # send headers <11> stream_id = quic_client.get_next_available_stream_id() <12> h3_client.send_headers( <13> stream_id=stream_id, <14> headers=[ <15> (b":method", b"GET"), <16> (b":scheme", b"https"), <17> (b":authority", b"localhost"), <18> (b":path", b"/"), <19> (b"x-foo", b"client"), <20> ], <21> ) <22> http_events = [] <23> for event in quic_client.stream_queue: <24> http_events.extend(h3_server.handle_event(event)) <25> quic_client.stream_queue.clear() <26> self.assertEqual( <27> http_events, <28> [ <29> RequestReceived( <30> headers=[ <31> (b":method", b"GET"), <32> (b":scheme", b"https"), <33> (b":authority", b"localhost"), <34> (b":path", b"/"), <35> (b"x-foo", b"client"), <36> ], <37> stream_id=0, <38> stream_ended=False, <39> ) <40> ], <41> ) <42> <43> # send body <44> h3_client.send_data(stream_id=stream_id, data=b"hello", end_stream=True) <45> http_events = [] <46> for event in quic_client</s>
===========below chunk 0=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_fragmented_frame(self): # offset: 1 http_events.extend(h3_server.handle_event(event)) quic_client.stream_queue.clear() self.assertEqual( http_events, [ DataReceived(data=b"hello", stream_id=0, stream_ended=False), DataReceived(data=b"", stream_id=0, stream_ended=True), ], ) ===========unchanged ref 0=========== at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection handle_event(event: aioquic.quic.events.Event) -> List[Event] send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers) -> None at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool) RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.h3.events.DataReceived data: bytes stream_id: int stream_ended: bool at: aioquic.h3.events.RequestReceived headers: Headers stream_id: int stream_ended: bool at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None ===========unchanged ref 1=========== supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: tests.test_h3 FakeQuicConnection(configuration) at: tests.test_h3.FakeQuicConnection get_next_available_stream_id(is_unidirectional=False) at: tests.test_h3.FakeQuicConnection.__init__ self.stream_queue = [] at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.h3.connection class H3Stream: def __init__(self) -> None: self.blocked = False self.buffer = b"" self.ended = False + self.frame_size: Optional[int] = None + self.frame_type: Optional[int] = None self.stream_type: Optional[int] = None ===========changed ref 1=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data_bidi( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: """ Client-initiated bidirectional streams carry requests and responses. """ http_events: List[Event] = [] stream = self._stream[stream_id] stream.buffer += data if stream_ended: stream.ended = True if stream.blocked: return http_events + # shortcut DATA frame bits + if ( + stream.frame_size is not None + and stream.frame_type == FrameType.DATA + and len(stream.buffer) < stream.frame_size + ): + http_events.append( + DataReceived( + data=stream.buffer, stream_id=stream_id, stream_ended=False + ) + ) + stream.frame_size -= len(stream.buffer) + stream.buffer = b"" + return http_events - buf = Buffer(data=stream.buffer) - consumed = 0 - unblocked_streams: Set[int] = set() # some peers (e.g. f5) end the stream with no data + if stream_ended and not stream.buffer: - if stream_ended and buf.eof(): http_events.append( DataReceived(data=b"", stream_id=stream_id, stream_ended=True) ) return http_events + buf = Buffer(data=stream.buffer) + consumed = 0 + while not buf.eof(): + # fetch next frame header - # fetch next frame + if stream.frame_size is None: + try: - try: + stream.frame_type = buf.pull_uint_var() - frame_type = buf.pull_uint_var() + stream.frame_size = buf.pull_uint_var() - </s> ===========changed ref 2=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data_bidi( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: # offset: 1 <s>type = buf.pull_uint_var() + stream.frame_size = buf.pull_uint_var() - frame_length = buf.pull_uint_var() - frame_data = buf.pull_bytes(frame_length) + except BufferReadError: - except BufferReadError: + break + consumed = buf.tell() + + # check how much data is available + chunk_size = min(stream.frame_size, buf.capacity - consumed) + if ( + stream.frame_type == FrameType.HEADERS + and chunk_size < stream.frame_size + ): break + + # read available data + frame_data = buf.pull_bytes(chunk_size) consumed = buf.tell() + # detect end of frame + stream.frame_size -= chunk_size + if not stream.frame_size: + stream.frame_size = None + + if stream.frame_type == FrameType.DATA and (stream_ended or frame_data): - if frame_type == FrameType.DATA: http_events.append( DataReceived( data=frame_data, stream_id=stream_id, stream_ended=stream_ended and buf.eof(), ) ) + elif stream.frame_type == FrameType.HEADERS: - elif frame_type == FrameType.HEADERS: try: decoder, headers = self._decoder.feed_header(stream_id, frame_data) except StreamBlocked: stream.blocked = True break self._quic.send_stream_data(self._local_</s>
examples.http3-client/HttpClient.__init__
Modified
aiortc~aioquic
4c15b4d21fd714a4e1942569cb2cf84af3522f9d
[examples] make HTTP/3 client use a deque for buffered events
<11>:<add> self._request_events: Dict[int, Deque[Event]] = {} <del> self._request_events: Dict[int, List[Event]] = {} <12>:<add> self._request_waiter: Dict[int, asyncio.Future[Deque[Event]]] = {} <del> self._request_waiter: Dict[int, asyncio.Future[List[Event]]] = {}
# module: examples.http3-client class HttpClient(asyncio.DatagramProtocol): def __init__( self, *, configuration: QuicConfiguration, server_addr: NetworkAddress, session_ticket_handler: Optional[SessionTicketHandler] = None ): <0> self._closed = asyncio.Event() <1> self._connect_called = False <2> self._http: HttpConnection <3> self._loop = asyncio.get_event_loop() <4> self._quic = QuicConnection( <5> configuration=configuration, session_ticket_handler=session_ticket_handler <6> ) <7> self._server_addr = server_addr <8> self._timer: Optional[asyncio.TimerHandle] = None <9> self._timer_at = 0.0 <10> <11> self._request_events: Dict[int, List[Event]] = {} <12> self._request_waiter: Dict[int, asyncio.Future[List[Event]]] = {} <13> <14> if configuration.alpn_protocols[0].startswith("hq-"): <15> self._http = H0Connection(self._quic) <16> else: <17> self._http = H3Connection(self._quic) <18>
===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.h0.connection H0Connection(quic: QuicConnection) at: aioquic.h3.events Event() at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.quic.connection NetworkAddress = Any QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.tls SessionTicketHandler = Callable[[SessionTicket], None] at: asyncio.events TimerHandle(when: float, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop, context: Optional[Context]=...) ===========unchanged ref 1=========== get_event_loop() -> AbstractEventLoop at: asyncio.futures Future(*, loop: Optional[AbstractEventLoop]=...) Future = _CFuture = _asyncio.Future at: asyncio.locks Event(*, loop: Optional[AbstractEventLoop]=...) at: asyncio.protocols DatagramProtocol() at: examples.http3-client HttpConnection = Union[H0Connection, H3Connection] at: examples.http3-client.HttpClient._consume_events self._timer = self._loop.call_at(timer_at, self._handle_timer) self._timer = None self._timer_at = timer_at at: examples.http3-client.HttpClient._handle_timer self._timer = None self._timer_at = None at: examples.http3-client.HttpClient.get self._connect_called = True at: typing Deque = _alias(collections.deque, 1, name='Deque') Dict = _alias(dict, 2, inst=False, name='Dict')
examples.http3-client/HttpClient.get
Modified
aiortc~aioquic
4c15b4d21fd714a4e1942569cb2cf84af3522f9d
[examples] make HTTP/3 client use a deque for buffered events
<20>:<add> self._request_events[stream_id] = deque() <del> self._request_events[stream_id] = []
# module: examples.http3-client class HttpClient(asyncio.DatagramProtocol): + def get(self, path: str) -> Deque[Event]: - def get(self, path: str) -> List[Event]: <0> """ <1> Perform a GET request. <2> """ <3> if not self._connect_called: <4> self._quic.connect(self._server_addr, now=self._loop.time()) <5> self._connect_called = True <6> <7> stream_id = self._quic.get_next_available_stream_id() <8> self._http.send_headers( <9> stream_id=stream_id, <10> headers=[ <11> (b":method", b"GET"), <12> (b":scheme", b"https"), <13> (b":authority", self._quic.configuration.server_name.encode("utf8")), <14> (b":path", path.encode("utf8")), <15> ], <16> ) <17> self._http.send_data(stream_id=stream_id, data=b"", end_stream=True) <18> <19> waiter = self._loop.create_future() <20> self._request_events[stream_id] = [] <21> self._request_waiter[stream_id] = waiter <22> self._consume_events() <23> <24> return await asyncio.shield(waiter) <25>
===========unchanged ref 0=========== at: aioquic.h0.connection.H0Connection send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: List[Tuple[bytes, bytes]]) -> None at: aioquic.h3.connection.H3Connection send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers) -> None at: aioquic.h3.events Event() at: aioquic.quic.configuration.QuicConfiguration server_name: Optional[str] = None at: aioquic.quic.connection.QuicConnection connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None get_next_available_stream_id(is_unidirectional=False) -> int at: asyncio.events.AbstractEventLoop time() -> float create_future() -> Future[Any] at: collections deque(iterable: Iterable[_T]=..., maxlen: Optional[int]=...) at: examples.http3-client.HttpClient _consume_events() -> None at: examples.http3-client.HttpClient.__init__ self._connect_called = False self._http = H3Connection(self._quic) self._http: HttpConnection self._http = H0Connection(self._quic) self._loop = asyncio.get_event_loop() self._quic = QuicConnection( configuration=configuration, session_ticket_handler=session_ticket_handler ) self._server_addr = server_addr self._request_events: Dict[int, Deque[Event]] = {} self._request_waiter: Dict[int, asyncio.Future[Deque[Event]]] = {} at: typing Deque = _alias(collections.deque, 1, name='Deque') ===========changed ref 0=========== # module: examples.http3-client class HttpClient(asyncio.DatagramProtocol): def __init__( self, *, configuration: QuicConfiguration, server_addr: NetworkAddress, session_ticket_handler: Optional[SessionTicketHandler] = None ): self._closed = asyncio.Event() self._connect_called = False self._http: HttpConnection self._loop = asyncio.get_event_loop() self._quic = QuicConnection( configuration=configuration, session_ticket_handler=session_ticket_handler ) self._server_addr = server_addr self._timer: Optional[asyncio.TimerHandle] = None self._timer_at = 0.0 + self._request_events: Dict[int, Deque[Event]] = {} - self._request_events: Dict[int, List[Event]] = {} + self._request_waiter: Dict[int, asyncio.Future[Deque[Event]]] = {} - self._request_waiter: Dict[int, asyncio.Future[List[Event]]] = {} if configuration.alpn_protocols[0].startswith("hq-"): self._http = H0Connection(self._quic) else: self._http = H3Connection(self._quic)
aioquic.asyncio.server/QuicServer.__init__
Modified
aiortc~aioquic
0f24a863310d2088fbd8a67319c62ef20ddea993
[asyncio] remove connection_handler argument
<6>:<del> <7>:<del> if connection_handler is not None: <8>:<del> self._connection_handler = connection_handler <9>:<del> else: <10>:<del> self._connection_handler = lambda c: None
<s>.asyncio.server class QuicServer(asyncio.DatagramProtocol): def __init__( self, *, configuration: QuicConfiguration, - connection_handler: Optional[QuicConnectionHandler] = None, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: <0> self._configuration = configuration <1> self._protocols: Dict[bytes, QuicConnectionProtocol] = {} <2> self._loop = asyncio.get_event_loop() <3> self._session_ticket_fetcher = session_ticket_fetcher <4> self._session_ticket_handler = session_ticket_handler <5> self._transport: Optional[asyncio.DatagramTransport] = None <6> <7> if connection_handler is not None: <8> self._connection_handler = connection_handler <9> else: <10> self._connection_handler = lambda c: None <11> <12> self._stream_handler = stream_handler <13> <14> if stateless_retry: <15> self._retry = QuicRetryTokenHandler() <16> else: <17> self._retry = None <18>
===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.asyncio.protocol QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None] QuicConnectionProtocol(connection: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.asyncio.protocol.QuicConnectionProtocol close() -> None at: aioquic.asyncio.server.QuicServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.retry QuicRetryTokenHandler() at: aioquic.tls SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] at: asyncio.events get_event_loop() -> AbstractEventLoop at: asyncio.transports DatagramTransport(extra: Optional[Mapping[Any, Any]]=...) at: asyncio.transports.BaseTransport __slots__ = ('_extra',) close() -> None at: typing Dict = _alias(dict, 2, inst=False, name='Dict')
aioquic.asyncio.server/QuicServer.datagram_received
Modified
aiortc~aioquic
0f24a863310d2088fbd8a67319c62ef20ddea993
[asyncio] remove connection_handler argument
# module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: <0> data = cast(bytes, data) <1> buf = Buffer(data=data) <2> header = pull_quic_header(buf, host_cid_length=8) <3> <4> # version negotiation <5> if ( <6> header.version is not None <7> and header.version not in self._configuration.supported_versions <8> ): <9> self._transport.sendto( <10> encode_quic_version_negotiation( <11> source_cid=header.destination_cid, <12> destination_cid=header.source_cid, <13> supported_versions=self._configuration.supported_versions, <14> ), <15> addr, <16> ) <17> return <18> <19> protocol = self._protocols.get(header.destination_cid, None) <20> original_connection_id: Optional[bytes] = None <21> if protocol is None and header.packet_type == PACKET_TYPE_INITIAL: <22> # stateless retry <23> if self._retry is not None: <24> if not header.token: <25> # create a retry token <26> self._transport.sendto( <27> encode_quic_retry( <28> version=header.version, <29> source_cid=os.urandom(8), <30> destination_cid=header.source_cid, <31> original_destination_cid=header.destination_cid, <32> retry_token=self._retry.create_token( <33> addr, header.destination_cid <34> ), <35> ), <36> addr, <37> ) <38> return <39> else: <40> # validate retry token <41> try: <42> original_connection_id = self._retry.validate_token( <43> addr, header.token <44> ) <45> except ValueError: <46> return <47> <48> # create new connection <49> connection = QuicConnection( <50> configuration=</s>
===========below chunk 0=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 1 original_connection_id=original_connection_id, session_ticket_fetcher=self._session_ticket_fetcher, session_ticket_handler=self._session_ticket_handler, ) protocol = QuicConnectionProtocol( connection, stream_handler=self._stream_handler ) protocol._connection_id_issued_handler = partial( self._connection_id_issued, protocol=protocol ) protocol._connection_id_retired_handler = partial( self._connection_id_retired, protocol=protocol ) self._protocols[header.destination_cid] = protocol protocol.connection_made(self._transport) self._protocols[connection.host_cid] = protocol self._connection_handler(protocol) if protocol is not None: protocol.datagram_received(data, addr) ===========unchanged ref 0=========== at: aioquic.asyncio.protocol QuicConnectionProtocol(connection: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.asyncio.protocol.QuicConnectionProtocol connection_made(transport: asyncio.BaseTransport) -> None datagram_received(data: Union[bytes, Text], addr: NetworkAddress) -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None at: aioquic.asyncio.server.QuicServer.__init__ self._configuration = configuration self._protocols: Dict[bytes, QuicConnectionProtocol] = {} self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler self._transport: Optional[asyncio.DatagramTransport] = None self._stream_handler = stream_handler self._retry = QuicRetryTokenHandler() self._retry = None at: aioquic.asyncio.server.QuicServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: aioquic.asyncio.server.QuicServer.datagram_received data = cast(bytes, data) header = pull_quic_header(buf, host_cid_length=8) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None ===========unchanged ref 1=========== supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.quic.connection.QuicConnection.__init__ self.host_cid = self._host_cids[0].cid at: aioquic.quic.connection.QuicConnection.receive_datagram self.host_cid = context.host_cid at: aioquic.quic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 encode_quic_retry(version: int, source_cid: bytes, destination_cid: bytes, original_destination_cid: bytes, retry_token: bytes) -> bytes encode_quic_version_negotiation(source_cid: bytes, destination_cid: bytes, supported_versions: List[QuicProtocolVersion]) -> bytes at: aioquic.quic.packet.QuicHeader is_long_header: bool version: Optional[int] packet_type: int destination_cid: bytes source_cid: bytes original_destination_cid: bytes = b"" token: bytes = b"" rest_length: int = 0 at: aioquic.quic.retry.QuicRetryTokenHandler create_token(addr: NetworkAddress, destination_cid: bytes) -> bytes validate_token(addr: NetworkAddress, token: bytes) -> bytes at: asyncio.transports.DatagramTransport __slots__ = () sendto(data: Any, addr: Optional[_Address]=...) -> None ===========unchanged ref 2=========== at: functools partial(func: Callable[..., _T], *args: Any, **kwargs: Any) partial(func, *args, **keywords, /) -> function with partial application() at: os urandom(size: int, /) -> bytes at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co] ===========changed ref 0=========== <s>.asyncio.server class QuicServer(asyncio.DatagramProtocol): def __init__( self, *, configuration: QuicConfiguration, - connection_handler: Optional[QuicConnectionHandler] = None, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: self._configuration = configuration self._protocols: Dict[bytes, QuicConnectionProtocol] = {} self._loop = asyncio.get_event_loop() self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler self._transport: Optional[asyncio.DatagramTransport] = None - - if connection_handler is not None: - self._connection_handler = connection_handler - else: - self._connection_handler = lambda c: None self._stream_handler = stream_handler if stateless_retry: self._retry = QuicRetryTokenHandler() else: self._retry = None
aioquic.asyncio.server/serve
Modified
aiortc~aioquic
0f24a863310d2088fbd8a67319c62ef20ddea993
[asyncio] remove connection_handler argument
<13>:<del> * ``connection_handler`` is a callback which is invoked whenever a <14>:<del> connection is created. It must be a a function accepting a single <15>:<del> argument: a :class:`~aioquic.asyncio.QuicConnectionProtocol`.
<s>, alpn_protocols: Optional[List[str]] = None, - connection_handler: QuicConnectionHandler = None, idle_timeout: Optional[float] = None, stream_handler: QuicStreamHandler = None, secrets_log_file: Optional[TextIO] = None, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, ) -> QuicServer: <0> """ <1> Start a QUIC server at the given `host` and `port`. <2> <3> :func:`serve` requires a TLS certificate and private key, which can be <4> specified using the following arguments: <5> <6> * ``certificate`` is the server's TLS certificate. <7> See :func:`cryptography.x509.load_pem_x509_certificate`. <8> * ``private_key`` is the server's private key. <9> See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. <10> <11> :func:`serve` also accepts the following optional arguments: <12> <13> * ``connection_handler`` is a callback which is invoked whenever a <14> connection is created. It must be a a function accepting a single <15> argument: a :class:`~aioquic.asyncio.QuicConnectionProtocol`. <16> * ``secrets_log_file`` is a file-like object in which to log traffic <17> secrets. This is useful to analyze traffic captures with Wireshark. <18> * ``session_ticket_fetcher`` is a callback which is invoked by the TLS <19> engine when a session ticket is presented by the peer. It should return <20> the session ticket with the specified ID or `None` if it is not found. <21> * ``session_ticket_handler`` is a callback which is invoked by the TLS <22> engine when a new session ticket is issued. It should store the session <23> ticket for future lookup. <24> * ``stateless_retry`` specifies whether a stateless retry should be <25> performed prior to handling new connections. <26> </s>
===========below chunk 0=========== <s>_protocols: Optional[List[str]] = None, - connection_handler: QuicConnectionHandler = None, idle_timeout: Optional[float] = None, stream_handler: QuicStreamHandler = None, secrets_log_file: Optional[TextIO] = None, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, ) -> QuicServer: # offset: 1 created. It must accept two arguments: a :class:`asyncio.StreamReader` and a :class:`asyncio.StreamWriter`. """ loop = asyncio.get_event_loop() configuration = QuicConfiguration( alpn_protocols=alpn_protocols, certificate=certificate, is_client=False, private_key=private_key, secrets_log_file=secrets_log_file, ) if idle_timeout is not None: configuration.idle_timeout = idle_timeout _, protocol = await loop.create_datagram_endpoint( lambda: QuicServer( configuration=configuration, connection_handler=connection_handler, session_ticket_fetcher=session_ticket_fetcher, session_ticket_handler=session_ticket_handler, stateless_retry=stateless_retry, stream_handler=stream_handler, ), local_addr=(host, port), ) return cast(QuicServer, protocol) ===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.asyncio.protocol QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None] at: aioquic.asyncio.server QuicServer(*, configuration: QuicConfiguration, session_ticket_fetcher: Optional[SessionTicketFetcher]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stateless_retry: bool=False, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.configuration.QuicConfiguration idle_timeout: float = 60.0 at: aioquic.tls SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] at: asyncio.events get_event_loop() -> AbstractEventLoop at: asyncio.events.AbstractEventLoop create_datagram_endpoint(protocol_factory: _ProtocolFactory, local_addr: Optional[Tuple[str, int]]=..., remote_addr: Optional[Tuple[str, int]]=..., *, family: int=..., proto: int=..., flags: int=..., reuse_address: Optional[bool]=..., reuse_port: Optional[bool]=..., allow_broadcast: Optional[bool]=..., sock: Optional[socket]=...) -> _TransProtPair ===========unchanged ref 1=========== at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any TextIO() ===========changed ref 0=========== <s>.asyncio.server class QuicServer(asyncio.DatagramProtocol): def __init__( self, *, configuration: QuicConfiguration, - connection_handler: Optional[QuicConnectionHandler] = None, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: self._configuration = configuration self._protocols: Dict[bytes, QuicConnectionProtocol] = {} self._loop = asyncio.get_event_loop() self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler self._transport: Optional[asyncio.DatagramTransport] = None - - if connection_handler is not None: - self._connection_handler = connection_handler - else: - self._connection_handler = lambda c: None self._stream_handler = stream_handler if stateless_retry: self._retry = QuicRetryTokenHandler() else: self._retry = None ===========changed ref 1=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: data = cast(bytes, data) buf = Buffer(data=data) header = pull_quic_header(buf, host_cid_length=8) # version negotiation if ( header.version is not None and header.version not in self._configuration.supported_versions ): self._transport.sendto( encode_quic_version_negotiation( source_cid=header.destination_cid, destination_cid=header.source_cid, supported_versions=self._configuration.supported_versions, ), addr, ) return protocol = self._protocols.get(header.destination_cid, None) original_connection_id: Optional[bytes] = None if protocol is None and header.packet_type == PACKET_TYPE_INITIAL: # stateless retry if self._retry is not None: if not header.token: # create a retry token self._transport.sendto( encode_quic_retry( version=header.version, source_cid=os.urandom(8), destination_cid=header.source_cid, original_destination_cid=header.destination_cid, retry_token=self._retry.create_token( addr, header.destination_cid ), ), addr, ) return else: # validate retry token try: original_connection_id = self._retry.validate_token( addr, header.token ) except ValueError: return # create new connection connection = QuicConnection( configuration=self._configuration, original_connection_id=original_connection_id, session_ticket_fetcher=self._session_ticket_fetcher, session_ticket_handler=self._session_ticket_handler</s> ===========changed ref 2=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 1 <s>_ticket_fetcher=self._session_ticket_fetcher, session_ticket_handler=self._session_ticket_handler, ) protocol = QuicConnectionProtocol( connection, stream_handler=self._stream_handler ) protocol._connection_id_issued_handler = partial( self._connection_id_issued, protocol=protocol ) protocol._connection_id_retired_handler = partial( self._connection_id_retired, protocol=protocol ) self._protocols[header.destination_cid] = protocol protocol.connection_made(self._transport) self._protocols[connection.host_cid] = protocol - self._connection_handler(protocol) if protocol is not None: protocol.datagram_received(data, addr)
aioquic.quic.connection/QuicConnection.__init__
Modified
aiortc~aioquic
759892804b56578170db7a28d873d65ab2e97c55
[asyncio] start converging HttpClient towards Protocol
<28>:<add> self._events: Deque[events.QuicEvent] = deque() <del> self._events: Deque[events.Event] = deque()
# module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: <0> if configuration.is_client: <1> assert ( <2> original_connection_id is None <3> ), "Cannot set original_connection_id for a client" <4> else: <5> assert ( <6> configuration.certificate is not None <7> ), "SSL certificate is required for a server" <8> assert ( <9> configuration.private_key is not None <10> ), "SSL private key is required for a server" <11> <12> # counters for debugging <13> self._quic_logger = configuration.quic_logger <14> self._stateless_retry_count = 0 <15> self._version_negotiation_count = 0 <16> <17> # configuration <18> self._configuration = configuration <19> self._is_client = configuration.is_client <20> <21> self._ack_delay = K_GRANULARITY <22> self._close_at: Optional[float] = None <23> self._close_event: Optional[events.ConnectionTerminated] = None <24> self._connect_called = False <25> self._cryptos: Dict[tls.Epoch, CryptoPair] = {} <26> self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} <27> self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} <28> self._events: Deque[events.Event] = deque() <29> self._handshake_complete = False <30> self._handshake_confirmed = False <31> self._host_cids = [ <32> QuicConnectionId( <33> cid=os.urandom(8), <34> sequence_number=0, <35> stateless_reset_token=os.urandom(16), <36> was_sent=True,</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 1 ] self.host_cid = self._host_cids[0].cid self._host_cid_seq = 1 self._local_active_connection_id_limit = 8 self._local_max_data = MAX_DATA_WINDOW self._local_max_data_sent = MAX_DATA_WINDOW self._local_max_data_used = 0 self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW self._local_max_stream_data_uni = MAX_DATA_WINDOW self._local_max_streams_bidi = 128 self._local_max_streams_uni = 128 self._logger = QuicConnectionAdapter( logger, {"host_cid": dump_cid(self.host_cid)} ) self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) self._loss_at: Optional[float] = None self._network_paths: List[QuicNetworkPath] = [] self._original_connection_id = original_connection_id self._packet_number = 0 self._parameters_received = False self._peer_cid = os.urandom(8) self._peer_cid_seq: Optional[int] = None self._peer_cid_available: List[QuicConnectionId] = [] self._peer_token = b"" self._remote_active</s> ===========below chunk 1=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 2 <s>cid_available: List[QuicConnectionId] = [] self._peer_token = b"" self._remote_active_connection_id_limit = 0 self._remote_idle_timeout = 0.0 # seconds self._remote_max_data = 0 self._remote_max_data_used = 0 self._remote_max_stream_data_bidi_local = 0 self._remote_max_stream_data_bidi_remote = 0 self._remote_max_stream_data_uni = 0 self._remote_max_streams_bidi = 0 self._remote_max_streams_uni = 0 self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._spin_bit = False self._spin_bit_peer = False self._spin_highest_pn = 0 self._state = QuicConnectionState.FIRSTFLIGHT self._streams: Dict[int, QuicStream] = {} self._streams_blocked_bidi: List[QuicStream] = [] self._streams_blocked_uni: List[QuicStream] = [] self._version: Optional[int] = None # things to send self._close_pending = False self._ping_pending: List[int] = [] self._probe_pending = False self._retire_connection_ids: List[int] = [] self._streams_blocked_pending = False # callbacks self._session_ticket_fetcher =</s> ===========below chunk 2=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 3 <s>ticket_fetcher self._session_ticket_handler = session_ticket_handler # frame handlers self.__frame_handlers = [ (self._handle_padding_frame, EPOCHS("IZHO")), (self._handle_padding_frame, EPOCHS("ZO")), (self._handle_ack_frame, EPOCHS("IHO")), (self._handle_ack_frame, EPOCHS("IHO")), (self._handle_reset_stream_frame, EPOCHS("ZO")), (self._handle_stop_sending_frame, EPOCHS("ZO")), (self._handle_crypto_frame, EPOCHS("IHO")), (self._handle_new_token_frame, EPOCHS("O")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_max_data_frame, EPOCHS("ZO")), (self._handle_</s> ===========below chunk 3=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 4 <s>stream_data_frame, EPOCHS("ZO")), (self._handle_max_streams_bidi_frame, EPOCHS("ZO")), (self._handle_max_streams_uni_frame, EPOCHS("ZO")), (self._handle_data_blocked_frame, EPOCHS("ZO")), (self._handle_stream_data_blocked_frame, EPOCHS("ZO")), (self._handle_streams_blocked_frame, EPOCHS("ZO")), (self._handle_streams_blocked_frame, EPOCHS("ZO")), (self._handle_new_connection_id_frame, EPOCHS("ZO")), (self._handle_retire_connection_id_frame, EPOCHS("O")), (self._handle_path_challenge_frame, EPOCHS("ZO")), (self._handle_path_response_frame, EPOCHS("O")), (self._handle_connection_close_frame, EPOCHS("IZHO")), (self._handle_connection_close_frame, EPOCHS("ZO")), ]
aioquic.asyncio.protocol/QuicConnectionProtocol.__init__
Modified
aiortc~aioquic
759892804b56578170db7a28d873d65ab2e97c55
[asyncio] start converging HttpClient towards Protocol
<2>:<del> self._connection = connection <7>:<add> self._quic = quic
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( - self, - connection: QuicConnection, + self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None - stream_handler: Optional[QuicStreamHandler] = None, ): <0> loop = asyncio.get_event_loop() <1> <2> self._connection = connection <3> self._closed = asyncio.Event() <4> self._connected_waiter = loop.create_future() <5> self._loop = loop <6> self._ping_waiter: Optional[asyncio.Future[None]] = None <7> self._send_task: Optional[asyncio.Handle] = None <8> self._stream_readers: Dict[int, asyncio.StreamReader] = {} <9> self._timer: Optional[asyncio.TimerHandle] = None <10> self._timer_at: Optional[float] = None <11> self._transport: Optional[asyncio.DatagramTransport] = None <12> <13> # callbacks <14> self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None <15> self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None <16> if stream_handler is not None: <17> self._stream_handler = stream_handler <18> else: <19> self._stream_handler = lambda r, w: None <20>
===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.asyncio.protocol QuicConnectionIdHandler = Callable[[bytes], None] QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None] at: aioquic.asyncio.protocol.QuicConnectionProtocol._handle_event self._ping_waiter = None at: aioquic.asyncio.protocol.QuicConnectionProtocol._handle_timer self._timer = None self._timer_at = None at: aioquic.asyncio.protocol.QuicConnectionProtocol._send_pending self._send_task = None self._timer = self._loop.call_at(timer_at, self._handle_timer) self._timer = None self._timer_at = timer_at at: aioquic.asyncio.protocol.QuicConnectionProtocol._send_soon self._send_task = self._loop.call_soon(self._send_pending) at: aioquic.asyncio.protocol.QuicConnectionProtocol.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: aioquic.asyncio.protocol.QuicConnectionProtocol.ping self._ping_waiter = self._loop.create_future() at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: asyncio.events Handle(callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop, context: Optional[Context]=...) TimerHandle(when: float, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop, context: Optional[Context]=...) get_event_loop() -> AbstractEventLoop at: asyncio.events.AbstractEventLoop create_future() -> Future[Any] ===========unchanged ref 1=========== at: asyncio.futures Future(*, loop: Optional[AbstractEventLoop]=...) Future = _CFuture = _asyncio.Future at: asyncio.locks Event(*, loop: Optional[AbstractEventLoop]=...) at: asyncio.streams StreamReader(limit: int=..., loop: Optional[events.AbstractEventLoop]=...) at: asyncio.transports DatagramTransport(extra: Optional[Mapping[Any, Any]]=...) at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: if configuration.is_client: assert ( original_connection_id is None ), "Cannot set original_connection_id for a client" else: assert ( configuration.certificate is not None ), "SSL certificate is required for a server" assert ( configuration.private_key is not None ), "SSL private key is required for a server" # counters for debugging self._quic_logger = configuration.quic_logger self._stateless_retry_count = 0 self._version_negotiation_count = 0 # configuration self._configuration = configuration self._is_client = configuration.is_client self._ack_delay = K_GRANULARITY self._close_at: Optional[float] = None self._close_event: Optional[events.ConnectionTerminated] = None self._connect_called = False self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} + self._events: Deque[events.QuicEvent] = deque() - self._events: Deque[events.Event] = deque() self._handshake_complete = False self._handshake_confirmed = False self._host_cids = [ QuicConnectionId( cid=os.urandom(8), sequence_number=0, stateless_reset_token=os.urandom(16), was_sent=True, ) ] self.host_cid = self._host</s> ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 1 <s>urandom(16), was_sent=True, ) ] self.host_cid = self._host_cids[0].cid self._host_cid_seq = 1 self._local_active_connection_id_limit = 8 self._local_max_data = MAX_DATA_WINDOW self._local_max_data_sent = MAX_DATA_WINDOW self._local_max_data_used = 0 self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW self._local_max_stream_data_uni = MAX_DATA_WINDOW self._local_max_streams_bidi = 128 self._local_max_streams_uni = 128 self._logger = QuicConnectionAdapter( logger, {"host_cid": dump_cid(self.host_cid)} ) self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) self._loss_at: Optional[float] = None self._network_paths: List[QuicNetworkPath] = [] self._original_connection_id = original_connection_id self._packet_number = 0 self._parameters_received = False self._peer_cid = os.urandom(8) </s>
aioquic.asyncio.protocol/QuicConnectionProtocol.change_connection_id
Modified
aiortc~aioquic
759892804b56578170db7a28d873d65ab2e97c55
[asyncio] start converging HttpClient towards Protocol
<5>:<add> self._quic.change_connection_id() <del> self._connection.change_connection_id()
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def change_connection_id(self) -> None: <0> """ <1> Change the connection ID used to communicate with the peer. <2> <3> The previous connection ID will be retired. <4> """ <5> self._connection.change_connection_id() <6> self._send_pending() <7>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol _send_pending(self) -> None _send_pending() -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._quic = quic at: aioquic.quic.connection.QuicConnection change_connection_id() -> None ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( - self, - connection: QuicConnection, + self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None - stream_handler: Optional[QuicStreamHandler] = None, ): loop = asyncio.get_event_loop() - self._connection = connection self._closed = asyncio.Event() self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None + self._quic = quic self._send_task: Optional[asyncio.Handle] = None self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: if configuration.is_client: assert ( original_connection_id is None ), "Cannot set original_connection_id for a client" else: assert ( configuration.certificate is not None ), "SSL certificate is required for a server" assert ( configuration.private_key is not None ), "SSL private key is required for a server" # counters for debugging self._quic_logger = configuration.quic_logger self._stateless_retry_count = 0 self._version_negotiation_count = 0 # configuration self._configuration = configuration self._is_client = configuration.is_client self._ack_delay = K_GRANULARITY self._close_at: Optional[float] = None self._close_event: Optional[events.ConnectionTerminated] = None self._connect_called = False self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} + self._events: Deque[events.QuicEvent] = deque() - self._events: Deque[events.Event] = deque() self._handshake_complete = False self._handshake_confirmed = False self._host_cids = [ QuicConnectionId( cid=os.urandom(8), sequence_number=0, stateless_reset_token=os.urandom(16), was_sent=True, ) ] self.host_cid = self._host</s> ===========changed ref 2=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 1 <s>urandom(16), was_sent=True, ) ] self.host_cid = self._host_cids[0].cid self._host_cid_seq = 1 self._local_active_connection_id_limit = 8 self._local_max_data = MAX_DATA_WINDOW self._local_max_data_sent = MAX_DATA_WINDOW self._local_max_data_used = 0 self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW self._local_max_stream_data_uni = MAX_DATA_WINDOW self._local_max_streams_bidi = 128 self._local_max_streams_uni = 128 self._logger = QuicConnectionAdapter( logger, {"host_cid": dump_cid(self.host_cid)} ) self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) self._loss_at: Optional[float] = None self._network_paths: List[QuicNetworkPath] = [] self._original_connection_id = original_connection_id self._packet_number = 0 self._parameters_received = False self._peer_cid = os.urandom(8) </s> ===========changed ref 3=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 2 <s>peer_cid_seq: Optional[int] = None self._peer_cid_available: List[QuicConnectionId] = [] self._peer_token = b"" self._remote_active_connection_id_limit = 0 self._remote_idle_timeout = 0.0 # seconds self._remote_max_data = 0 self._remote_max_data_used = 0 self._remote_max_stream_data_bidi_local = 0 self._remote_max_stream_data_bidi_remote = 0 self._remote_max_stream_data_uni = 0 self._remote_max_streams_bidi = 0 self._remote_max_streams_uni = 0 self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._spin_bit = False self._spin_bit_peer = False self._spin_highest_pn = 0 self._state = QuicConnectionState.FIRSTFLIGHT self._streams: Dict[int, QuicStream] = {} self._streams_blocked_bidi: List[QuicStream] = [] self._streams_blocked_uni: List[QuicStream] = [] self._version: Optional[int] = None # things to send self._close_pending = False self._ping_pending: List[int] = [] self._probe_pending = False self._retire_connection_ids: List[int] = [] self._streams_blocked_pending</s>
aioquic.asyncio.protocol/QuicConnectionProtocol.close
Modified
aiortc~aioquic
759892804b56578170db7a28d873d65ab2e97c55
[asyncio] start converging HttpClient towards Protocol
<3>:<add> self._quic.close() <del> self._connection.close()
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def close(self) -> None: <0> """ <1> Close the connection. <2> """ <3> self._connection.close() <4> self._send_pending() <5>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol _send_pending(self) -> None _send_pending() -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._quic = quic at: aioquic.quic.connection NetworkAddress = Any at: aioquic.quic.connection.QuicConnection close(error_code: int=QuicErrorCode.NO_ERROR, frame_type: Optional[int]=None, reason_phrase: str="") -> None ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def change_connection_id(self) -> None: """ Change the connection ID used to communicate with the peer. The previous connection ID will be retired. """ + self._quic.change_connection_id() - self._connection.change_connection_id() self._send_pending() ===========changed ref 1=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( - self, - connection: QuicConnection, + self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None - stream_handler: Optional[QuicStreamHandler] = None, ): loop = asyncio.get_event_loop() - self._connection = connection self._closed = asyncio.Event() self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None + self._quic = quic self._send_task: Optional[asyncio.Handle] = None self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None ===========changed ref 2=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: if configuration.is_client: assert ( original_connection_id is None ), "Cannot set original_connection_id for a client" else: assert ( configuration.certificate is not None ), "SSL certificate is required for a server" assert ( configuration.private_key is not None ), "SSL private key is required for a server" # counters for debugging self._quic_logger = configuration.quic_logger self._stateless_retry_count = 0 self._version_negotiation_count = 0 # configuration self._configuration = configuration self._is_client = configuration.is_client self._ack_delay = K_GRANULARITY self._close_at: Optional[float] = None self._close_event: Optional[events.ConnectionTerminated] = None self._connect_called = False self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} + self._events: Deque[events.QuicEvent] = deque() - self._events: Deque[events.Event] = deque() self._handshake_complete = False self._handshake_confirmed = False self._host_cids = [ QuicConnectionId( cid=os.urandom(8), sequence_number=0, stateless_reset_token=os.urandom(16), was_sent=True, ) ] self.host_cid = self._host</s> ===========changed ref 3=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 1 <s>urandom(16), was_sent=True, ) ] self.host_cid = self._host_cids[0].cid self._host_cid_seq = 1 self._local_active_connection_id_limit = 8 self._local_max_data = MAX_DATA_WINDOW self._local_max_data_sent = MAX_DATA_WINDOW self._local_max_data_used = 0 self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW self._local_max_stream_data_uni = MAX_DATA_WINDOW self._local_max_streams_bidi = 128 self._local_max_streams_uni = 128 self._logger = QuicConnectionAdapter( logger, {"host_cid": dump_cid(self.host_cid)} ) self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) self._loss_at: Optional[float] = None self._network_paths: List[QuicNetworkPath] = [] self._original_connection_id = original_connection_id self._packet_number = 0 self._parameters_received = False self._peer_cid = os.urandom(8) </s>
aioquic.asyncio.protocol/QuicConnectionProtocol.connect
Modified
aiortc~aioquic
759892804b56578170db7a28d873d65ab2e97c55
[asyncio] start converging HttpClient towards Protocol
<5>:<add> self._quic.connect( <del> self._connection.connect(
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def connect(self, addr: NetworkAddress, protocol_version: int) -> None: <0> """ <1> Initiate the TLS handshake. <2> <3> This method can only be called for clients and a single time. <4> """ <5> self._connection.connect( <6> addr, now=self._loop.time(), protocol_version=protocol_version <7> ) <8> self._send_pending() <9>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol _send_pending(self) -> None _send_pending() -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._loop = loop self._quic = quic at: aioquic.quic.connection.QuicConnection connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None at: asyncio.events.AbstractEventLoop time() -> float ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def close(self) -> None: """ Close the connection. """ + self._quic.close() - self._connection.close() self._send_pending() ===========changed ref 1=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def change_connection_id(self) -> None: """ Change the connection ID used to communicate with the peer. The previous connection ID will be retired. """ + self._quic.change_connection_id() - self._connection.change_connection_id() self._send_pending() ===========changed ref 2=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( - self, - connection: QuicConnection, + self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None - stream_handler: Optional[QuicStreamHandler] = None, ): loop = asyncio.get_event_loop() - self._connection = connection self._closed = asyncio.Event() self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None + self._quic = quic self._send_task: Optional[asyncio.Handle] = None self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None ===========changed ref 3=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: if configuration.is_client: assert ( original_connection_id is None ), "Cannot set original_connection_id for a client" else: assert ( configuration.certificate is not None ), "SSL certificate is required for a server" assert ( configuration.private_key is not None ), "SSL private key is required for a server" # counters for debugging self._quic_logger = configuration.quic_logger self._stateless_retry_count = 0 self._version_negotiation_count = 0 # configuration self._configuration = configuration self._is_client = configuration.is_client self._ack_delay = K_GRANULARITY self._close_at: Optional[float] = None self._close_event: Optional[events.ConnectionTerminated] = None self._connect_called = False self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} + self._events: Deque[events.QuicEvent] = deque() - self._events: Deque[events.Event] = deque() self._handshake_complete = False self._handshake_confirmed = False self._host_cids = [ QuicConnectionId( cid=os.urandom(8), sequence_number=0, stateless_reset_token=os.urandom(16), was_sent=True, ) ] self.host_cid = self._host</s> ===========changed ref 4=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 1 <s>urandom(16), was_sent=True, ) ] self.host_cid = self._host_cids[0].cid self._host_cid_seq = 1 self._local_active_connection_id_limit = 8 self._local_max_data = MAX_DATA_WINDOW self._local_max_data_sent = MAX_DATA_WINDOW self._local_max_data_used = 0 self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW self._local_max_stream_data_uni = MAX_DATA_WINDOW self._local_max_streams_bidi = 128 self._local_max_streams_uni = 128 self._logger = QuicConnectionAdapter( logger, {"host_cid": dump_cid(self.host_cid)} ) self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) self._loss_at: Optional[float] = None self._network_paths: List[QuicNetworkPath] = [] self._original_connection_id = original_connection_id self._packet_number = 0 self._parameters_received = False self._peer_cid = os.urandom(8) </s>
aioquic.asyncio.protocol/QuicConnectionProtocol.create_stream
Modified
aiortc~aioquic
759892804b56578170db7a28d873d65ab2e97c55
[asyncio] start converging HttpClient towards Protocol
<6>:<add> stream_id = self._quic.get_next_available_stream_id( <del> stream_id = self._connection.get_next_available_stream_id(
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def create_stream( self, is_unidirectional: bool = False ) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]: <0> """ <1> Create a QUIC stream and return a pair of (reader, writer) objects. <2> <3> The returned reader and writer objects are instances of :class:`asyncio.StreamReader` <4> and :class:`asyncio.StreamWriter` classes. <5> """ <6> stream_id = self._connection.get_next_available_stream_id( <7> is_unidirectional=is_unidirectional <8> ) <9> return self._create_stream(stream_id) <10>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol _create_stream(self, stream_id: int) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter] _create_stream(stream_id: int) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter] at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._quic = quic at: aioquic.quic.connection.QuicConnection get_next_available_stream_id(is_unidirectional=False) -> int at: asyncio.streams StreamWriter(transport: transports.BaseTransport, protocol: protocols.BaseProtocol, reader: Optional[StreamReader], loop: events.AbstractEventLoop) StreamReader(limit: int=..., loop: Optional[events.AbstractEventLoop]=...) at: typing Tuple = _TupleType(tuple, -1, inst=False, name='Tuple') ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def close(self) -> None: """ Close the connection. """ + self._quic.close() - self._connection.close() self._send_pending() ===========changed ref 1=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def connect(self, addr: NetworkAddress, protocol_version: int) -> None: """ Initiate the TLS handshake. This method can only be called for clients and a single time. """ + self._quic.connect( - self._connection.connect( addr, now=self._loop.time(), protocol_version=protocol_version ) self._send_pending() ===========changed ref 2=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def change_connection_id(self) -> None: """ Change the connection ID used to communicate with the peer. The previous connection ID will be retired. """ + self._quic.change_connection_id() - self._connection.change_connection_id() self._send_pending() ===========changed ref 3=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( - self, - connection: QuicConnection, + self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None - stream_handler: Optional[QuicStreamHandler] = None, ): loop = asyncio.get_event_loop() - self._connection = connection self._closed = asyncio.Event() self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None + self._quic = quic self._send_task: Optional[asyncio.Handle] = None self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None ===========changed ref 4=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: if configuration.is_client: assert ( original_connection_id is None ), "Cannot set original_connection_id for a client" else: assert ( configuration.certificate is not None ), "SSL certificate is required for a server" assert ( configuration.private_key is not None ), "SSL private key is required for a server" # counters for debugging self._quic_logger = configuration.quic_logger self._stateless_retry_count = 0 self._version_negotiation_count = 0 # configuration self._configuration = configuration self._is_client = configuration.is_client self._ack_delay = K_GRANULARITY self._close_at: Optional[float] = None self._close_event: Optional[events.ConnectionTerminated] = None self._connect_called = False self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} + self._events: Deque[events.QuicEvent] = deque() - self._events: Deque[events.Event] = deque() self._handshake_complete = False self._handshake_confirmed = False self._host_cids = [ QuicConnectionId( cid=os.urandom(8), sequence_number=0, stateless_reset_token=os.urandom(16), was_sent=True, ) ] self.host_cid = self._host</s> ===========changed ref 5=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 1 <s>urandom(16), was_sent=True, ) ] self.host_cid = self._host_cids[0].cid self._host_cid_seq = 1 self._local_active_connection_id_limit = 8 self._local_max_data = MAX_DATA_WINDOW self._local_max_data_sent = MAX_DATA_WINDOW self._local_max_data_used = 0 self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW self._local_max_stream_data_uni = MAX_DATA_WINDOW self._local_max_streams_bidi = 128 self._local_max_streams_uni = 128 self._logger = QuicConnectionAdapter( logger, {"host_cid": dump_cid(self.host_cid)} ) self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) self._loss_at: Optional[float] = None self._network_paths: List[QuicNetworkPath] = [] self._original_connection_id = original_connection_id self._packet_number = 0 self._parameters_received = False self._peer_cid = os.urandom(8) </s>
aioquic.asyncio.protocol/QuicConnectionProtocol.request_key_update
Modified
aiortc~aioquic
759892804b56578170db7a28d873d65ab2e97c55
[asyncio] start converging HttpClient towards Protocol
<3>:<add> self._quic.request_key_update() <del> self._connection.request_key_update()
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def request_key_update(self) -> None: <0> """ <1> Request an update of the encryption keys. <2> """ <3> self._connection.request_key_update() <4> self._send_pending() <5>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol _send_pending(self) -> None _send_pending() -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._quic = quic at: aioquic.quic.connection.QuicConnection request_key_update() -> None ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def close(self) -> None: """ Close the connection. """ + self._quic.close() - self._connection.close() self._send_pending() ===========changed ref 1=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def connect(self, addr: NetworkAddress, protocol_version: int) -> None: """ Initiate the TLS handshake. This method can only be called for clients and a single time. """ + self._quic.connect( - self._connection.connect( addr, now=self._loop.time(), protocol_version=protocol_version ) self._send_pending() ===========changed ref 2=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def change_connection_id(self) -> None: """ Change the connection ID used to communicate with the peer. The previous connection ID will be retired. """ + self._quic.change_connection_id() - self._connection.change_connection_id() self._send_pending() ===========changed ref 3=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def create_stream( self, is_unidirectional: bool = False ) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]: """ Create a QUIC stream and return a pair of (reader, writer) objects. The returned reader and writer objects are instances of :class:`asyncio.StreamReader` and :class:`asyncio.StreamWriter` classes. """ + stream_id = self._quic.get_next_available_stream_id( - stream_id = self._connection.get_next_available_stream_id( is_unidirectional=is_unidirectional ) return self._create_stream(stream_id) ===========changed ref 4=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( - self, - connection: QuicConnection, + self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None - stream_handler: Optional[QuicStreamHandler] = None, ): loop = asyncio.get_event_loop() - self._connection = connection self._closed = asyncio.Event() self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None + self._quic = quic self._send_task: Optional[asyncio.Handle] = None self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None ===========changed ref 5=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: if configuration.is_client: assert ( original_connection_id is None ), "Cannot set original_connection_id for a client" else: assert ( configuration.certificate is not None ), "SSL certificate is required for a server" assert ( configuration.private_key is not None ), "SSL private key is required for a server" # counters for debugging self._quic_logger = configuration.quic_logger self._stateless_retry_count = 0 self._version_negotiation_count = 0 # configuration self._configuration = configuration self._is_client = configuration.is_client self._ack_delay = K_GRANULARITY self._close_at: Optional[float] = None self._close_event: Optional[events.ConnectionTerminated] = None self._connect_called = False self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} + self._events: Deque[events.QuicEvent] = deque() - self._events: Deque[events.Event] = deque() self._handshake_complete = False self._handshake_confirmed = False self._host_cids = [ QuicConnectionId( cid=os.urandom(8), sequence_number=0, stateless_reset_token=os.urandom(16), was_sent=True, ) ] self.host_cid = self._host</s> ===========changed ref 6=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 1 <s>urandom(16), was_sent=True, ) ] self.host_cid = self._host_cids[0].cid self._host_cid_seq = 1 self._local_active_connection_id_limit = 8 self._local_max_data = MAX_DATA_WINDOW self._local_max_data_sent = MAX_DATA_WINDOW self._local_max_data_used = 0 self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW self._local_max_stream_data_uni = MAX_DATA_WINDOW self._local_max_streams_bidi = 128 self._local_max_streams_uni = 128 self._logger = QuicConnectionAdapter( logger, {"host_cid": dump_cid(self.host_cid)} ) self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) self._loss_at: Optional[float] = None self._network_paths: List[QuicNetworkPath] = [] self._original_connection_id = original_connection_id self._packet_number = 0 self._parameters_received = False self._peer_cid = os.urandom(8) </s>
aioquic.asyncio.protocol/QuicConnectionProtocol.ping
Modified
aiortc~aioquic
759892804b56578170db7a28d873d65ab2e97c55
[asyncio] start converging HttpClient towards Protocol
<5>:<add> self._quic.send_ping(id(self._ping_waiter)) <del> self._connection.send_ping(id(self._ping_waiter))
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def ping(self) -> None: <0> """ <1> Pings the remote host and waits for the response. <2> """ <3> assert self._ping_waiter is None, "already await a ping" <4> self._ping_waiter = self._loop.create_future() <5> self._connection.send_ping(id(self._ping_waiter)) <6> self._send_pending() <7> await asyncio.shield(self._ping_waiter) <8>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol _send_pending(self) -> None _send_pending() -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None self._quic = quic at: aioquic.asyncio.protocol.QuicConnectionProtocol._handle_event self._ping_waiter = None at: aioquic.quic.connection.QuicConnection send_ping(uid: int) -> None at: asyncio.events.AbstractEventLoop create_future() -> Future[Any] at: asyncio.tasks shield(arg: _FutureT[_T], *, loop: Optional[AbstractEventLoop]=...) -> Future[_T] ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def request_key_update(self) -> None: """ Request an update of the encryption keys. """ + self._quic.request_key_update() - self._connection.request_key_update() self._send_pending() ===========changed ref 1=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def close(self) -> None: """ Close the connection. """ + self._quic.close() - self._connection.close() self._send_pending() ===========changed ref 2=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def connect(self, addr: NetworkAddress, protocol_version: int) -> None: """ Initiate the TLS handshake. This method can only be called for clients and a single time. """ + self._quic.connect( - self._connection.connect( addr, now=self._loop.time(), protocol_version=protocol_version ) self._send_pending() ===========changed ref 3=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def change_connection_id(self) -> None: """ Change the connection ID used to communicate with the peer. The previous connection ID will be retired. """ + self._quic.change_connection_id() - self._connection.change_connection_id() self._send_pending() ===========changed ref 4=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def create_stream( self, is_unidirectional: bool = False ) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]: """ Create a QUIC stream and return a pair of (reader, writer) objects. The returned reader and writer objects are instances of :class:`asyncio.StreamReader` and :class:`asyncio.StreamWriter` classes. """ + stream_id = self._quic.get_next_available_stream_id( - stream_id = self._connection.get_next_available_stream_id( is_unidirectional=is_unidirectional ) return self._create_stream(stream_id) ===========changed ref 5=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( - self, - connection: QuicConnection, + self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None - stream_handler: Optional[QuicStreamHandler] = None, ): loop = asyncio.get_event_loop() - self._connection = connection self._closed = asyncio.Event() self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None + self._quic = quic self._send_task: Optional[asyncio.Handle] = None self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None ===========changed ref 6=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: if configuration.is_client: assert ( original_connection_id is None ), "Cannot set original_connection_id for a client" else: assert ( configuration.certificate is not None ), "SSL certificate is required for a server" assert ( configuration.private_key is not None ), "SSL private key is required for a server" # counters for debugging self._quic_logger = configuration.quic_logger self._stateless_retry_count = 0 self._version_negotiation_count = 0 # configuration self._configuration = configuration self._is_client = configuration.is_client self._ack_delay = K_GRANULARITY self._close_at: Optional[float] = None self._close_event: Optional[events.ConnectionTerminated] = None self._connect_called = False self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} + self._events: Deque[events.QuicEvent] = deque() - self._events: Deque[events.Event] = deque() self._handshake_complete = False self._handshake_confirmed = False self._host_cids = [ QuicConnectionId( cid=os.urandom(8), sequence_number=0, stateless_reset_token=os.urandom(16), was_sent=True, ) ] self.host_cid = self._host</s>
aioquic.asyncio.protocol/QuicConnectionProtocol.datagram_received
Modified
aiortc~aioquic
759892804b56578170db7a28d873d65ab2e97c55
[asyncio] start converging HttpClient towards Protocol
<0>:<del> self._connection.receive_datagram( <1>:<add> self._quic.receive_datagram(cast(bytes, data), addr, now=self._loop.time()) <del> cast(bytes, data), addr, now=self._loop.time() <2>:<del> )
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: <0> self._connection.receive_datagram( <1> cast(bytes, data), addr, now=self._loop.time() <2> ) <3> self._send_pending() <4>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol _send_pending(self) -> None _send_pending() -> None ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def request_key_update(self) -> None: """ Request an update of the encryption keys. """ + self._quic.request_key_update() - self._connection.request_key_update() self._send_pending() ===========changed ref 1=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def close(self) -> None: """ Close the connection. """ + self._quic.close() - self._connection.close() self._send_pending() ===========changed ref 2=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def connect(self, addr: NetworkAddress, protocol_version: int) -> None: """ Initiate the TLS handshake. This method can only be called for clients and a single time. """ + self._quic.connect( - self._connection.connect( addr, now=self._loop.time(), protocol_version=protocol_version ) self._send_pending() ===========changed ref 3=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def change_connection_id(self) -> None: """ Change the connection ID used to communicate with the peer. The previous connection ID will be retired. """ + self._quic.change_connection_id() - self._connection.change_connection_id() self._send_pending() ===========changed ref 4=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def ping(self) -> None: """ Pings the remote host and waits for the response. """ assert self._ping_waiter is None, "already await a ping" self._ping_waiter = self._loop.create_future() + self._quic.send_ping(id(self._ping_waiter)) - self._connection.send_ping(id(self._ping_waiter)) self._send_pending() await asyncio.shield(self._ping_waiter) ===========changed ref 5=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def create_stream( self, is_unidirectional: bool = False ) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]: """ Create a QUIC stream and return a pair of (reader, writer) objects. The returned reader and writer objects are instances of :class:`asyncio.StreamReader` and :class:`asyncio.StreamWriter` classes. """ + stream_id = self._quic.get_next_available_stream_id( - stream_id = self._connection.get_next_available_stream_id( is_unidirectional=is_unidirectional ) return self._create_stream(stream_id) ===========changed ref 6=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( - self, - connection: QuicConnection, + self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None - stream_handler: Optional[QuicStreamHandler] = None, ): loop = asyncio.get_event_loop() - self._connection = connection self._closed = asyncio.Event() self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None + self._quic = quic self._send_task: Optional[asyncio.Handle] = None self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None ===========changed ref 7=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: if configuration.is_client: assert ( original_connection_id is None ), "Cannot set original_connection_id for a client" else: assert ( configuration.certificate is not None ), "SSL certificate is required for a server" assert ( configuration.private_key is not None ), "SSL private key is required for a server" # counters for debugging self._quic_logger = configuration.quic_logger self._stateless_retry_count = 0 self._version_negotiation_count = 0 # configuration self._configuration = configuration self._is_client = configuration.is_client self._ack_delay = K_GRANULARITY self._close_at: Optional[float] = None self._close_event: Optional[events.ConnectionTerminated] = None self._connect_called = False self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} + self._events: Deque[events.QuicEvent] = deque() - self._events: Deque[events.Event] = deque() self._handshake_complete = False self._handshake_confirmed = False self._host_cids = [ QuicConnectionId( cid=os.urandom(8), sequence_number=0, stateless_reset_token=os.urandom(16), was_sent=True, ) ] self.host_cid = self._host</s>
aioquic.asyncio.protocol/QuicConnectionProtocol._handle_timer
Modified
aiortc~aioquic
759892804b56578170db7a28d873d65ab2e97c55
[asyncio] start converging HttpClient towards Protocol
<1>:<del> <4>:<del> <5>:<add> self._quic.handle_timer(now=now) <del> self._connection.handle_timer(now=now) <6>:<del>
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def _handle_timer(self) -> None: <0> now = max(self._timer_at, self._loop.time()) <1> <2> self._timer = None <3> self._timer_at = None <4> <5> self._connection.handle_timer(now=now) <6> <7> self._send_pending() <8>
===========unchanged ref 0=========== at: _asyncio.Future done() set_exception(exception, /) set_result(result, /) at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._closed = asyncio.Event() self._connected_waiter = loop.create_future() self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None at: aioquic.quic.events ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str) HandshakeCompleted(alpn_protocol: Optional[str], early_data_accepted: bool, session_resumed: bool) at: asyncio.futures.Future _state = _PENDING _result = None _exception = None _loop = None _source_traceback = None _cancel_message = None _cancelled_exc = None _asyncio_future_blocking = False __log_traceback = False __class_getitem__ = classmethod(GenericAlias) done() -> bool set_result(result: _T, /) -> None set_exception(exception: Union[type, BaseException], /) -> None __iter__ = __await__ # make compatible with 'yield from'. at: asyncio.locks.Event set() -> None at: asyncio.streams.StreamReader _source_traceback = None feed_eof() -> None ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: - self._connection.receive_datagram( + self._quic.receive_datagram(cast(bytes, data), addr, now=self._loop.time()) - cast(bytes, data), addr, now=self._loop.time() - ) self._send_pending() ===========changed ref 1=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def request_key_update(self) -> None: """ Request an update of the encryption keys. """ + self._quic.request_key_update() - self._connection.request_key_update() self._send_pending() ===========changed ref 2=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def close(self) -> None: """ Close the connection. """ + self._quic.close() - self._connection.close() self._send_pending() ===========changed ref 3=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def connect(self, addr: NetworkAddress, protocol_version: int) -> None: """ Initiate the TLS handshake. This method can only be called for clients and a single time. """ + self._quic.connect( - self._connection.connect( addr, now=self._loop.time(), protocol_version=protocol_version ) self._send_pending() ===========changed ref 4=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def change_connection_id(self) -> None: """ Change the connection ID used to communicate with the peer. The previous connection ID will be retired. """ + self._quic.change_connection_id() - self._connection.change_connection_id() self._send_pending() ===========changed ref 5=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def ping(self) -> None: """ Pings the remote host and waits for the response. """ assert self._ping_waiter is None, "already await a ping" self._ping_waiter = self._loop.create_future() + self._quic.send_ping(id(self._ping_waiter)) - self._connection.send_ping(id(self._ping_waiter)) self._send_pending() await asyncio.shield(self._ping_waiter) ===========changed ref 6=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def create_stream( self, is_unidirectional: bool = False ) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]: """ Create a QUIC stream and return a pair of (reader, writer) objects. The returned reader and writer objects are instances of :class:`asyncio.StreamReader` and :class:`asyncio.StreamWriter` classes. """ + stream_id = self._quic.get_next_available_stream_id( - stream_id = self._connection.get_next_available_stream_id( is_unidirectional=is_unidirectional ) return self._create_stream(stream_id) ===========changed ref 7=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): + def _handle_event(self, event: events.QuicEvent) -> None: + if isinstance(event, events.ConnectionIdIssued): + self._connection_id_issued_handler(event.connection_id) + elif isinstance(event, events.ConnectionIdRetired): + self._connection_id_retired_handler(event.connection_id) + elif isinstance(event, events.ConnectionTerminated): + for reader in self._stream_readers.values(): + reader.feed_eof() + if not self._connected_waiter.done(): + self._connected_waiter.set_exception(ConnectionError) + self._closed.set() + elif isinstance(event, events.HandshakeCompleted): + self._connected_waiter.set_result(None) + elif isinstance(event, events.PingAcknowledged): + waiter = self._ping_waiter + self._ping_waiter = None + waiter.set_result(None) + elif isinstance(event, events.StreamDataReceived): + reader = self._stream_readers.get(event.stream_id, None) + if reader is None: + reader, writer = self._create_stream(event.stream_id) + self._stream_handler(reader, writer) + reader.feed_data(event.data) + if event.end_stream: + reader.feed_eof() + ===========changed ref 8=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( - self, - connection: QuicConnection, + self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None - stream_handler: Optional[QuicStreamHandler] = None, ): loop = asyncio.get_event_loop() - self._connection = connection self._closed = asyncio.Event() self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None + self._quic = quic self._send_task: Optional[asyncio.Handle] = None self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None
aioquic.asyncio.protocol/QuicConnectionProtocol._send_pending
Modified
aiortc~aioquic
759892804b56578170db7a28d873d65ab2e97c55
[asyncio] start converging HttpClient towards Protocol
<3>:<add> event = self._quic.next_event() <del> event = self._connection.next_event() <5>:<del> if isinstance(event, events.ConnectionIdIssued): <6>:<del> self._connection_id_issued_handler(event.connection_id) <7>:<del> elif isinstance(event, events.ConnectionIdRetired): <8>:<del> self._connection_id_retired_handler(event.connection_id) <9>:<del> elif isinstance(event, events.ConnectionTerminated): <10>:<del> for reader in self._stream_readers.values(): <11>:<del> reader.feed_eof() <12>:<del> if not self._connected_waiter.done(): <13>:<del> self._connected_waiter.set_exception(ConnectionError) <14>:<del> self._closed.set() <15>:<del> elif isinstance(event, events.HandshakeCompleted): <16>:<del> self._connected_waiter.set_result(None) <17>:<del> elif isinstance(event, events.PingAcknowledged): <18>:<del> waiter = self._ping_waiter <19>:<del> self._ping_waiter = None <20>:<del> waiter.set_result(None) <21>:<del> elif isinstance(event, events.StreamDataReceived): <22>:<del> reader = self._stream_readers.get(event.stream_id, None) <23>:<del> if reader is None: <24>:<del> reader, writer = self._create_stream(event.stream_id) <25>:<del> self._stream_handler(reader, writer) <26>:<del> reader.feed_data(event.data) <27>:<del> if event.end_stream: <28>:<del> reader.feed_eof() <29>:<del> <30>:<add> self._handle_event(event) <add> event = self._quic.next_event() <del> event = self._connection.next_event() <33>:<add> for data, addr in self._quic.datagrams_to_send(now=self._loop.time()): <del> for data, addr in self._connection.datagrams_to_send(now=self._loop.time()): <37>:<add> timer_at = self._quic.get_timer() <del> timer_at = self._connection.get_timer()
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def _send_pending(self) -> None: <0> self._send_task = None <1> <2> # process events <3> event = self._connection.next_event() <4> while event is not None: <5> if isinstance(event, events.ConnectionIdIssued): <6> self._connection_id_issued_handler(event.connection_id) <7> elif isinstance(event, events.ConnectionIdRetired): <8> self._connection_id_retired_handler(event.connection_id) <9> elif isinstance(event, events.ConnectionTerminated): <10> for reader in self._stream_readers.values(): <11> reader.feed_eof() <12> if not self._connected_waiter.done(): <13> self._connected_waiter.set_exception(ConnectionError) <14> self._closed.set() <15> elif isinstance(event, events.HandshakeCompleted): <16> self._connected_waiter.set_result(None) <17> elif isinstance(event, events.PingAcknowledged): <18> waiter = self._ping_waiter <19> self._ping_waiter = None <20> waiter.set_result(None) <21> elif isinstance(event, events.StreamDataReceived): <22> reader = self._stream_readers.get(event.stream_id, None) <23> if reader is None: <24> reader, writer = self._create_stream(event.stream_id) <25> self._stream_handler(reader, writer) <26> reader.feed_data(event.data) <27> if event.end_stream: <28> reader.feed_eof() <29> <30> event = self._connection.next_event() <31> <32> # send datagrams <33> for data, addr in self._connection.datagrams_to_send(now=self._loop.time()): <34> self._transport.sendto(data, addr) <35> <36> # re-arm timer <37> timer_at = self._connection.get_timer() <38> if self._timer is not</s>
===========below chunk 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def _send_pending(self) -> None: # offset: 1 self._timer.cancel() self._timer = None if self._timer is None and timer_at is not None: self._timer = self._loop.call_at(timer_at, self._handle_timer) self._timer_at = timer_at ===========unchanged ref 0=========== at: _asyncio.Future set_result(result, /) at: aioquic.asyncio.protocol.QuicConnectionProtocol _create_stream(self, stream_id: int) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter] _create_stream(stream_id: int) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter] _handle_event(event: events.QuicEvent) -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None self._quic = quic self._send_task: Optional[asyncio.Handle] = None self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transport: Optional[asyncio.DatagramTransport] = None self._stream_handler = lambda r, w: None self._stream_handler = stream_handler at: aioquic.asyncio.protocol.QuicConnectionProtocol.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: aioquic.asyncio.protocol.QuicConnectionProtocol.ping self._ping_waiter = self._loop.create_future() at: aioquic.quic.connection.QuicConnection datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_timer() -> Optional[float] handle_timer(now: float) -> None next_event() -> Optional[events.QuicEvent] at: aioquic.quic.events StreamDataReceived(data: bytes, end_stream: bool, stream_id: int) at: asyncio.events.TimerHandle __slots__ = ['_scheduled', '_when'] cancel() -> None ===========unchanged ref 1=========== at: asyncio.futures.Future set_result(result: _T, /) -> None at: asyncio.streams.StreamReader feed_eof() -> None feed_data(data: bytes) -> None at: asyncio.transports.DatagramTransport __slots__ = () sendto(data: Any, addr: Optional[_Address]=...) -> None at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co] ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): + def _handle_event(self, event: events.QuicEvent) -> None: + if isinstance(event, events.ConnectionIdIssued): + self._connection_id_issued_handler(event.connection_id) + elif isinstance(event, events.ConnectionIdRetired): + self._connection_id_retired_handler(event.connection_id) + elif isinstance(event, events.ConnectionTerminated): + for reader in self._stream_readers.values(): + reader.feed_eof() + if not self._connected_waiter.done(): + self._connected_waiter.set_exception(ConnectionError) + self._closed.set() + elif isinstance(event, events.HandshakeCompleted): + self._connected_waiter.set_result(None) + elif isinstance(event, events.PingAcknowledged): + waiter = self._ping_waiter + self._ping_waiter = None + waiter.set_result(None) + elif isinstance(event, events.StreamDataReceived): + reader = self._stream_readers.get(event.stream_id, None) + if reader is None: + reader, writer = self._create_stream(event.stream_id) + self._stream_handler(reader, writer) + reader.feed_data(event.data) + if event.end_stream: + reader.feed_eof() + ===========changed ref 1=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def _handle_timer(self) -> None: now = max(self._timer_at, self._loop.time()) - self._timer = None self._timer_at = None - + self._quic.handle_timer(now=now) - self._connection.handle_timer(now=now) - self._send_pending() ===========changed ref 2=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: - self._connection.receive_datagram( + self._quic.receive_datagram(cast(bytes, data), addr, now=self._loop.time()) - cast(bytes, data), addr, now=self._loop.time() - ) self._send_pending() ===========changed ref 3=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def request_key_update(self) -> None: """ Request an update of the encryption keys. """ + self._quic.request_key_update() - self._connection.request_key_update() self._send_pending() ===========changed ref 4=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def close(self) -> None: """ Close the connection. """ + self._quic.close() - self._connection.close() self._send_pending() ===========changed ref 5=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def connect(self, addr: NetworkAddress, protocol_version: int) -> None: """ Initiate the TLS handshake. This method can only be called for clients and a single time. """ + self._quic.connect( - self._connection.connect( addr, now=self._loop.time(), protocol_version=protocol_version ) self._send_pending() ===========changed ref 6=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def change_connection_id(self) -> None: """ Change the connection ID used to communicate with the peer. The previous connection ID will be retired. """ + self._quic.change_connection_id() - self._connection.change_connection_id() self._send_pending() ===========changed ref 7=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def ping(self) -> None: """ Pings the remote host and waits for the response. """ assert self._ping_waiter is None, "already await a ping" self._ping_waiter = self._loop.create_future() + self._quic.send_ping(id(self._ping_waiter)) - self._connection.send_ping(id(self._ping_waiter)) self._send_pending() await asyncio.shield(self._ping_waiter)
aioquic.asyncio.protocol/QuicStreamAdapter.write
Modified
aiortc~aioquic
759892804b56578170db7a28d873d65ab2e97c55
[asyncio] start converging HttpClient towards Protocol
<0>:<add> self.protocol._quic.send_stream_data(self.stream_id, data) <del> self.protocol._connection.send_stream_data(self.stream_id, data)
# module: aioquic.asyncio.protocol class QuicStreamAdapter(asyncio.Transport): def write(self, data): <0> self.protocol._connection.send_stream_data(self.stream_id, data) <1> self.protocol._send_soon() <2>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol _send_soon(self) -> None _send_soon() -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._quic = quic at: aioquic.asyncio.protocol.QuicStreamAdapter.__init__ self.protocol = protocol self.stream_id = stream_id at: aioquic.quic.connection.QuicConnection send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def _handle_timer(self) -> None: now = max(self._timer_at, self._loop.time()) - self._timer = None self._timer_at = None - + self._quic.handle_timer(now=now) - self._connection.handle_timer(now=now) - self._send_pending() ===========changed ref 1=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: - self._connection.receive_datagram( + self._quic.receive_datagram(cast(bytes, data), addr, now=self._loop.time()) - cast(bytes, data), addr, now=self._loop.time() - ) self._send_pending() ===========changed ref 2=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def request_key_update(self) -> None: """ Request an update of the encryption keys. """ + self._quic.request_key_update() - self._connection.request_key_update() self._send_pending() ===========changed ref 3=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def close(self) -> None: """ Close the connection. """ + self._quic.close() - self._connection.close() self._send_pending() ===========changed ref 4=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def connect(self, addr: NetworkAddress, protocol_version: int) -> None: """ Initiate the TLS handshake. This method can only be called for clients and a single time. """ + self._quic.connect( - self._connection.connect( addr, now=self._loop.time(), protocol_version=protocol_version ) self._send_pending() ===========changed ref 5=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def change_connection_id(self) -> None: """ Change the connection ID used to communicate with the peer. The previous connection ID will be retired. """ + self._quic.change_connection_id() - self._connection.change_connection_id() self._send_pending() ===========changed ref 6=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def ping(self) -> None: """ Pings the remote host and waits for the response. """ assert self._ping_waiter is None, "already await a ping" self._ping_waiter = self._loop.create_future() + self._quic.send_ping(id(self._ping_waiter)) - self._connection.send_ping(id(self._ping_waiter)) self._send_pending() await asyncio.shield(self._ping_waiter) ===========changed ref 7=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def create_stream( self, is_unidirectional: bool = False ) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]: """ Create a QUIC stream and return a pair of (reader, writer) objects. The returned reader and writer objects are instances of :class:`asyncio.StreamReader` and :class:`asyncio.StreamWriter` classes. """ + stream_id = self._quic.get_next_available_stream_id( - stream_id = self._connection.get_next_available_stream_id( is_unidirectional=is_unidirectional ) return self._create_stream(stream_id) ===========changed ref 8=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): + def _handle_event(self, event: events.QuicEvent) -> None: + if isinstance(event, events.ConnectionIdIssued): + self._connection_id_issued_handler(event.connection_id) + elif isinstance(event, events.ConnectionIdRetired): + self._connection_id_retired_handler(event.connection_id) + elif isinstance(event, events.ConnectionTerminated): + for reader in self._stream_readers.values(): + reader.feed_eof() + if not self._connected_waiter.done(): + self._connected_waiter.set_exception(ConnectionError) + self._closed.set() + elif isinstance(event, events.HandshakeCompleted): + self._connected_waiter.set_result(None) + elif isinstance(event, events.PingAcknowledged): + waiter = self._ping_waiter + self._ping_waiter = None + waiter.set_result(None) + elif isinstance(event, events.StreamDataReceived): + reader = self._stream_readers.get(event.stream_id, None) + if reader is None: + reader, writer = self._create_stream(event.stream_id) + self._stream_handler(reader, writer) + reader.feed_data(event.data) + if event.end_stream: + reader.feed_eof() + ===========changed ref 9=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( - self, - connection: QuicConnection, + self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None - stream_handler: Optional[QuicStreamHandler] = None, ): loop = asyncio.get_event_loop() - self._connection = connection self._closed = asyncio.Event() self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None + self._quic = quic self._send_task: Optional[asyncio.Handle] = None self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None
aioquic.asyncio.protocol/QuicStreamAdapter.write_eof
Modified
aiortc~aioquic
759892804b56578170db7a28d873d65ab2e97c55
[asyncio] start converging HttpClient towards Protocol
<0>:<add> self.protocol._quic.send_stream_data(self.stream_id, b"", end_stream=True) <del> self.protocol._connection.send_stream_data(self.stream_id, b"", end_stream=True)
# module: aioquic.asyncio.protocol class QuicStreamAdapter(asyncio.Transport): def write_eof(self): <0> self.protocol._connection.send_stream_data(self.stream_id, b"", end_stream=True) <1> self.protocol._send_soon() <2>
===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicStreamAdapter(asyncio.Transport): def write(self, data): + self.protocol._quic.send_stream_data(self.stream_id, data) - self.protocol._connection.send_stream_data(self.stream_id, data) self.protocol._send_soon() ===========changed ref 1=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def _handle_timer(self) -> None: now = max(self._timer_at, self._loop.time()) - self._timer = None self._timer_at = None - + self._quic.handle_timer(now=now) - self._connection.handle_timer(now=now) - self._send_pending() ===========changed ref 2=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: - self._connection.receive_datagram( + self._quic.receive_datagram(cast(bytes, data), addr, now=self._loop.time()) - cast(bytes, data), addr, now=self._loop.time() - ) self._send_pending() ===========changed ref 3=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def request_key_update(self) -> None: """ Request an update of the encryption keys. """ + self._quic.request_key_update() - self._connection.request_key_update() self._send_pending() ===========changed ref 4=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def close(self) -> None: """ Close the connection. """ + self._quic.close() - self._connection.close() self._send_pending() ===========changed ref 5=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def connect(self, addr: NetworkAddress, protocol_version: int) -> None: """ Initiate the TLS handshake. This method can only be called for clients and a single time. """ + self._quic.connect( - self._connection.connect( addr, now=self._loop.time(), protocol_version=protocol_version ) self._send_pending() ===========changed ref 6=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def change_connection_id(self) -> None: """ Change the connection ID used to communicate with the peer. The previous connection ID will be retired. """ + self._quic.change_connection_id() - self._connection.change_connection_id() self._send_pending() ===========changed ref 7=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def ping(self) -> None: """ Pings the remote host and waits for the response. """ assert self._ping_waiter is None, "already await a ping" self._ping_waiter = self._loop.create_future() + self._quic.send_ping(id(self._ping_waiter)) - self._connection.send_ping(id(self._ping_waiter)) self._send_pending() await asyncio.shield(self._ping_waiter) ===========changed ref 8=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def create_stream( self, is_unidirectional: bool = False ) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]: """ Create a QUIC stream and return a pair of (reader, writer) objects. The returned reader and writer objects are instances of :class:`asyncio.StreamReader` and :class:`asyncio.StreamWriter` classes. """ + stream_id = self._quic.get_next_available_stream_id( - stream_id = self._connection.get_next_available_stream_id( is_unidirectional=is_unidirectional ) return self._create_stream(stream_id) ===========changed ref 9=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): + def _handle_event(self, event: events.QuicEvent) -> None: + if isinstance(event, events.ConnectionIdIssued): + self._connection_id_issued_handler(event.connection_id) + elif isinstance(event, events.ConnectionIdRetired): + self._connection_id_retired_handler(event.connection_id) + elif isinstance(event, events.ConnectionTerminated): + for reader in self._stream_readers.values(): + reader.feed_eof() + if not self._connected_waiter.done(): + self._connected_waiter.set_exception(ConnectionError) + self._closed.set() + elif isinstance(event, events.HandshakeCompleted): + self._connected_waiter.set_result(None) + elif isinstance(event, events.PingAcknowledged): + waiter = self._ping_waiter + self._ping_waiter = None + waiter.set_result(None) + elif isinstance(event, events.StreamDataReceived): + reader = self._stream_readers.get(event.stream_id, None) + if reader is None: + reader, writer = self._create_stream(event.stream_id) + self._stream_handler(reader, writer) + reader.feed_data(event.data) + if event.end_stream: + reader.feed_eof() + ===========changed ref 10=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( - self, - connection: QuicConnection, + self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None - stream_handler: Optional[QuicStreamHandler] = None, ): loop = asyncio.get_event_loop() - self._connection = connection self._closed = asyncio.Event() self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None + self._quic = quic self._send_task: Optional[asyncio.Handle] = None self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None
aioquic.h0.connection/H0Connection.handle_event
Modified
aiortc~aioquic
759892804b56578170db7a28d873d65ab2e97c55
[asyncio] start converging HttpClient towards Protocol
<2>:<del> if ( <3>:<del> isinstance(event, aioquic.quic.events.StreamDataReceived) <4>:<del> and (event.stream_id % 4) == 0 <5>:<del> ): <6>:<add> if isinstance(event, StreamDataReceived) and (event.stream_id % 4) == 0:
# module: aioquic.h0.connection class H0Connection: + def handle_event(self, event: QuicEvent) -> List[Event]: - def handle_event(self, event: aioquic.quic.events.Event) -> List[Event]: <0> http_events: List[Event] = [] <1> <2> if ( <3> isinstance(event, aioquic.quic.events.StreamDataReceived) <4> and (event.stream_id % 4) == 0 <5> ): <6> data = event.data <7> if not self._headers_received.get(event.stream_id, False): <8> if self._is_client: <9> http_events.append( <10> ResponseReceived( <11> headers=[], stream_ended=False, stream_id=event.stream_id <12> ) <13> ) <14> else: <15> method, path = data.rstrip().split(b" ", 1) <16> http_events.append( <17> RequestReceived( <18> headers=[(b":method", method), (b":path", path)], <19> stream_ended=False, <20> stream_id=event.stream_id, <21> ) <22> ) <23> data = b"" <24> self._headers_received[event.stream_id] = True <25> <26> http_events.append( <27> DataReceived( <28> data=data, stream_ended=event.end_stream, stream_id=event.stream_id <29> ) <30> ) <31> <32> return http_events <33>
===========unchanged ref 0=========== at: aioquic.h0.connection.H0Connection.__init__ self._headers_received: Dict[int, bool] = {} self._is_client = quic.configuration.is_client at: aioquic.h3.events Event() DataReceived(data: bytes, stream_id: int, stream_ended: bool) RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.h3.events.DataReceived data: bytes stream_id: int stream_ended: bool at: aioquic.h3.events.RequestReceived headers: Headers stream_id: int stream_ended: bool at: aioquic.h3.events.ResponseReceived headers: Headers stream_id: int stream_ended: bool at: aioquic.quic.events Event() StreamDataReceived(data: bytes, end_stream: bool, stream_id: int) at: typing List = _alias(list, 1, inst=False, name='List') at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co] ===========changed ref 0=========== # module: aioquic.quic.events - class Event: - """ - Base class for QUIC events. - """ - - pass - ===========changed ref 1=========== # module: aioquic.quic.events - class Event: - """ - Base class for QUIC events. - """ - - pass - ===========changed ref 2=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def close(self) -> None: """ Close the connection. """ + self._quic.close() - self._connection.close() self._send_pending() ===========changed ref 3=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def request_key_update(self) -> None: """ Request an update of the encryption keys. """ + self._quic.request_key_update() - self._connection.request_key_update() self._send_pending() ===========changed ref 4=========== # module: aioquic.asyncio.protocol class QuicStreamAdapter(asyncio.Transport): def write(self, data): + self.protocol._quic.send_stream_data(self.stream_id, data) - self.protocol._connection.send_stream_data(self.stream_id, data) self.protocol._send_soon() ===========changed ref 5=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def change_connection_id(self) -> None: """ Change the connection ID used to communicate with the peer. The previous connection ID will be retired. """ + self._quic.change_connection_id() - self._connection.change_connection_id() self._send_pending() ===========changed ref 6=========== # module: aioquic.asyncio.protocol class QuicStreamAdapter(asyncio.Transport): def write_eof(self): + self.protocol._quic.send_stream_data(self.stream_id, b"", end_stream=True) - self.protocol._connection.send_stream_data(self.stream_id, b"", end_stream=True) self.protocol._send_soon() ===========changed ref 7=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: - self._connection.receive_datagram( + self._quic.receive_datagram(cast(bytes, data), addr, now=self._loop.time()) - cast(bytes, data), addr, now=self._loop.time() - ) self._send_pending() ===========changed ref 8=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def connect(self, addr: NetworkAddress, protocol_version: int) -> None: """ Initiate the TLS handshake. This method can only be called for clients and a single time. """ + self._quic.connect( - self._connection.connect( addr, now=self._loop.time(), protocol_version=protocol_version ) self._send_pending() ===========changed ref 9=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def _handle_timer(self) -> None: now = max(self._timer_at, self._loop.time()) - self._timer = None self._timer_at = None - + self._quic.handle_timer(now=now) - self._connection.handle_timer(now=now) - self._send_pending() ===========changed ref 10=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def ping(self) -> None: """ Pings the remote host and waits for the response. """ assert self._ping_waiter is None, "already await a ping" self._ping_waiter = self._loop.create_future() + self._quic.send_ping(id(self._ping_waiter)) - self._connection.send_ping(id(self._ping_waiter)) self._send_pending() await asyncio.shield(self._ping_waiter) ===========changed ref 11=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def create_stream( self, is_unidirectional: bool = False ) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]: """ Create a QUIC stream and return a pair of (reader, writer) objects. The returned reader and writer objects are instances of :class:`asyncio.StreamReader` and :class:`asyncio.StreamWriter` classes. """ + stream_id = self._quic.get_next_available_stream_id( - stream_id = self._connection.get_next_available_stream_id( is_unidirectional=is_unidirectional ) return self._create_stream(stream_id) ===========changed ref 12=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( - self, - connection: QuicConnection, + self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None - stream_handler: Optional[QuicStreamHandler] = None, ): loop = asyncio.get_event_loop() - self._connection = connection self._closed = asyncio.Event() self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None + self._quic = quic self._send_task: Optional[asyncio.Handle] = None self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None
aioquic.h3.connection/H3Connection.handle_event
Modified
aiortc~aioquic
759892804b56578170db7a28d873d65ab2e97c55
[asyncio] start converging HttpClient towards Protocol
<5>:<add> if isinstance(event, StreamDataReceived): <del> if isinstance(event, aioquic.quic.events.StreamDataReceived):
# module: aioquic.h3.connection class H3Connection: + def handle_event(self, event: QuicEvent) -> List[Event]: - def handle_event(self, event: aioquic.quic.events.Event) -> List[Event]: <0> """ <1> Handle a QUIC event and return a list of HTTP events. <2> <3> :param event: The QUIC event to handle. <4> """ <5> if isinstance(event, aioquic.quic.events.StreamDataReceived): <6> stream_id = event.stream_id <7> if stream_id not in self._stream: <8> self._stream[stream_id] = H3Stream() <9> if stream_id % 4 == 0: <10> return self._receive_stream_data_bidi( <11> stream_id, event.data, event.end_stream <12> ) <13> elif stream_is_unidirectional(stream_id): <14> return self._receive_stream_data_uni(stream_id, event.data) <15> return [] <16>
===========unchanged ref 0=========== at: aioquic.h3.connection H3Stream() at: aioquic.h3.connection.H3Connection _receive_stream_data_bidi(stream_id: int, data: bytes, stream_ended: bool) -> List[Event] _receive_stream_data_uni(stream_id: int, data: bytes) -> List[Event] at: aioquic.h3.connection.H3Connection.__init__ self._stream: Dict[int, H3Stream] = {} at: aioquic.h3.events Event() at: aioquic.quic.connection stream_is_unidirectional(stream_id: int) -> bool at: aioquic.quic.events StreamDataReceived(data: bytes, end_stream: bool, stream_id: int) at: aioquic.quic.events.StreamDataReceived data: bytes end_stream: bool stream_id: int at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.quic.events - class Event: - """ - Base class for QUIC events. - """ - - pass - ===========changed ref 1=========== # module: aioquic.quic.events - class Event: - """ - Base class for QUIC events. - """ - - pass - ===========changed ref 2=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def close(self) -> None: """ Close the connection. """ + self._quic.close() - self._connection.close() self._send_pending() ===========changed ref 3=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def request_key_update(self) -> None: """ Request an update of the encryption keys. """ + self._quic.request_key_update() - self._connection.request_key_update() self._send_pending() ===========changed ref 4=========== # module: aioquic.asyncio.protocol class QuicStreamAdapter(asyncio.Transport): def write(self, data): + self.protocol._quic.send_stream_data(self.stream_id, data) - self.protocol._connection.send_stream_data(self.stream_id, data) self.protocol._send_soon() ===========changed ref 5=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def change_connection_id(self) -> None: """ Change the connection ID used to communicate with the peer. The previous connection ID will be retired. """ + self._quic.change_connection_id() - self._connection.change_connection_id() self._send_pending() ===========changed ref 6=========== # module: aioquic.asyncio.protocol class QuicStreamAdapter(asyncio.Transport): def write_eof(self): + self.protocol._quic.send_stream_data(self.stream_id, b"", end_stream=True) - self.protocol._connection.send_stream_data(self.stream_id, b"", end_stream=True) self.protocol._send_soon() ===========changed ref 7=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: - self._connection.receive_datagram( + self._quic.receive_datagram(cast(bytes, data), addr, now=self._loop.time()) - cast(bytes, data), addr, now=self._loop.time() - ) self._send_pending() ===========changed ref 8=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def connect(self, addr: NetworkAddress, protocol_version: int) -> None: """ Initiate the TLS handshake. This method can only be called for clients and a single time. """ + self._quic.connect( - self._connection.connect( addr, now=self._loop.time(), protocol_version=protocol_version ) self._send_pending() ===========changed ref 9=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def _handle_timer(self) -> None: now = max(self._timer_at, self._loop.time()) - self._timer = None self._timer_at = None - + self._quic.handle_timer(now=now) - self._connection.handle_timer(now=now) - self._send_pending() ===========changed ref 10=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def ping(self) -> None: """ Pings the remote host and waits for the response. """ assert self._ping_waiter is None, "already await a ping" self._ping_waiter = self._loop.create_future() + self._quic.send_ping(id(self._ping_waiter)) - self._connection.send_ping(id(self._ping_waiter)) self._send_pending() await asyncio.shield(self._ping_waiter) ===========changed ref 11=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def create_stream( self, is_unidirectional: bool = False ) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]: """ Create a QUIC stream and return a pair of (reader, writer) objects. The returned reader and writer objects are instances of :class:`asyncio.StreamReader` and :class:`asyncio.StreamWriter` classes. """ + stream_id = self._quic.get_next_available_stream_id( - stream_id = self._connection.get_next_available_stream_id( is_unidirectional=is_unidirectional ) return self._create_stream(stream_id) ===========changed ref 12=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( - self, - connection: QuicConnection, + self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None - stream_handler: Optional[QuicStreamHandler] = None, ): loop = asyncio.get_event_loop() - self._connection = connection self._closed = asyncio.Event() self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None + self._quic = quic self._send_task: Optional[asyncio.Handle] = None self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None
examples.http3-client/HttpClient.__init__
Modified
aiortc~aioquic
759892804b56578170db7a28d873d65ab2e97c55
[asyncio] start converging HttpClient towards Protocol
<0>:<add> super().__init__( <add> quic=QuicConnection( <add> configuration=configuration, <add> session_ticket_handler=session_ticket_handler, <add> ) <add> ) <add> <del> self._closed = asyncio.Event() <3>:<del> self._loop = asyncio.get_event_loop() <4>:<del> self._quic = QuicConnection( <5>:<del> configuration=configuration, session_ticket_handler=session_ticket_handler <6>:<del> ) <8>:<del> self._timer: Optional[asyncio.TimerHandle] = None <9>:<del> self._timer_at = 0.0
# module: examples.http3-client + class HttpClient(QuicConnectionProtocol): - class HttpClient(asyncio.DatagramProtocol): def __init__( self, *, configuration: QuicConfiguration, server_addr: NetworkAddress, session_ticket_handler: Optional[SessionTicketHandler] = None ): <0> self._closed = asyncio.Event() <1> self._connect_called = False <2> self._http: HttpConnection <3> self._loop = asyncio.get_event_loop() <4> self._quic = QuicConnection( <5> configuration=configuration, session_ticket_handler=session_ticket_handler <6> ) <7> self._server_addr = server_addr <8> self._timer: Optional[asyncio.TimerHandle] = None <9> self._timer_at = 0.0 <10> <11> self._request_events: Dict[int, Deque[Event]] = {} <12> self._request_waiter: Dict[int, asyncio.Future[Deque[Event]]] = {} <13> <14> if configuration.alpn_protocols[0].startswith("hq-"): <15> self._http = H0Connection(self._quic) <16> else: <17> self._http = H3Connection(self._quic) <18>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol QuicConnectionProtocol(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.asyncio.protocol.QuicConnectionProtocol __init__(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) __init__(self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._quic = quic at: aioquic.h0.connection H0Connection(quic: QuicConnection) at: aioquic.h3.events Event() at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.quic.connection NetworkAddress = Any ===========unchanged ref 1=========== QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.tls SessionTicketHandler = Callable[[SessionTicket], None] at: asyncio.futures Future(*, loop: Optional[AbstractEventLoop]=...) Future = _CFuture = _asyncio.Future at: examples.http3-client HttpConnection = Union[H0Connection, H3Connection] at: examples.http3-client.HttpClient.get self._connect_called = True at: typing Deque = _alias(collections.deque, 1, name='Deque') Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( - self, - connection: QuicConnection, + self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None - stream_handler: Optional[QuicStreamHandler] = None, ): loop = asyncio.get_event_loop() - self._connection = connection self._closed = asyncio.Event() self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None + self._quic = quic self._send_task: Optional[asyncio.Handle] = None self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None ===========changed ref 1=========== # module: aioquic.quic.events - class Event: - """ - Base class for QUIC events. - """ - - pass - ===========changed ref 2=========== # module: aioquic.quic.events - class Event: - """ - Base class for QUIC events. - """ - - pass - ===========changed ref 3=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def close(self) -> None: """ Close the connection. """ + self._quic.close() - self._connection.close() self._send_pending() ===========changed ref 4=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def request_key_update(self) -> None: """ Request an update of the encryption keys. """ + self._quic.request_key_update() - self._connection.request_key_update() self._send_pending() ===========changed ref 5=========== # module: aioquic.asyncio.protocol class QuicStreamAdapter(asyncio.Transport): def write(self, data): + self.protocol._quic.send_stream_data(self.stream_id, data) - self.protocol._connection.send_stream_data(self.stream_id, data) self.protocol._send_soon() ===========changed ref 6=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def change_connection_id(self) -> None: """ Change the connection ID used to communicate with the peer. The previous connection ID will be retired. """ + self._quic.change_connection_id() - self._connection.change_connection_id() self._send_pending() ===========changed ref 7=========== # module: aioquic.asyncio.protocol class QuicStreamAdapter(asyncio.Transport): def write_eof(self): + self.protocol._quic.send_stream_data(self.stream_id, b"", end_stream=True) - self.protocol._connection.send_stream_data(self.stream_id, b"", end_stream=True) self.protocol._send_soon() ===========changed ref 8=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: - self._connection.receive_datagram( + self._quic.receive_datagram(cast(bytes, data), addr, now=self._loop.time()) - cast(bytes, data), addr, now=self._loop.time() - ) self._send_pending() ===========changed ref 9=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def connect(self, addr: NetworkAddress, protocol_version: int) -> None: """ Initiate the TLS handshake. This method can only be called for clients and a single time. """ + self._quic.connect( - self._connection.connect( addr, now=self._loop.time(), protocol_version=protocol_version ) self._send_pending() ===========changed ref 10=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def _handle_timer(self) -> None: now = max(self._timer_at, self._loop.time()) - self._timer = None self._timer_at = None - + self._quic.handle_timer(now=now) - self._connection.handle_timer(now=now) - self._send_pending()
examples.http3-client/HttpClient.get
Modified
aiortc~aioquic
759892804b56578170db7a28d873d65ab2e97c55
[asyncio] start converging HttpClient towards Protocol
<22>:<add> self._send_pending() <del> self._consume_events()
# module: examples.http3-client + class HttpClient(QuicConnectionProtocol): - class HttpClient(asyncio.DatagramProtocol): def get(self, path: str) -> Deque[Event]: <0> """ <1> Perform a GET request. <2> """ <3> if not self._connect_called: <4> self._quic.connect(self._server_addr, now=self._loop.time()) <5> self._connect_called = True <6> <7> stream_id = self._quic.get_next_available_stream_id() <8> self._http.send_headers( <9> stream_id=stream_id, <10> headers=[ <11> (b":method", b"GET"), <12> (b":scheme", b"https"), <13> (b":authority", self._quic.configuration.server_name.encode("utf8")), <14> (b":path", path.encode("utf8")), <15> ], <16> ) <17> self._http.send_data(stream_id=stream_id, data=b"", end_stream=True) <18> <19> waiter = self._loop.create_future() <20> self._request_events[stream_id] = deque() <21> self._request_waiter[stream_id] = waiter <22> self._consume_events() <23> <24> return await asyncio.shield(waiter) <25>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol _handle_event(self, event: events.QuicEvent) -> None _send_pending() -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._loop = loop self._quic = quic at: aioquic.h0.connection.H0Connection handle_event(event: QuicEvent) -> List[Event] send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: List[Tuple[bytes, bytes]]) -> None at: aioquic.h3.connection.H3Connection handle_event(event: QuicEvent) -> List[Event] send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers) -> None at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.quic.configuration.QuicConfiguration server_name: Optional[str] = None at: aioquic.quic.connection.QuicConnection get_next_available_stream_id(is_unidirectional=False) -> int at: asyncio.events.AbstractEventLoop create_future() -> Future[Any] at: asyncio.tasks shield(arg: _FutureT[_T], *, loop: Optional[AbstractEventLoop]=...) -> Future[_T] at: collections deque(iterable: Iterable[_T]=..., maxlen: Optional[int]=...) at: examples.http3-client.HttpClient.__init__ self._http = H3Connection(self._quic) self._http: HttpConnection self._http = H0Connection(self._quic) ===========unchanged ref 1=========== self._request_events: Dict[int, Deque[Event]] = {} self._request_waiter: Dict[int, asyncio.Future[Deque[Event]]] = {} ===========changed ref 0=========== # module: aioquic.h3.connection class H3Connection: + def handle_event(self, event: QuicEvent) -> List[Event]: - def handle_event(self, event: aioquic.quic.events.Event) -> List[Event]: """ Handle a QUIC event and return a list of HTTP events. :param event: The QUIC event to handle. """ + if isinstance(event, StreamDataReceived): - if isinstance(event, aioquic.quic.events.StreamDataReceived): stream_id = event.stream_id if stream_id not in self._stream: self._stream[stream_id] = H3Stream() if stream_id % 4 == 0: return self._receive_stream_data_bidi( stream_id, event.data, event.end_stream ) elif stream_is_unidirectional(stream_id): return self._receive_stream_data_uni(stream_id, event.data) return [] ===========changed ref 1=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): + def _handle_event(self, event: events.QuicEvent) -> None: + if isinstance(event, events.ConnectionIdIssued): + self._connection_id_issued_handler(event.connection_id) + elif isinstance(event, events.ConnectionIdRetired): + self._connection_id_retired_handler(event.connection_id) + elif isinstance(event, events.ConnectionTerminated): + for reader in self._stream_readers.values(): + reader.feed_eof() + if not self._connected_waiter.done(): + self._connected_waiter.set_exception(ConnectionError) + self._closed.set() + elif isinstance(event, events.HandshakeCompleted): + self._connected_waiter.set_result(None) + elif isinstance(event, events.PingAcknowledged): + waiter = self._ping_waiter + self._ping_waiter = None + waiter.set_result(None) + elif isinstance(event, events.StreamDataReceived): + reader = self._stream_readers.get(event.stream_id, None) + if reader is None: + reader, writer = self._create_stream(event.stream_id) + self._stream_handler(reader, writer) + reader.feed_data(event.data) + if event.end_stream: + reader.feed_eof() + ===========changed ref 2=========== # module: aioquic.h0.connection class H0Connection: + def handle_event(self, event: QuicEvent) -> List[Event]: - def handle_event(self, event: aioquic.quic.events.Event) -> List[Event]: http_events: List[Event] = [] - if ( - isinstance(event, aioquic.quic.events.StreamDataReceived) - and (event.stream_id % 4) == 0 - ): + if isinstance(event, StreamDataReceived) and (event.stream_id % 4) == 0: data = event.data if not self._headers_received.get(event.stream_id, False): if self._is_client: http_events.append( ResponseReceived( headers=[], stream_ended=False, stream_id=event.stream_id ) ) else: method, path = data.rstrip().split(b" ", 1) http_events.append( RequestReceived( headers=[(b":method", method), (b":path", path)], stream_ended=False, stream_id=event.stream_id, ) ) data = b"" self._headers_received[event.stream_id] = True http_events.append( DataReceived( data=data, stream_ended=event.end_stream, stream_id=event.stream_id ) ) return http_events
examples.http3-client/run
Modified
aiortc~aioquic
759892804b56578170db7a28d873d65ab2e97c55
[asyncio] start converging HttpClient towards Protocol
# module: examples.http3-client def run(url: str, legacy_http: bool, **kwargs) -> None: <0> # parse URL <1> parsed = urlparse(url) <2> assert parsed.scheme == "https", "Only HTTPS URLs are supported." <3> if ":" in parsed.netloc: <4> server_name, port_str = parsed.netloc.split(":") <5> port = int(port_str) <6> else: <7> server_name = parsed.netloc <8> port = 443 <9> <10> # lookup remote address <11> infos = await loop.getaddrinfo(server_name, port, type=socket.SOCK_DGRAM) <12> server_addr = infos[0][4] <13> if len(server_addr) == 2: <14> server_addr = ("::ffff:" + server_addr[0], server_addr[1], 0, 0) <15> <16> # prepare QUIC connection <17> _, client = await loop.create_datagram_endpoint( <18> lambda: HttpClient( <19> configuration=QuicConfiguration( <20> alpn_protocols=["hq-22" if legacy_http else "h3-22"], <21> is_client=True, <22> server_name=server_name, <23> **kwargs <24> ), <25> server_addr=server_addr, <26> session_ticket_handler=save_session_ticket, <27> ), <28> local_addr=("::", 0), <29> ) <30> client = cast(HttpClient, client) <31> <32> # perform request <33> start = time.time() <34> http_events = await client.get(parsed.path) <35> elapsed = time.time() - start <36> <37> # print speed <38> octets = 0 <39> for http_event in http_events: <40> if isinstance(http_event, DataReceived): <41> octets += len(http_event.data) <42> logger.info( <43> "Received %d bytes in %.1f s (%.3f Mbps)" <44> % (octets, elapsed, octets *</s>
===========below chunk 0=========== # module: examples.http3-client def run(url: str, legacy_http: bool, **kwargs) -> None: # offset: 1 ) # print response for http_event in http_events: if isinstance(http_event, ResponseReceived): headers = b"" for k, v in http_event.headers: headers += k + b": " + v + b"\r\n" if headers: sys.stderr.buffer.write(headers + b"\r\n") sys.stderr.buffer.flush() elif isinstance(http_event, DataReceived): sys.stdout.buffer.write(http_event.data) sys.stdout.buffer.flush() # close QUIC connection await client.close() ===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol close() -> None wait_closed() -> None at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.quic.logger QuicLogger() at: argparse ArgumentParser(prog: Optional[str]=..., usage: Optional[str]=..., description: Optional[str]=..., epilog: Optional[str]=..., parents: Sequence[ArgumentParser]=..., formatter_class: _FormatterClass=..., prefix_chars: str=..., fromfile_prefix_chars: Optional[str]=..., argument_default: Any=..., conflict_handler: str=..., add_help: bool=..., allow_abbrev: bool=...) at: argparse.ArgumentParser parse_args(args: Optional[Sequence[Text]], namespace: None) -> Namespace parse_args(args: Optional[Sequence[Text]]=...) -> Namespace parse_args(*, namespace: None) -> Namespace parse_args(args: Optional[Sequence[Text]], namespace: _N) -> _N parse_args(*, namespace: _N) -> _N at: argparse._ActionsContainer add_argument(*name_or_flags: Text, action: Union[Text, Type[Action]]=..., nargs: Union[int, Text]=..., const: Any=..., default: Any=..., type: Union[Callable[[Text], _T], Callable[[str], _T], FileType]=..., choices: Iterable[_T]=..., required: bool=..., help: Optional[Text]=..., metavar: Optional[Union[Text, Tuple[Text, ...]]]=..., dest: Optional[Text]=..., version: Text=..., **kwargs: Any) -> Action at: examples.http3-client logger = logging.getLogger("client") at: examples.http3-client.run client = cast(HttpClient, client) ===========unchanged ref 1=========== http_events = await client.get(parsed.path) elapsed = time.time() - start at: logging INFO = 20 DEBUG = 10 basicConfig(*, filename: Optional[StrPath]=..., filemode: str=..., format: str=..., datefmt: Optional[str]=..., style: str=..., level: Optional[_Level]=..., stream: Optional[IO[str]]=..., handlers: Optional[Iterable[Handler]]=...) -> None at: logging.Logger info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None at: sys stdout: TextIO stderr: TextIO at: typing.BinaryIO __slots__ = () write(s: AnyStr) -> int at: typing.IO __slots__ = () flush() -> None at: typing.TextIO __slots__ = () ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def close(self) -> None: """ Close the connection. """ + self._quic.close() - self._connection.close() self._send_pending() ===========changed ref 1=========== # module: examples.http3-client + class HttpClient(QuicConnectionProtocol): - class HttpClient(asyncio.DatagramProtocol): - def _handle_timer(self) -> None: - now = max(self._timer_at, self._loop.time()) - self._timer = None - self._timer_at = None - self._quic.handle_timer(now=now) - self._consume_events() - ===========changed ref 2=========== # module: examples.http3-client + class HttpClient(QuicConnectionProtocol): - class HttpClient(asyncio.DatagramProtocol): - def connection_made(self, transport: asyncio.BaseTransport) -> None: - self._transport = cast(asyncio.DatagramTransport, transport) - ===========changed ref 3=========== # module: examples.http3-client + class HttpClient(QuicConnectionProtocol): - class HttpClient(asyncio.DatagramProtocol): - def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: - self._quic.receive_datagram(cast(bytes, data), addr, self._loop.time()) - self._consume_events() - ===========changed ref 4=========== # module: examples.http3-client + class HttpClient(QuicConnectionProtocol): - class HttpClient(asyncio.DatagramProtocol): - def close(self) -> None: - """ - Close the connection. - """ - self._quic.close() - self._consume_events() - await self._closed.wait() - ===========changed ref 5=========== # module: examples.http3-client + class HttpClient(QuicConnectionProtocol): - class HttpClient(asyncio.DatagramProtocol): + def _handle_event(self, event: QuicEvent): + #  pass event to the HTTP layer + for http_event in self._http.handle_event(event): + if ( + isinstance(http_event, (ResponseReceived, DataReceived)) + and http_event.stream_id in self._request_events + ): + self._request_events[http_event.stream_id].append(http_event) + if http_event.stream_ended: + request_waiter = self._request_waiter.pop(http_event.stream_id) + request_waiter.set_result( + self._request_events.pop(http_event.stream_id) + ) + + if isinstance(event, ConnectionTerminated): + self._closed.set() + ===========changed ref 6=========== # module: examples.http3-client + class HttpClient(QuicConnectionProtocol): - class HttpClient(asyncio.DatagramProtocol): def get(self, path: str) -> Deque[Event]: """ Perform a GET request. """ if not self._connect_called: self._quic.connect(self._server_addr, now=self._loop.time()) self._connect_called = True stream_id = self._quic.get_next_available_stream_id() self._http.send_headers( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", self._quic.configuration.server_name.encode("utf8")), (b":path", path.encode("utf8")), ], ) self._http.send_data(stream_id=stream_id, data=b"", end_stream=True) waiter = self._loop.create_future() self._request_events[stream_id] = deque() self._request_waiter[stream_id] = waiter + self._send_pending() - self._consume_events() return await asyncio.shield(waiter)
examples.interop/http3_request
Modified
aiortc~aioquic
7c90328291236be416840786ab1270f00d31a8b0
[interop] adjust for QuicConnectionProtocol changes
<3>:<add> http = H3Connection(connection._quic) <del> http = H3Connection(connection._connection)
# module: examples.interop def http3_request(connection, authority, path): <0> reader, writer = await connection.create_stream() <1> stream_id = writer.get_extra_info("stream_id") <2> <3> http = H3Connection(connection._connection) <4> http.send_headers( <5> stream_id=stream_id, <6> headers=[ <7> (b":method", b"GET"), <8> (b":scheme", b"https"), <9> (b":authority", authority.encode("utf8")), <10> (b":path", path.encode("utf8")), <11> ], <12> ) <13> http.send_data(stream_id=stream_id, data=b"", end_stream=True) <14> <15> return await reader.read() <16>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol create_stream(is_unidirectional: bool=False) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter] at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._quic = quic at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers) -> None at: asyncio.streams.StreamReader _source_traceback = None read(n: int=...) -> bytes at: asyncio.streams.StreamWriter get_extra_info(name: str, default: Any=...) -> Any ===========changed ref 0=========== # module: examples.interop @dataclass class Config: name: str host: str + port: int = 4433 - port: int + retry_port: Optional[int] = 4434 - retry_port: Optional[int] + path: str = "/" - path: str result: Result = field(default_factory=lambda: Result(0)) ===========changed ref 1=========== # module: examples.interop CONFIGS = [ + Config("aioquic", "quic.aiortc.org"), - Config("aioquic", "quic.aiortc.org", 4433, 4434, "/"), + Config("ats", "quic.ogre.com"), - Config("ats", "quic.ogre.com", 4433, 4434, "/"), + Config("f5", "f5quic.com", retry_port=4433), - Config("f5", "f5quic.com", 4433, 4433, "/"), + Config("gquic", "quic.rocks", retry_port=None), - Config("gquic", "quic.rocks", 4433, 4433, "/"), + Config("lsquic", "http3-test.litespeedtech.com"), - Config("lsquic", "http3-test.litespeedtech.com", 4433, 4434, None), + Config("mvfst", "fb.mvfst.net"), - Config("mvfst", "fb.mvfst.net", 4433, 4434, "/"), + Config("ngtcp2", "nghttp2.org"), - Config("ngtcp2", "nghttp2.org", 4433, 4434, "/"), + Config("ngx_quic", "cloudflare-quic.com", port=443, retry_port=443), - Config("ngx_quic", "cloudflare-quic.com", 443, 443, None), + Config("pandora", "pandora.cm.in.tum.de"), - Config("pandora", "pandora.cm.in.tum.de", 4433, 4434, "/"), + Config("picoquic", "test.privateoctopus.com"), - Config("picoquic", "test.privateoctopus.com", 4433, 4434, "/"), + Config("quant", "quant.eggert.</s> ===========changed ref 2=========== # module: examples.interop # offset: 1 <s>.privateoctopus.com", 4433, 4434, "/"), + Config("quant", "quant.eggert.org"), - Config("quant", "quant.eggert.org", 4433, 4434, "/"), + Config("quic-go", "quic.seemann.io", port=443, retry_port=443), - Config("quic-go", "quic.seemann.io", 443, 443, "/"), + Config("quiche", "quic.tech", retry_port=4433), - Config("quiche", "quic.tech", 4433, 4433, "/"), + Config("quicker", "quicker.edm.uhasselt.be", retry_port=None), - Config("quicker", "quicker.edm.uhasselt.be", 4433, None, "/"), + Config("quicly", "kazuhooku.com"), - Config("quicly", "kazuhooku.com", 4433, 4434, "/"), + Config("quinn", "ralith.com"), - Config("quinn", "ralith.com", 4433, 4434, "/"), + Config("winquic", "quic.westus.cloudapp.azure.com"), - Config("winquic", "quic.westus.cloudapp.azure.com", 4433, 4434, "/"), ]
examples.interop/test_version_negotiation
Modified
aiortc~aioquic
7c90328291236be416840786ab1270f00d31a8b0
[interop] adjust for QuicConnectionProtocol changes
<4>:<add> if connection._quic._version_negotiation_count == 1: <del> if connection._connection._version_negotiation_count == 1:
# module: examples.interop def test_version_negotiation(config, **kwargs): <0> async with connect( <1> config.host, config.port, protocol_version=0x1A2A3A4A, **kwargs <2> ) as connection: <3> await connection.ping() <4> if connection._connection._version_negotiation_count == 1: <5> config.result |= Result.V <6>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(*args, **kwds) connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] at: aioquic.asyncio.protocol.QuicConnectionProtocol ping() -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._quic = quic at: aioquic.quic.connection.QuicConnection.__init__ self._version_negotiation_count = 0 at: aioquic.quic.connection.QuicConnection.receive_datagram self._version_negotiation_count += 1 at: examples.interop Result() ===========changed ref 0=========== # module: examples.interop @dataclass class Config: name: str host: str + port: int = 4433 - port: int + retry_port: Optional[int] = 4434 - retry_port: Optional[int] + path: str = "/" - path: str result: Result = field(default_factory=lambda: Result(0)) ===========changed ref 1=========== # module: examples.interop def http3_request(connection, authority, path): reader, writer = await connection.create_stream() stream_id = writer.get_extra_info("stream_id") + http = H3Connection(connection._quic) - http = H3Connection(connection._connection) http.send_headers( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", authority.encode("utf8")), (b":path", path.encode("utf8")), ], ) http.send_data(stream_id=stream_id, data=b"", end_stream=True) return await reader.read() ===========changed ref 2=========== # module: examples.interop CONFIGS = [ + Config("aioquic", "quic.aiortc.org"), - Config("aioquic", "quic.aiortc.org", 4433, 4434, "/"), + Config("ats", "quic.ogre.com"), - Config("ats", "quic.ogre.com", 4433, 4434, "/"), + Config("f5", "f5quic.com", retry_port=4433), - Config("f5", "f5quic.com", 4433, 4433, "/"), + Config("gquic", "quic.rocks", retry_port=None), - Config("gquic", "quic.rocks", 4433, 4433, "/"), + Config("lsquic", "http3-test.litespeedtech.com"), - Config("lsquic", "http3-test.litespeedtech.com", 4433, 4434, None), + Config("mvfst", "fb.mvfst.net"), - Config("mvfst", "fb.mvfst.net", 4433, 4434, "/"), + Config("ngtcp2", "nghttp2.org"), - Config("ngtcp2", "nghttp2.org", 4433, 4434, "/"), + Config("ngx_quic", "cloudflare-quic.com", port=443, retry_port=443), - Config("ngx_quic", "cloudflare-quic.com", 443, 443, None), + Config("pandora", "pandora.cm.in.tum.de"), - Config("pandora", "pandora.cm.in.tum.de", 4433, 4434, "/"), + Config("picoquic", "test.privateoctopus.com"), - Config("picoquic", "test.privateoctopus.com", 4433, 4434, "/"), + Config("quant", "quant.eggert.</s> ===========changed ref 3=========== # module: examples.interop # offset: 1 <s>.privateoctopus.com", 4433, 4434, "/"), + Config("quant", "quant.eggert.org"), - Config("quant", "quant.eggert.org", 4433, 4434, "/"), + Config("quic-go", "quic.seemann.io", port=443, retry_port=443), - Config("quic-go", "quic.seemann.io", 443, 443, "/"), + Config("quiche", "quic.tech", retry_port=4433), - Config("quiche", "quic.tech", 4433, 4433, "/"), + Config("quicker", "quicker.edm.uhasselt.be", retry_port=None), - Config("quicker", "quicker.edm.uhasselt.be", 4433, None, "/"), + Config("quicly", "kazuhooku.com"), - Config("quicly", "kazuhooku.com", 4433, 4434, "/"), + Config("quinn", "ralith.com"), - Config("quinn", "ralith.com", 4433, 4434, "/"), + Config("winquic", "quic.westus.cloudapp.azure.com"), - Config("winquic", "quic.westus.cloudapp.azure.com", 4433, 4434, "/"), ]
examples.interop/test_stateless_retry
Modified
aiortc~aioquic
7c90328291236be416840786ab1270f00d31a8b0
[interop] adjust for QuicConnectionProtocol changes
<2>:<add> if connection._quic._stateless_retry_count == 1: <del> if connection._connection._stateless_retry_count == 1:
# module: examples.interop def test_stateless_retry(config, **kwargs): <0> async with connect(config.host, config.retry_port, **kwargs) as connection: <1> await connection.ping() <2> if connection._connection._stateless_retry_count == 1: <3> config.result |= Result.S <4>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(*args, **kwds) connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] at: aioquic.asyncio.protocol.QuicConnectionProtocol ping() -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._quic = quic at: aioquic.quic.connection.QuicConnection.__init__ self._stateless_retry_count = 0 at: aioquic.quic.connection.QuicConnection.receive_datagram self._stateless_retry_count += 1 at: examples.interop Result() ===========changed ref 0=========== # module: examples.interop def test_version_negotiation(config, **kwargs): async with connect( config.host, config.port, protocol_version=0x1A2A3A4A, **kwargs ) as connection: await connection.ping() + if connection._quic._version_negotiation_count == 1: - if connection._connection._version_negotiation_count == 1: config.result |= Result.V ===========changed ref 1=========== # module: examples.interop @dataclass class Config: name: str host: str + port: int = 4433 - port: int + retry_port: Optional[int] = 4434 - retry_port: Optional[int] + path: str = "/" - path: str result: Result = field(default_factory=lambda: Result(0)) ===========changed ref 2=========== # module: examples.interop def http3_request(connection, authority, path): reader, writer = await connection.create_stream() stream_id = writer.get_extra_info("stream_id") + http = H3Connection(connection._quic) - http = H3Connection(connection._connection) http.send_headers( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", authority.encode("utf8")), (b":path", path.encode("utf8")), ], ) http.send_data(stream_id=stream_id, data=b"", end_stream=True) return await reader.read() ===========changed ref 3=========== # module: examples.interop CONFIGS = [ + Config("aioquic", "quic.aiortc.org"), - Config("aioquic", "quic.aiortc.org", 4433, 4434, "/"), + Config("ats", "quic.ogre.com"), - Config("ats", "quic.ogre.com", 4433, 4434, "/"), + Config("f5", "f5quic.com", retry_port=4433), - Config("f5", "f5quic.com", 4433, 4433, "/"), + Config("gquic", "quic.rocks", retry_port=None), - Config("gquic", "quic.rocks", 4433, 4433, "/"), + Config("lsquic", "http3-test.litespeedtech.com"), - Config("lsquic", "http3-test.litespeedtech.com", 4433, 4434, None), + Config("mvfst", "fb.mvfst.net"), - Config("mvfst", "fb.mvfst.net", 4433, 4434, "/"), + Config("ngtcp2", "nghttp2.org"), - Config("ngtcp2", "nghttp2.org", 4433, 4434, "/"), + Config("ngx_quic", "cloudflare-quic.com", port=443, retry_port=443), - Config("ngx_quic", "cloudflare-quic.com", 443, 443, None), + Config("pandora", "pandora.cm.in.tum.de"), - Config("pandora", "pandora.cm.in.tum.de", 4433, 4434, "/"), + Config("picoquic", "test.privateoctopus.com"), - Config("picoquic", "test.privateoctopus.com", 4433, 4434, "/"), + Config("quant", "quant.eggert.</s> ===========changed ref 4=========== # module: examples.interop # offset: 1 <s>.privateoctopus.com", 4433, 4434, "/"), + Config("quant", "quant.eggert.org"), - Config("quant", "quant.eggert.org", 4433, 4434, "/"), + Config("quic-go", "quic.seemann.io", port=443, retry_port=443), - Config("quic-go", "quic.seemann.io", 443, 443, "/"), + Config("quiche", "quic.tech", retry_port=4433), - Config("quiche", "quic.tech", 4433, 4433, "/"), + Config("quicker", "quicker.edm.uhasselt.be", retry_port=None), - Config("quicker", "quicker.edm.uhasselt.be", 4433, None, "/"), + Config("quicly", "kazuhooku.com"), - Config("quicly", "kazuhooku.com", 4433, 4434, "/"), + Config("quinn", "ralith.com"), - Config("quinn", "ralith.com", 4433, 4434, "/"), + Config("winquic", "quic.westus.cloudapp.azure.com"), - Config("winquic", "quic.westus.cloudapp.azure.com", 4433, 4434, "/"), ]
examples.interop/test_session_resumption
Modified
aiortc~aioquic
7c90328291236be416840786ab1270f00d31a8b0
[interop] adjust for QuicConnectionProtocol changes
<23>:<add> if connection._quic.tls.session_resumed: <del> if connection._connection.tls.session_resumed: <27>:<add> if connection._quic.tls.early_data_accepted: <del> if connection._connection.tls.early_data_accepted:
# module: examples.interop def test_session_resumption(config, **kwargs): <0> saved_ticket = None <1> <2> def session_ticket_handler(ticket): <3> nonlocal saved_ticket <4> saved_ticket = ticket <5> <6> # connect a first time, receive a ticket <7> async with connect( <8> config.host, <9> config.port, <10> session_ticket_handler=session_ticket_handler, <11> **kwargs <12> ) as connection: <13> await connection.ping() <14> <15> # connect a second time, with the ticket <16> if saved_ticket is not None: <17> async with connect( <18> config.host, config.port, session_ticket=saved_ticket, **kwargs <19> ) as connection: <20> await connection.ping() <21> <22> # check session was resumed <23> if connection._connection.tls.session_resumed: <24> config.result |= Result.R <25> <26> # check early data was accepted <27> if connection._connection.tls.early_data_accepted: <28> config.result |= Result.Z <29>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(*args, **kwds) connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] at: aioquic.asyncio.protocol.QuicConnectionProtocol ping() -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._quic = quic at: aioquic.quic.connection.QuicConnection._initialize self.tls = tls.Context(is_client=self._is_client, logger=self._logger) at: aioquic.tls.Context.__init__ self.early_data_accepted = False at: aioquic.tls.Context._client_handle_encrypted_extensions self.early_data_accepted = encrypted_extensions.early_data at: aioquic.tls.Context._server_handle_hello self.early_data_accepted = True at: examples.interop Result() ===========changed ref 0=========== # module: examples.interop def test_stateless_retry(config, **kwargs): async with connect(config.host, config.retry_port, **kwargs) as connection: await connection.ping() + if connection._quic._stateless_retry_count == 1: - if connection._connection._stateless_retry_count == 1: config.result |= Result.S ===========changed ref 1=========== # module: examples.interop def test_version_negotiation(config, **kwargs): async with connect( config.host, config.port, protocol_version=0x1A2A3A4A, **kwargs ) as connection: await connection.ping() + if connection._quic._version_negotiation_count == 1: - if connection._connection._version_negotiation_count == 1: config.result |= Result.V ===========changed ref 2=========== # module: examples.interop @dataclass class Config: name: str host: str + port: int = 4433 - port: int + retry_port: Optional[int] = 4434 - retry_port: Optional[int] + path: str = "/" - path: str result: Result = field(default_factory=lambda: Result(0)) ===========changed ref 3=========== # module: examples.interop def http3_request(connection, authority, path): reader, writer = await connection.create_stream() stream_id = writer.get_extra_info("stream_id") + http = H3Connection(connection._quic) - http = H3Connection(connection._connection) http.send_headers( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", authority.encode("utf8")), (b":path", path.encode("utf8")), ], ) http.send_data(stream_id=stream_id, data=b"", end_stream=True) return await reader.read() ===========changed ref 4=========== # module: examples.interop CONFIGS = [ + Config("aioquic", "quic.aiortc.org"), - Config("aioquic", "quic.aiortc.org", 4433, 4434, "/"), + Config("ats", "quic.ogre.com"), - Config("ats", "quic.ogre.com", 4433, 4434, "/"), + Config("f5", "f5quic.com", retry_port=4433), - Config("f5", "f5quic.com", 4433, 4433, "/"), + Config("gquic", "quic.rocks", retry_port=None), - Config("gquic", "quic.rocks", 4433, 4433, "/"), + Config("lsquic", "http3-test.litespeedtech.com"), - Config("lsquic", "http3-test.litespeedtech.com", 4433, 4434, None), + Config("mvfst", "fb.mvfst.net"), - Config("mvfst", "fb.mvfst.net", 4433, 4434, "/"), + Config("ngtcp2", "nghttp2.org"), - Config("ngtcp2", "nghttp2.org", 4433, 4434, "/"), + Config("ngx_quic", "cloudflare-quic.com", port=443, retry_port=443), - Config("ngx_quic", "cloudflare-quic.com", 443, 443, None), + Config("pandora", "pandora.cm.in.tum.de"), - Config("pandora", "pandora.cm.in.tum.de", 4433, 4434, "/"), + Config("picoquic", "test.privateoctopus.com"), - Config("picoquic", "test.privateoctopus.com", 4433, 4434, "/"), + Config("quant", "quant.eggert.</s> ===========changed ref 5=========== # module: examples.interop # offset: 1 <s>.privateoctopus.com", 4433, 4434, "/"), + Config("quant", "quant.eggert.org"), - Config("quant", "quant.eggert.org", 4433, 4434, "/"), + Config("quic-go", "quic.seemann.io", port=443, retry_port=443), - Config("quic-go", "quic.seemann.io", 443, 443, "/"), + Config("quiche", "quic.tech", retry_port=4433), - Config("quiche", "quic.tech", 4433, 4433, "/"), + Config("quicker", "quicker.edm.uhasselt.be", retry_port=None), - Config("quicker", "quicker.edm.uhasselt.be", 4433, None, "/"), + Config("quicly", "kazuhooku.com"), - Config("quicly", "kazuhooku.com", 4433, 4434, "/"), + Config("quinn", "ralith.com"), - Config("quinn", "ralith.com", 4433, 4434, "/"), + Config("winquic", "quic.westus.cloudapp.azure.com"), - Config("winquic", "quic.westus.cloudapp.azure.com", 4433, 4434, "/"), ]
examples.interop/test_spin_bit
Modified
aiortc~aioquic
7c90328291236be416840786ab1270f00d31a8b0
[interop] adjust for QuicConnectionProtocol changes
<4>:<add> spin_bits.add(connection._quic._spin_bit_peer) <del> spin_bits.add(connection._connection._spin_bit_peer)
# module: examples.interop def test_spin_bit(config, **kwargs): <0> async with connect(config.host, config.port, **kwargs) as connection: <1> spin_bits = set() <2> for i in range(5): <3> await connection.ping() <4> spin_bits.add(connection._connection._spin_bit_peer) <5> if len(spin_bits) == 2: <6> config.result |= Result.P <7>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(*args, **kwds) connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] at: aioquic.asyncio.protocol.QuicConnectionProtocol ping() -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._quic = quic at: aioquic.quic.connection.QuicConnection.__init__ self._spin_bit_peer = False at: aioquic.quic.connection.QuicConnection.receive_datagram self._spin_bit_peer = get_spin_bit(plain_header[0]) at: examples.interop Result() ===========changed ref 0=========== # module: examples.interop def test_stateless_retry(config, **kwargs): async with connect(config.host, config.retry_port, **kwargs) as connection: await connection.ping() + if connection._quic._stateless_retry_count == 1: - if connection._connection._stateless_retry_count == 1: config.result |= Result.S ===========changed ref 1=========== # module: examples.interop def test_version_negotiation(config, **kwargs): async with connect( config.host, config.port, protocol_version=0x1A2A3A4A, **kwargs ) as connection: await connection.ping() + if connection._quic._version_negotiation_count == 1: - if connection._connection._version_negotiation_count == 1: config.result |= Result.V ===========changed ref 2=========== # module: examples.interop @dataclass class Config: name: str host: str + port: int = 4433 - port: int + retry_port: Optional[int] = 4434 - retry_port: Optional[int] + path: str = "/" - path: str result: Result = field(default_factory=lambda: Result(0)) ===========changed ref 3=========== # module: examples.interop def http3_request(connection, authority, path): reader, writer = await connection.create_stream() stream_id = writer.get_extra_info("stream_id") + http = H3Connection(connection._quic) - http = H3Connection(connection._connection) http.send_headers( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", authority.encode("utf8")), (b":path", path.encode("utf8")), ], ) http.send_data(stream_id=stream_id, data=b"", end_stream=True) return await reader.read() ===========changed ref 4=========== # module: examples.interop def test_session_resumption(config, **kwargs): saved_ticket = None def session_ticket_handler(ticket): nonlocal saved_ticket saved_ticket = ticket # connect a first time, receive a ticket async with connect( config.host, config.port, session_ticket_handler=session_ticket_handler, **kwargs ) as connection: await connection.ping() # connect a second time, with the ticket if saved_ticket is not None: async with connect( config.host, config.port, session_ticket=saved_ticket, **kwargs ) as connection: await connection.ping() # check session was resumed + if connection._quic.tls.session_resumed: - if connection._connection.tls.session_resumed: config.result |= Result.R # check early data was accepted + if connection._quic.tls.early_data_accepted: - if connection._connection.tls.early_data_accepted: config.result |= Result.Z ===========changed ref 5=========== # module: examples.interop CONFIGS = [ + Config("aioquic", "quic.aiortc.org"), - Config("aioquic", "quic.aiortc.org", 4433, 4434, "/"), + Config("ats", "quic.ogre.com"), - Config("ats", "quic.ogre.com", 4433, 4434, "/"), + Config("f5", "f5quic.com", retry_port=4433), - Config("f5", "f5quic.com", 4433, 4433, "/"), + Config("gquic", "quic.rocks", retry_port=None), - Config("gquic", "quic.rocks", 4433, 4433, "/"), + Config("lsquic", "http3-test.litespeedtech.com"), - Config("lsquic", "http3-test.litespeedtech.com", 4433, 4434, None), + Config("mvfst", "fb.mvfst.net"), - Config("mvfst", "fb.mvfst.net", 4433, 4434, "/"), + Config("ngtcp2", "nghttp2.org"), - Config("ngtcp2", "nghttp2.org", 4433, 4434, "/"), + Config("ngx_quic", "cloudflare-quic.com", port=443, retry_port=443), - Config("ngx_quic", "cloudflare-quic.com", 443, 443, None), + Config("pandora", "pandora.cm.in.tum.de"), - Config("pandora", "pandora.cm.in.tum.de", 4433, 4434, "/"), + Config("picoquic", "test.privateoctopus.com"), - Config("picoquic", "test.privateoctopus.com", 4433, 4434, "/"), + Config("quant", "quant.eggert.</s> ===========changed ref 6=========== # module: examples.interop # offset: 1 <s>.privateoctopus.com", 4433, 4434, "/"), + Config("quant", "quant.eggert.org"), - Config("quant", "quant.eggert.org", 4433, 4434, "/"), + Config("quic-go", "quic.seemann.io", port=443, retry_port=443), - Config("quic-go", "quic.seemann.io", 443, 443, "/"), + Config("quiche", "quic.tech", retry_port=4433), - Config("quiche", "quic.tech", 4433, 4433, "/"), + Config("quicker", "quicker.edm.uhasselt.be", retry_port=None), - Config("quicker", "quicker.edm.uhasselt.be", 4433, None, "/"), + Config("quicly", "kazuhooku.com"), - Config("quicly", "kazuhooku.com", 4433, 4434, "/"), + Config("quinn", "ralith.com"), - Config("quinn", "ralith.com", 4433, 4434, "/"), + Config("winquic", "quic.westus.cloudapp.azure.com"), - Config("winquic", "quic.westus.cloudapp.azure.com", 4433, 4434, "/"), ]
aioquic.asyncio.client/connect
Modified
aiortc~aioquic
d886b91aee032a7447e7d50a6e8b6171fd0cac9d
[tests] run packet loss tests with QLOG enabled
<s>List[str]] = None, idle_timeout: Optional[float] = None, protocol_version: Optional[int] = None, + quic_logger: Optional[QuicLogger] = None, secrets_log_file: Optional[TextIO] = None, session_ticket: Optional[SessionTicket] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> AsyncGenerator[QuicConnectionProtocol, None]: <0> """ <1> Connect to a QUIC server at the given `host` and `port`. <2> <3> :meth:`connect()` returns an awaitable. Awaiting it yields a <4> :class:`~aioquic.asyncio.QuicConnectionProtocol` which can be used to <5> create streams. <6> <7> :func:`connect` also accepts the following optional arguments: <8> <9> * ``alpn_protocols`` is a list of ALPN protocols to offer in the <10> ClientHello. <11> * ``secrets_log_file`` is a file-like object in which to log traffic <12> secrets. This is useful to analyze traffic captures with Wireshark. <13> * ``session_ticket`` is a TLS session ticket which should be used for <14> resumption. <15> * ``session_ticket_handler`` is a callback which is invoked by the TLS <16> engine when a new session ticket is received. <17> * ``stream_handler`` is a callback which is invoked whenever a stream is <18> created. It must accept two arguments: a :class:`asyncio.StreamReader` <19> and a :class:`asyncio.StreamWriter`. <20> """ <21> loop = asyncio.get_event_loop() <22> <23> # if host is not an IP address, pass it to enable SNI <24> try: <25> ipaddress.ip_address(host) <26> server_name = None <27> except ValueError: <28> server_name = host <29> <30> # lookup remote address <31> infos = await loop.getaddrinfo(host, port, type=socket.SOCK_DGRAM) <32> addr</s>
===========below chunk 0=========== <s> None, idle_timeout: Optional[float] = None, protocol_version: Optional[int] = None, + quic_logger: Optional[QuicLogger] = None, secrets_log_file: Optional[TextIO] = None, session_ticket: Optional[SessionTicket] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> AsyncGenerator[QuicConnectionProtocol, None]: # offset: 1 if len(addr) == 2: addr = ("::ffff:" + addr[0], addr[1], 0, 0) configuration = QuicConfiguration( alpn_protocols=alpn_protocols, is_client=True, secrets_log_file=secrets_log_file, server_name=server_name, session_ticket=session_ticket, ) if idle_timeout is not None: configuration.idle_timeout = idle_timeout connection = QuicConnection( configuration=configuration, session_ticket_handler=session_ticket_handler ) # connect _, protocol = await loop.create_datagram_endpoint( lambda: QuicConnectionProtocol(connection, stream_handler=stream_handler), local_addr=("::", 0), ) protocol = cast(QuicConnectionProtocol, protocol) protocol.connect(addr, protocol_version) await protocol.wait_connected() try: yield protocol finally: protocol.close() await protocol.wait_closed() ===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.asyncio.compat asynccontextmanager = _asynccontextmanager asynccontextmanager = None at: aioquic.asyncio.protocol QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None] QuicConnectionProtocol(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.asyncio.protocol.QuicConnectionProtocol connect(addr: NetworkAddress, protocol_version: int) -> None wait_connected() -> None at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) ===========unchanged ref 1=========== at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.quic.logger QuicLogger() at: aioquic.tls SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) SessionTicketHandler = Callable[[SessionTicket], None] at: asyncio.events get_event_loop() -> AbstractEventLoop at: asyncio.events.AbstractEventLoop getaddrinfo(host: Optional[str], port: Union[str, int, None], *, family: int=..., type: int=..., proto: int=..., flags: int=...) -> List[Tuple[AddressFamily, SocketKind, int, str, Union[Tuple[str, int], Tuple[str, int, int, int]]]] create_datagram_endpoint(protocol_factory: _ProtocolFactory, local_addr: Optional[Tuple[str, int]]=..., remote_addr: Optional[Tuple[str, int]]=..., *, family: int=..., proto: int=..., flags: int=..., reuse_address: Optional[bool]=..., reuse_port: Optional[bool]=..., allow_broadcast: Optional[bool]=..., sock: Optional[socket]=...) -> _TransProtPair at: contextlib asynccontextmanager(func: Callable[..., AsyncIterator[_T]]) -> Callable[..., AsyncContextManager[_T]] at: ipaddress ip_address(address: object) -> Any at: socket SOCK_DGRAM: SocketKind ===========unchanged ref 2=========== at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any List = _alias(list, 1, inst=False, name='List') AsyncGenerator = _alias(collections.abc.AsyncGenerator, 2) TextIO()
aioquic.asyncio.server/serve
Modified
aiortc~aioquic
d886b91aee032a7447e7d50a6e8b6171fd0cac9d
[tests] run packet loss tests with QLOG enabled
<s> alpn_protocols: Optional[List[str]] = None, idle_timeout: Optional[float] = None, + quic_logger: Optional[QuicLogger] = None, stream_handler: QuicStreamHandler = None, secrets_log_file: Optional[TextIO] = None, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, ) -> QuicServer: <0> """ <1> Start a QUIC server at the given `host` and `port`. <2> <3> :func:`serve` requires a TLS certificate and private key, which can be <4> specified using the following arguments: <5> <6> * ``certificate`` is the server's TLS certificate. <7> See :func:`cryptography.x509.load_pem_x509_certificate`. <8> * ``private_key`` is the server's private key. <9> See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. <10> <11> :func:`serve` also accepts the following optional arguments: <12> <13> * ``secrets_log_file`` is a file-like object in which to log traffic <14> secrets. This is useful to analyze traffic captures with Wireshark. <15> * ``session_ticket_fetcher`` is a callback which is invoked by the TLS <16> engine when a session ticket is presented by the peer. It should return <17> the session ticket with the specified ID or `None` if it is not found. <18> * ``session_ticket_handler`` is a callback which is invoked by the TLS <19> engine when a new session ticket is issued. It should store the session <20> ticket for future lookup. <21> * ``stateless_retry`` specifies whether a stateless retry should be <22> performed prior to handling new connections. <23> * ``stream_handler`` is a callback which is invoked whenever a stream is <24> created. It must accept two arguments: a :class:`asyncio.StreamReader` <25> and a :class:`asyncio.StreamWriter`. <26> """ <27> </s>
===========below chunk 0=========== <s> Optional[List[str]] = None, idle_timeout: Optional[float] = None, + quic_logger: Optional[QuicLogger] = None, stream_handler: QuicStreamHandler = None, secrets_log_file: Optional[TextIO] = None, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, ) -> QuicServer: # offset: 1 configuration = QuicConfiguration( alpn_protocols=alpn_protocols, certificate=certificate, is_client=False, private_key=private_key, secrets_log_file=secrets_log_file, ) if idle_timeout is not None: configuration.idle_timeout = idle_timeout _, protocol = await loop.create_datagram_endpoint( lambda: QuicServer( configuration=configuration, session_ticket_fetcher=session_ticket_fetcher, session_ticket_handler=session_ticket_handler, stateless_retry=stateless_retry, stream_handler=stream_handler, ), local_addr=(host, port), ) return cast(QuicServer, protocol) ===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.asyncio.protocol QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None] at: aioquic.asyncio.server QuicServer(*, configuration: QuicConfiguration, session_ticket_fetcher: Optional[SessionTicketFetcher]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stateless_retry: bool=False, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.quic.logger QuicLogger() at: aioquic.tls SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] at: asyncio.events get_event_loop() -> AbstractEventLoop ===========unchanged ref 1=========== at: asyncio.events.AbstractEventLoop create_datagram_endpoint(protocol_factory: _ProtocolFactory, local_addr: Optional[Tuple[str, int]]=..., remote_addr: Optional[Tuple[str, int]]=..., *, family: int=..., proto: int=..., flags: int=..., reuse_address: Optional[bool]=..., reuse_port: Optional[bool]=..., allow_broadcast: Optional[bool]=..., sock: Optional[socket]=...) -> _TransProtPair at: typing List = _alias(list, 1, inst=False, name='List') TextIO() ===========changed ref 0=========== <s>List[str]] = None, idle_timeout: Optional[float] = None, protocol_version: Optional[int] = None, + quic_logger: Optional[QuicLogger] = None, secrets_log_file: Optional[TextIO] = None, session_ticket: Optional[SessionTicket] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> AsyncGenerator[QuicConnectionProtocol, None]: """ Connect to a QUIC server at the given `host` and `port`. :meth:`connect()` returns an awaitable. Awaiting it yields a :class:`~aioquic.asyncio.QuicConnectionProtocol` which can be used to create streams. :func:`connect` also accepts the following optional arguments: * ``alpn_protocols`` is a list of ALPN protocols to offer in the ClientHello. * ``secrets_log_file`` is a file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. * ``session_ticket`` is a TLS session ticket which should be used for resumption. * ``session_ticket_handler`` is a callback which is invoked by the TLS engine when a new session ticket is received. * ``stream_handler`` is a callback which is invoked whenever a stream is created. It must accept two arguments: a :class:`asyncio.StreamReader` and a :class:`asyncio.StreamWriter`. """ loop = asyncio.get_event_loop() # if host is not an IP address, pass it to enable SNI try: ipaddress.ip_address(host) server_name = None except ValueError: server_name = host # lookup remote address infos = await loop.getaddrinfo(host, port, type=socket.SOCK_DGRAM) addr = infos[0][4] if len(addr) == 2: addr = ("::ffff:" + addr[0], addr[1</s> ===========changed ref 1=========== <s> None, idle_timeout: Optional[float] = None, protocol_version: Optional[int] = None, + quic_logger: Optional[QuicLogger] = None, secrets_log_file: Optional[TextIO] = None, session_ticket: Optional[SessionTicket] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, ) -> AsyncGenerator[QuicConnectionProtocol, None]: # offset: 1 <s>0][4] if len(addr) == 2: addr = ("::ffff:" + addr[0], addr[1], 0, 0) configuration = QuicConfiguration( alpn_protocols=alpn_protocols, is_client=True, + quic_logger=quic_logger, secrets_log_file=secrets_log_file, server_name=server_name, session_ticket=session_ticket, ) if idle_timeout is not None: configuration.idle_timeout = idle_timeout connection = QuicConnection( configuration=configuration, session_ticket_handler=session_ticket_handler ) # connect _, protocol = await loop.create_datagram_endpoint( lambda: QuicConnectionProtocol(connection, stream_handler=stream_handler), local_addr=("::", 0), ) protocol = cast(QuicConnectionProtocol, protocol) protocol.connect(addr, protocol_version) await protocol.wait_connected() try: yield protocol finally: protocol.close() await protocol.wait_closed()
tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_packet_loss
Modified
aiortc~aioquic
d886b91aee032a7447e7d50a6e8b6171fd0cac9d
[tests] run packet loss tests with QLOG enabled
<7>:<add> run_server( <add> idle_timeout=300.0, quic_logger=QuicLogger(), stateless_retry=True <add> ), <add> run_client( <add> "127.0.0.1", <add> idle_timeout=300.0, <add> quic_logger=QuicLogger(), <add> request=data, <add> ), <del> run_server(idle_timeout=300.0, stateless_retry=True), <8>:<del> run_client("127.0.0.1", idle_timeout=300.0, request=data),
# module: tests.test_asyncio class HighLevelTest(TestCase): @patch("socket.socket.sendto", new_callable=lambda: sendto_with_loss) def test_connect_and_serve_with_packet_loss(self, mock_sendto): <0> """ <1> This test ensures handshake success and stream data is successfully sent <2> and received in the presence of packet loss (randomized 25% in each direction). <3> """ <4> data = b"Z" * 65536 <5> server, response = run( <6> asyncio.gather( <7> run_server(idle_timeout=300.0, stateless_retry=True), <8> run_client("127.0.0.1", idle_timeout=300.0, request=data), <9> ) <10> ) <11> self.assertEqual(response, data) <12> server.close() <13>
===========unchanged ref 0=========== at: aioquic.quic.logger QuicLogger() ===========unchanged ref 1=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 2=========== at: tests.test_asyncio sendto_with_loss(self, data, addr=None) run_client(host, port=4433, request=b"ping", *, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None) at: tests.utils run(coro) at: unittest.mock _patcher(target: Any, new: _T, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[_T] _patcher(target: Any, *, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[Union[MagicMock, AsyncMock]] ===========changed ref 0=========== <s> alpn_protocols: Optional[List[str]] = None, idle_timeout: Optional[float] = None, + quic_logger: Optional[QuicLogger] = None, stream_handler: QuicStreamHandler = None, secrets_log_file: Optional[TextIO] = None, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, ) -> QuicServer: """ Start a QUIC server at the given `host` and `port`. :func:`serve` requires a TLS certificate and private key, which can be specified using the following arguments: * ``certificate`` is the server's TLS certificate. See :func:`cryptography.x509.load_pem_x509_certificate`. * ``private_key`` is the server's private key. See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. :func:`serve` also accepts the following optional arguments: * ``secrets_log_file`` is a file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. * ``session_ticket_fetcher`` is a callback which is invoked by the TLS engine when a session ticket is presented by the peer. It should return the session ticket with the specified ID or `None` if it is not found. * ``session_ticket_handler`` is a callback which is invoked by the TLS engine when a new session ticket is issued. It should store the session ticket for future lookup. * ``stateless_retry`` specifies whether a stateless retry should be performed prior to handling new connections. * ``stream_handler`` is a callback which is invoked whenever a stream is created. It must accept two arguments: a :class:`asyncio.StreamReader` and a :class:`asyncio.StreamWriter`. """ loop = asyncio.get_event_loop() configuration = QuicConfiguration( alpn_protocols=</s> ===========changed ref 1=========== <s> Optional[List[str]] = None, idle_timeout: Optional[float] = None, + quic_logger: Optional[QuicLogger] = None, stream_handler: QuicStreamHandler = None, secrets_log_file: Optional[TextIO] = None, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, ) -> QuicServer: # offset: 1 <s> """ loop = asyncio.get_event_loop() configuration = QuicConfiguration( alpn_protocols=alpn_protocols, certificate=certificate, is_client=False, private_key=private_key, + quic_logger=quic_logger, secrets_log_file=secrets_log_file, ) if idle_timeout is not None: configuration.idle_timeout = idle_timeout _, protocol = await loop.create_datagram_endpoint( lambda: QuicServer( configuration=configuration, session_ticket_fetcher=session_ticket_fetcher, session_ticket_handler=session_ticket_handler, stateless_retry=stateless_retry, stream_handler=stream_handler, ), local_addr=(host, port), ) return cast(QuicServer, protocol)
tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_version_negotiation
Modified
aiortc~aioquic
2a0c0dd4756a9b3b01c5e037f86a99408b090f1b
[tests] run stateless retry test with QLOG enabled
<2>:<add> run_server(), <add> run_client( <add> "127.0.0.1", protocol_version=0x1A2A3A4A, quic_logger=QuicLogger() <add> ), <del> run_server(), run_client("127.0.0.1", protocol_version=0x1A2A3A4A)
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_version_negotiation(self): <0> server, response = run( <1> asyncio.gather( <2> run_server(), run_client("127.0.0.1", protocol_version=0x1A2A3A4A) <3> ) <4> ) <5> self.assertEqual(response, b"gnip") <6> server.close() <7>
===========unchanged ref 0=========== at: aioquic.quic.logger QuicLogger() ===========unchanged ref 1=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 2=========== at: tests.test_asyncio run_client(host, port=4433, request=b"ping", *, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None) at: tests.utils run(coro)
tests.test_connection/client_and_server
Modified
aiortc~aioquic
674b9447b61037c38e9ff88621465c85e6fc79bc
[tests] add simple test for 0-RTT
<1>:<add> configuration=QuicConfiguration(is_client=True, **client_options), <del> configuration=QuicConfiguration(is_client=True, **client_options) <2>:<add> **client_kwargs <12>:<add> ), <del> ) <13>:<add> **server_kwargs <18>:<add> if handshake: <add> client.connect(SERVER_ADDR, now=time.time()) <del> client.connect(SERVER_ADDR, now=time.time()) <19>:<add> for i in range(3): <del> for i in range(3): <20>:<add> roundtrip(client, server) <del> roundtrip(client, server)
# module: tests.test_connection @contextlib.contextmanager def client_and_server( + client_kwargs={}, client_options={}, client_patch=lambda x: None, + handshake=True, + server_kwargs={}, server_options={}, server_patch=lambda x: None, transport_options={}, ): <0> client = QuicConnection( <1> configuration=QuicConfiguration(is_client=True, **client_options) <2> ) <3> client._ack_delay = 0 <4> client_patch(client) <5> <6> server = QuicConnection( <7> configuration=QuicConfiguration( <8> is_client=False, <9> certificate=SERVER_CERTIFICATE, <10> private_key=SERVER_PRIVATE_KEY, <11> **server_options <12> ) <13> ) <14> server._ack_delay = 0 <15> server_patch(server) <16> <17> # perform handshake <18> client.connect(SERVER_ADDR, now=time.time()) <19> for i in range(3): <20> roundtrip(client, server) <21> <22> yield client, server <23> <24> # close <25> client.close() <26> server.close() <27>
===========unchanged ref 0=========== at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.quic.connection.QuicConnection connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._ack_delay = K_GRANULARITY at: contextlib contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., _GeneratorContextManager[_T]] ===========unchanged ref 1=========== at: tests.test_connection SERVER_ADDR = ("2.3.4.5", 4433) drop(sender) at: tests.utils SERVER_CERTIFICATE = x509.load_pem_x509_certificate( load("ssl_cert.pem"), backend=default_backend() ) SERVER_PRIVATE_KEY = serialization.load_pem_private_key( load("ssl_key.pem"), password=None, backend=default_backend() ) at: time time() -> float at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_connection + class SessionTicketStore: + def pop(self, label): + return self.tickets.pop(label, None) + ===========changed ref 1=========== # module: tests.test_connection + class SessionTicketStore: + def __init__(self): + self.tickets = {} + ===========changed ref 2=========== # module: tests.test_connection + class SessionTicketStore: + def add(self, ticket): + self.tickets[ticket.ticket] = ticket +
tests.test_h3/FakeQuicConnection.__init__
Modified
aiortc~aioquic
1adf0202b983cb8c5231720cc8c547ba257801b4
[tests] fix FakeQuicConnection.get_next_available_stream_id
<2>:<add> self._next_stream_bidi = 0 if configuration.is_client else 1 <del> self._next_stream_bidi = 0 if configuration.is_client else 2 <3>:<add> self._next_stream_uni = 2 if configuration.is_client else 3 <del> self._next_stream_uni = 1 if configuration.is_client else 3
# module: tests.test_h3 class FakeQuicConnection: def __init__(self, configuration): <0> self.configuration = configuration <1> self.stream_queue = [] <2> self._next_stream_bidi = 0 if configuration.is_client else 2 <3> self._next_stream_uni = 1 if configuration.is_client else 3 <4>
===========unchanged ref 0=========== at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: tests.test_h3.FakeQuicConnection.get_next_available_stream_id self._next_stream_uni += 4 self._next_stream_bidi += 4
examples.http3-server/HttpServer.__init__
Modified
aiortc~aioquic
06f622b40b03dba61d8548d22a67fa272c101ec7
[http3-server] start adding support for ASGI
<0>:<add> self._application = application
# module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def __init__( self, *, + application: AsgiApplication, configuration: QuicConfiguration, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, ) -> None: <0> self._connections: Dict[bytes, QuicConnection] = {} <1> self._configuration = configuration <2> self._http: Dict[QuicConnection, HttpConnection] = {} <3> self._loop = asyncio.get_event_loop() <4> self._session_ticket_fetcher = session_ticket_fetcher <5> self._session_ticket_handler = session_ticket_handler <6> self._timer: Dict[QuicConnection, Tuple[asyncio.TimerHandle, float]] = {} <7> self._transport: Optional[asyncio.DatagramTransport] = None <8> <9> if stateless_retry: <10> self._retry = QuicRetryTokenHandler() <11> else: <12> self._retry = None <13>
===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.quic.retry QuicRetryTokenHandler() at: aioquic.tls SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] at: asyncio.events TimerHandle(when: float, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop, context: Optional[Context]=...) get_event_loop() -> AbstractEventLoop at: asyncio.transports DatagramTransport(extra: Optional[Mapping[Any, Any]]=...) at: examples.http3-server AsgiApplication = Callable HttpConnection = Union[H0Connection, H3Connection] at: examples.http3-server.HttpServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: typing Tuple = _TupleType(tuple, -1, inst=False, name='Tuple') Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: examples.http3-server try: import uvloop except ImportError: uvloop = None - ROOT = os.path.join(os.path.dirname(__file__), "htdocs") - + AsgiApplication = Callable HttpConnection = Union[H0Connection, H3Connection] ===========changed ref 1=========== + # module: examples.demo + + ===========changed ref 2=========== + # module: examples.demo + ROOT = os.path.join(os.path.dirname(__file__), "htdocs") + ===========changed ref 3=========== + # module: examples.demo + def app(scope, receive, send): + """ + Demo ASGI application for use with the http3-server.py example. + """ + assert scope["type"] == "http" + + path = scope["path"] + + # dynamically generated data, maximum 50MB + size_match = re.match(r"^/(\d+)$", path) + if size_match: + size = min(50000000, int(size_match.group(1))) + await send( + { + "type": "http.response.start", + "status": 200, + "headers": [[b"content-type", b"text/plain"]], + } + ) + await send({"type": "http.response.body", "body": b"Z" * size}) + return + + if path == "/": + path = "/index.html" + + # static files + file_match = re.match(r"^/([a-z0-9]+\.[a-z]+)$", path) + if file_match: + file_name = file_match.group(1) + file_path = os.path.join(ROOT, file_match.group(1)) + try: + with open(file_path, "rb") as fp: + await send( + { + "type": "http.response.start", + "status": 200, + "headers": [ + [ + b"content-type", + mimetypes.guess_type(file_name)[0].encode("ascii"), + ] + ], + } + ) + await send({"type": "http.response.body", "body": fp.read()}) + return + except OSError: + pass + + # not found + await send( + { + "type": "http.response.start", + "</s> ===========changed ref 4=========== + # module: examples.demo + def app(scope, receive, send): # offset: 1 <s> # not found + await send( + { + "type": "http.response.start", + "status": 404, + "headers": [[b"content-type", b"text/plain"]], + } + ) + await send({"type": "http.response.body", "body": b"Not Found"}) +
examples.http3-server/HttpServer._consume_events
Modified
aiortc~aioquic
06f622b40b03dba61d8548d22a67fa272c101ec7
[http3-server] start adding support for ASGI
<26>:<add> if isinstance(http_event, RequestReceived): <add> asyncio.ensure_future( <add> handle_http_request(self._application, http, http_event) <del> handle_http_event(http, http_event) <27>:<add> )
# module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def _consume_events(self, connection: QuicConnection) -> None: <0> # process events <1> event = connection.next_event() <2> while event is not None: <3> if isinstance(event, aioquic.quic.events.ConnectionTerminated): <4> # remove the connection <5> for cid, conn in list(self._connections.items()): <6> if conn == connection: <7> del self._connections[cid] <8> self._http.pop(connection, None) <9> self._timer.pop(connection, None) <10> return <11> elif isinstance(event, aioquic.quic.events.ProtocolNegotiated): <12> if event.alpn_protocol == "h3-22": <13> self._http[connection] = H3Connection(connection) <14> elif event.alpn_protocol == "hq-22": <15> self._http[connection] = H0Connection(connection) <16> elif isinstance(event, aioquic.quic.events.ConnectionIdIssued): <17> self._connections[event.connection_id] = connection <18> elif isinstance(event, aioquic.quic.events.ConnectionIdRetired): <19> assert self._connections[event.connection_id] == connection <20> del self._connections[event.connection_id] <21> <22> #  pass event to the HTTP layer <23> http = self._http.get(connection) <24> if http is not None: <25> for http_event in http.handle_event(event): <26> handle_http_event(http, http_event) <27> <28> event = connection.next_event() <29> <30> # send datagrams <31> for data, addr in connection.datagrams_to_send(now=self._loop.time()): <32> self._transport.sendto(data, addr) <33> <34> # re-arm timer <35> next_timer_at = connection.get_timer() <36> (timer, timer_at) = self._timer.get(connection, (None</s>
===========below chunk 0=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def _consume_events(self, connection: QuicConnection) -> None: # offset: 1 if timer is not None and timer_at != next_timer_at: timer.cancel() timer = None if timer is None and timer_at is not None: timer = self._loop.call_at( next_timer_at, partial(self._handle_timer, connection) ) self._timer[connection] = (timer, next_timer_at) ===========unchanged ref 0=========== at: aioquic.h0.connection H0Connection(quic: QuicConnection) at: aioquic.h0.connection.H0Connection handle_event(event: QuicEvent) -> List[Event] at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection handle_event(event: QuicEvent) -> List[Event] at: aioquic.h3.events RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.quic.connection.QuicConnection datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_timer() -> Optional[float] next_event() -> Optional[events.QuicEvent] at: aioquic.quic.events ConnectionIdIssued(connection_id: bytes) ConnectionIdRetired(connection_id: bytes) ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str) ProtocolNegotiated(alpn_protocol: Optional[str]) at: asyncio.events.AbstractEventLoop call_at(when: float, callback: Callable[..., Any], *args: Any) -> TimerHandle time() -> float at: asyncio.events.TimerHandle __slots__ = ['_scheduled', '_when'] cancel() -> None at: asyncio.tasks ensure_future(coro_or_future: _FutureT[_T], *, loop: Optional[AbstractEventLoop]=...) -> Future[_T] at: asyncio.transports.DatagramTransport __slots__ = () ===========unchanged ref 1=========== sendto(data: Any, addr: Optional[_Address]=...) -> None at: examples.http3-server handle_http_request(application: AsgiApplication, connection: HttpConnection, event: aioquic.h3.events.RequestReceived) -> None at: examples.http3-server.HttpServer.__init__ self._application = application self._connections: Dict[bytes, QuicConnection] = {} self._http: Dict[QuicConnection, HttpConnection] = {} self._loop = asyncio.get_event_loop() self._timer: Dict[QuicConnection, Tuple[asyncio.TimerHandle, float]] = {} self._transport: Optional[asyncio.DatagramTransport] = None at: examples.http3-server.HttpServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co] at: typing.MutableMapping pop(key: _KT) -> _VT pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T] ===========changed ref 0=========== # module: examples.http3-server try: import uvloop except ImportError: uvloop = None - ROOT = os.path.join(os.path.dirname(__file__), "htdocs") - + AsgiApplication = Callable HttpConnection = Union[H0Connection, H3Connection] ===========changed ref 1=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def __init__( self, *, + application: AsgiApplication, configuration: QuicConfiguration, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, ) -> None: + self._application = application self._connections: Dict[bytes, QuicConnection] = {} self._configuration = configuration self._http: Dict[QuicConnection, HttpConnection] = {} self._loop = asyncio.get_event_loop() self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler self._timer: Dict[QuicConnection, Tuple[asyncio.TimerHandle, float]] = {} self._transport: Optional[asyncio.DatagramTransport] = None if stateless_retry: self._retry = QuicRetryTokenHandler() else: self._retry = None ===========changed ref 2=========== + # module: examples.demo + + ===========changed ref 3=========== + # module: examples.demo + ROOT = os.path.join(os.path.dirname(__file__), "htdocs") + ===========changed ref 4=========== + # module: examples.demo + def app(scope, receive, send): + """ + Demo ASGI application for use with the http3-server.py example. + """ + assert scope["type"] == "http" + + path = scope["path"] + + # dynamically generated data, maximum 50MB + size_match = re.match(r"^/(\d+)$", path) + if size_match: + size = min(50000000, int(size_match.group(1))) + await send( + { + "type": "http.response.start", + "status": 200, + "headers": [[b"content-type", b"text/plain"]], + } + ) + await send({"type": "http.response.body", "body": b"Z" * size}) + return + + if path == "/": + path = "/index.html" + + # static files + file_match = re.match(r"^/([a-z0-9]+\.[a-z]+)$", path) + if file_match: + file_name = file_match.group(1) + file_path = os.path.join(ROOT, file_match.group(1)) + try: + with open(file_path, "rb") as fp: + await send( + { + "type": "http.response.start", + "status": 200, + "headers": [ + [ + b"content-type", + mimetypes.guess_type(file_name)[0].encode("ascii"), + ] + ], + } + ) + await send({"type": "http.response.body", "body": fp.read()}) + return + except OSError: + pass + + # not found + await send( + { + "type": "http.response.start", + "</s> ===========changed ref 5=========== + # module: examples.demo + def app(scope, receive, send): # offset: 1 <s> # not found + await send( + { + "type": "http.response.start", + "status": 404, + "headers": [[b"content-type", b"text/plain"]], + } + ) + await send({"type": "http.response.body", "body": b"Not Found"}) +
examples.http3-server/handle_http_request
Modified
aiortc~aioquic
4e3754e5c60d31f5ba7babc5f6c7bfc982002caa
[http3-server] pass query string to ASGI app
<3>:<del> headers = dict(event.headers) <6>:<add> headers = [] <add> raw_path = b"" <add> method = "" <add> for header, value in event.headers: <add> if header == b":authority": <add> headers.append((b"host", value + ":{}".format(args.port).encode("utf8"))) <add> elif header == b":method": <add> method = value.decode("utf8") <add> elif header == b":path": <add> raw_path = value <add> elif header and not header.startswith(b":"): <add> headers.append((header, value)) <add> <add> if b"?" in raw_path: <add> path_bytes, query_string = raw_path.split(b"?", maxsplit=1) <add> else: <add> path_bytes, query_string = raw_path, b"" <add> <7>:<add> "headers": headers, <del> "headers": event.headers, <8>:<add> "http_version": "0.9" if isinstance(connection, H0Connection) else "3", <add> "method": method, <del> "http_version": "3",
# module: examples.http3-server def handle_http_request( application: AsgiApplication, connection: HttpConnection, event: aioquic.h3.events.RequestReceived, ) -> None: <0> """ <1> Pass HTTP requests to the ASGI application. <2> """ <3> headers = dict(event.headers) <4> stream_id = event.stream_id <5> <6> scope = { <7> "headers": event.headers, <8> "http_version": "3", <9> "method": headers[b":method"].decode("utf8"), <10> "path": headers[b":path"].decode("utf8"), <11> "query_string": b"", <12> "raw_path": headers[b":path"], <13> "root_path": "", <14> "scheme": "https", <15> "type": "http", <16> } <17> <18> async def receive(x): <19> pass <20> <21> async def send(event): <22> if event["type"] == "http.response.start": <23> connection.send_headers( <24> stream_id=stream_id, <25> headers=[(b":status", str(event["status"]).encode("ascii"))] <26> + [(k, v) for k, v in event["headers"]], <27> ) <28> elif event["type"] == "http.response.body": <29> connection.send_data( <30> stream_id=stream_id, data=event["body"], end_stream=True <31> ) <32> <33> await application(scope, receive, send) <34>
===========unchanged ref 0=========== at: aioquic.h0.connection H0Connection(quic: QuicConnection) at: aioquic.h3.events RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.h3.events.RequestReceived headers: Headers stream_id: int stream_ended: bool at: examples.http3-server AsgiApplication = Callable HttpConnection = Union[H0Connection, H3Connection] args = parser.parse_args()
examples.http3-server/handle_http_request
Modified
aiortc~aioquic
1a919dd52ba60cccf8a71feb76d3201ea07647d6
[http3-server] send FIN after application ends
# module: examples.http3-server def handle_http_request( application: AsgiApplication, connection: HttpConnection, event: aioquic.h3.events.RequestReceived, ) -> None: <0> """ <1> Pass HTTP requests to the ASGI application. <2> """ <3> stream_id = event.stream_id <4> <5> headers = [] <6> raw_path = b"" <7> method = "" <8> for header, value in event.headers: <9> if header == b":authority": <10> headers.append((b"host", value + ":{}".format(args.port).encode("utf8"))) <11> elif header == b":method": <12> method = value.decode("utf8") <13> elif header == b":path": <14> raw_path = value <15> elif header and not header.startswith(b":"): <16> headers.append((header, value)) <17> <18> if b"?" in raw_path: <19> path_bytes, query_string = raw_path.split(b"?", maxsplit=1) <20> else: <21> path_bytes, query_string = raw_path, b"" <22> <23> scope = { <24> "headers": headers, <25> "http_version": "0.9" if isinstance(connection, H0Connection) else "3", <26> "method": method, <27> "path": path_bytes.decode("utf8"), <28> "query_string": query_string, <29> "raw_path": raw_path, <30> "root_path": "", <31> "scheme": "https", <32> "type": "http", <33> } <34> <35> # FIXME: actually handle request body <36> queue: asyncio.Queue[Dict] = asyncio.Queue() <37> queue.put_nowait({"type": "http.request", "body": b"", "more_body": False}) <38> <39> async def receive(): <40> return await queue.get() <41> <42> async def send(event): <43> if event["type"] == "http.response.start":</s>
===========below chunk 0=========== # module: examples.http3-server def handle_http_request( application: AsgiApplication, connection: HttpConnection, event: aioquic.h3.events.RequestReceived, ) -> None: # offset: 1 stream_id=stream_id, headers=[(b":status", str(event["status"]).encode("ascii"))] + [(k, v) for k, v in event["headers"]], ) elif event["type"] == "http.response.body": connection.send_data( stream_id=stream_id, data=event["body"], end_stream=True ) await application(scope, receive, send) ===========unchanged ref 0=========== at: aioquic.h0.connection H0Connection(quic: QuicConnection) at: aioquic.h0.connection.H0Connection send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: List[Tuple[bytes, bytes]]) -> None at: aioquic.h3.connection.H3Connection send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers) -> None at: aioquic.h3.events RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.h3.events.RequestReceived headers: Headers stream_id: int stream_ended: bool at: asyncio.queues Queue(maxsize: int=..., *, loop: Optional[AbstractEventLoop]=...) at: asyncio.queues.Queue __class_getitem__ = classmethod(GenericAlias) put_nowait(item: _T) -> None get() -> _T at: examples.http3-server AsgiApplication = Callable HttpConnection = Union[H0Connection, H3Connection] args = parser.parse_args() at: typing Dict = _alias(dict, 2, inst=False, name='Dict')
examples.http3-server/HttpServer.datagram_received
Modified
aiortc~aioquic
7c4d13b05fc7179891ccac355ad6526da46620ca
[http3-server] send pending datagrams when from ASGI send()
# module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: <0> data = cast(bytes, data) <1> buf = Buffer(data=data) <2> header = pull_quic_header(buf, host_cid_length=8) <3> <4> # version negotiation <5> if ( <6> header.version is not None <7> and header.version not in self._configuration.supported_versions <8> ): <9> self._transport.sendto( <10> encode_quic_version_negotiation( <11> source_cid=header.destination_cid, <12> destination_cid=header.source_cid, <13> supported_versions=self._configuration.supported_versions, <14> ), <15> addr, <16> ) <17> return <18> <19> connection = self._connections.get(header.destination_cid, None) <20> original_connection_id: Optional[bytes] = None <21> if connection is None and header.packet_type == PACKET_TYPE_INITIAL: <22> # stateless retry <23> if self._retry is not None: <24> if not header.token: <25> # create a retry token <26> self._transport.sendto( <27> encode_quic_retry( <28> version=header.version, <29> source_cid=os.urandom(8), <30> destination_cid=header.source_cid, <31> original_destination_cid=header.destination_cid, <32> retry_token=self._retry.create_token( <33> addr, header.destination_cid <34> ), <35> ), <36> addr, <37> ) <38> return <39> else: <40> # validate retry token <41> try: <42> original_connection_id = self._retry.validate_token( <43> addr, header.token <44> ) <45> except ValueError: <46> return <47> <48> # create new connection <49> connection = QuicConnection( <50> configuration=self._configuration,</s>
===========below chunk 0=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 1 session_ticket_fetcher=self._session_ticket_fetcher, session_ticket_handler=self._session_ticket_handler, ) self._connections[header.destination_cid] = connection self._connections[connection.host_cid] = connection if connection is not None: connection.receive_datagram(cast(bytes, data), addr, now=self._loop.time()) self._consume_events(connection) ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.quic.connection NetworkAddress = Any QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.quic.connection.QuicConnection receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None at: aioquic.quic.connection.QuicConnection.__init__ self.host_cid = self._host_cids[0].cid at: aioquic.quic.connection.QuicConnection.receive_datagram self.host_cid = context.host_cid at: aioquic.quic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 pull_quic_header(buf: Buffer, host_cid_length: Optional[int]=None) -> QuicHeader encode_quic_retry(version: int, source_cid: bytes, destination_cid: bytes, original_destination_cid: bytes, retry_token: bytes) -> bytes ===========unchanged ref 1=========== encode_quic_version_negotiation(source_cid: bytes, destination_cid: bytes, supported_versions: List[QuicProtocolVersion]) -> bytes at: aioquic.quic.packet.QuicHeader is_long_header: bool version: Optional[int] packet_type: int destination_cid: bytes source_cid: bytes original_destination_cid: bytes = b"" token: bytes = b"" rest_length: int = 0 at: aioquic.quic.retry.QuicRetryTokenHandler create_token(addr: NetworkAddress, destination_cid: bytes) -> bytes validate_token(addr: NetworkAddress, token: bytes) -> bytes at: asyncio.events.AbstractEventLoop time() -> float at: asyncio.protocols.DatagramProtocol __slots__ = () datagram_received(self, data: bytes, addr: Tuple[str, int]) -> None at: asyncio.transports.DatagramTransport __slots__ = () sendto(data: Any, addr: Optional[_Address]=...) -> None at: examples.http3-server.HttpServer _consume_events(self, connection: QuicConnection) -> None _consume_events(connection: QuicConnection) -> None at: examples.http3-server.HttpServer.__init__ self._connections: Dict[bytes, QuicConnection] = {} self._configuration = configuration self._loop = asyncio.get_event_loop() self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler self._transport: Optional[asyncio.DatagramTransport] = None self._retry = QuicRetryTokenHandler() self._retry = None at: examples.http3-server.HttpServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: os urandom(size: int, /) -> bytes ===========unchanged ref 2=========== at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any Text = str at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co]
examples.http3-server/HttpServer._consume_events
Modified
aiortc~aioquic
7c4d13b05fc7179891ccac355ad6526da46620ca
[http3-server] send pending datagrams when from ASGI send()
<28>:<add> handle_http_request( <add> self._application, <add> http, <add> http_event, <add> partial(self._send_pending, connection), <add> ) <del> handle_http_request(self._application, http, http_event) <33>:<del> # send datagrams <34>:<del> for data, addr in connection.datagrams_to_send(now=self._loop.time()): <35>:<del> self._transport.sendto(data, addr) <36>:<del> <37>:<del> # re-arm timer <38>:<del> next_timer
# module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def _consume_events(self, connection: QuicConnection) -> None: <0> # process events <1> event = connection.next_event() <2> while event is not None: <3> if isinstance(event, aioquic.quic.events.ConnectionTerminated): <4> # remove the connection <5> for cid, conn in list(self._connections.items()): <6> if conn == connection: <7> del self._connections[cid] <8> self._http.pop(connection, None) <9> self._timer.pop(connection, None) <10> return <11> elif isinstance(event, aioquic.quic.events.ProtocolNegotiated): <12> if event.alpn_protocol == "h3-22": <13> self._http[connection] = H3Connection(connection) <14> elif event.alpn_protocol == "hq-22": <15> self._http[connection] = H0Connection(connection) <16> elif isinstance(event, aioquic.quic.events.ConnectionIdIssued): <17> self._connections[event.connection_id] = connection <18> elif isinstance(event, aioquic.quic.events.ConnectionIdRetired): <19> assert self._connections[event.connection_id] == connection <20> del self._connections[event.connection_id] <21> <22> #  pass event to the HTTP layer <23> http = self._http.get(connection) <24> if http is not None: <25> for http_event in http.handle_event(event): <26> if isinstance(http_event, RequestReceived): <27> asyncio.ensure_future( <28> handle_http_request(self._application, http, http_event) <29> ) <30> <31> event = connection.next_event() <32> <33> # send datagrams <34> for data, addr in connection.datagrams_to_send(now=self._loop.time()): <35> self._transport.sendto(data, addr) <36> <37> # re-arm timer <38> next_timer</s>
===========below chunk 0=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def _consume_events(self, connection: QuicConnection) -> None: # offset: 1 (timer, timer_at) = self._timer.get(connection, (None, None)) if timer is not None and timer_at != next_timer_at: timer.cancel() timer = None if timer is None and timer_at is not None: timer = self._loop.call_at( next_timer_at, partial(self._handle_timer, connection) ) self._timer[connection] = (timer, next_timer_at) ===========unchanged ref 0=========== at: aioquic.h0.connection H0Connection(quic: QuicConnection) at: aioquic.h0.connection.H0Connection handle_event(event: QuicEvent) -> List[Event] at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection handle_event(event: QuicEvent) -> List[Event] at: aioquic.h3.events RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.quic.connection.QuicConnection handle_timer(now: float) -> None next_event() -> Optional[events.QuicEvent] at: aioquic.quic.events ConnectionIdIssued(connection_id: bytes) ConnectionIdRetired(connection_id: bytes) ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str) ProtocolNegotiated(alpn_protocol: Optional[str]) at: asyncio.events.AbstractEventLoop time() -> float at: asyncio.tasks ensure_future(coro_or_future: _FutureT[_T], *, loop: Optional[AbstractEventLoop]=...) -> Future[_T] at: examples.http3-server handle_http_request(application: AsgiApplication, connection: HttpConnection, event: aioquic.h3.events.RequestReceived, send_pending: Callable[[], None]) -> None at: examples.http3-server.HttpServer _send_pending(connection: QuicConnection) -> None ===========unchanged ref 1=========== at: examples.http3-server.HttpServer.__init__ self._application = application self._connections: Dict[bytes, QuicConnection] = {} self._http: Dict[QuicConnection, HttpConnection] = {} self._loop = asyncio.get_event_loop() self._timer: Dict[QuicConnection, Tuple[asyncio.TimerHandle, float]] = {} at: functools partial(func: Callable[..., _T], *args: Any, **kwargs: Any) partial(func, *args, **keywords, /) -> function with partial application() at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co] at: typing.MutableMapping pop(key: _KT) -> _VT pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T] ===========changed ref 0=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: data = cast(bytes, data) buf = Buffer(data=data) header = pull_quic_header(buf, host_cid_length=8) # version negotiation if ( header.version is not None and header.version not in self._configuration.supported_versions ): self._transport.sendto( encode_quic_version_negotiation( source_cid=header.destination_cid, destination_cid=header.source_cid, supported_versions=self._configuration.supported_versions, ), addr, ) return connection = self._connections.get(header.destination_cid, None) original_connection_id: Optional[bytes] = None if connection is None and header.packet_type == PACKET_TYPE_INITIAL: # stateless retry if self._retry is not None: if not header.token: # create a retry token self._transport.sendto( encode_quic_retry( version=header.version, source_cid=os.urandom(8), destination_cid=header.source_cid, original_destination_cid=header.destination_cid, retry_token=self._retry.create_token( addr, header.destination_cid ), ), addr, ) return else: # validate retry token try: original_connection_id = self._retry.validate_token( addr, header.token ) except ValueError: return # create new connection connection = QuicConnection( configuration=self._configuration, original_connection_id=original_connection_id, session_ticket_fetcher=self._session_ticket_fetcher, session_ticket_handler=self._session_ticket_handler, )</s> ===========changed ref 1=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 1 <s>er=self._session_ticket_fetcher, session_ticket_handler=self._session_ticket_handler, ) self._connections[header.destination_cid] = connection self._connections[connection.host_cid] = connection if connection is not None: connection.receive_datagram(cast(bytes, data), addr, now=self._loop.time()) self._consume_events(connection) + self._send_pending(connection)
examples.http3-server/HttpServer._handle_timer
Modified
aiortc~aioquic
7c4d13b05fc7179891ccac355ad6526da46620ca
[http3-server] send pending datagrams when from ASGI send()
<6>:<add> self._send_pending(connection)
# module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def _handle_timer(self, connection: QuicConnection) -> None: <0> (timer, timer_at) = self._timer.pop(connection) <1> <2> now = max(timer_at, self._loop.time()) <3> connection.handle_timer(now=now) <4> <5> self._consume_events(connection) <6>
===========unchanged ref 0=========== at: aioquic.quic.connection.QuicConnection datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_timer() -> Optional[float] at: asyncio.events.AbstractEventLoop time() -> float at: asyncio.transports.DatagramTransport sendto(data: Any, addr: Optional[_Address]=...) -> None at: examples.http3-server.HttpServer.__init__ self._loop = asyncio.get_event_loop() self._timer: Dict[QuicConnection, Tuple[asyncio.TimerHandle, float]] = {} self._transport: Optional[asyncio.DatagramTransport] = None at: examples.http3-server.HttpServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co] ===========changed ref 0=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): + def _send_pending(self, connection: QuicConnection) -> None: + # send datagrams + for data, addr in connection.datagrams_to_send(now=self._loop.time()): + self._transport.sendto(data, addr) + + # re-arm timer + next_timer_at = connection.get_timer() + (timer, timer_at) = self._timer.get(connection, (None, None)) + if timer is not None and timer_at != next_timer_at: + timer.cancel() + timer = None + if timer is None and timer_at is not None: + timer = self._loop.call_at( + next_timer_at, partial(self._handle_timer, connection) + ) + self._timer[connection] = (timer, next_timer_at) + ===========changed ref 1=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: data = cast(bytes, data) buf = Buffer(data=data) header = pull_quic_header(buf, host_cid_length=8) # version negotiation if ( header.version is not None and header.version not in self._configuration.supported_versions ): self._transport.sendto( encode_quic_version_negotiation( source_cid=header.destination_cid, destination_cid=header.source_cid, supported_versions=self._configuration.supported_versions, ), addr, ) return connection = self._connections.get(header.destination_cid, None) original_connection_id: Optional[bytes] = None if connection is None and header.packet_type == PACKET_TYPE_INITIAL: # stateless retry if self._retry is not None: if not header.token: # create a retry token self._transport.sendto( encode_quic_retry( version=header.version, source_cid=os.urandom(8), destination_cid=header.source_cid, original_destination_cid=header.destination_cid, retry_token=self._retry.create_token( addr, header.destination_cid ), ), addr, ) return else: # validate retry token try: original_connection_id = self._retry.validate_token( addr, header.token ) except ValueError: return # create new connection connection = QuicConnection( configuration=self._configuration, original_connection_id=original_connection_id, session_ticket_fetcher=self._session_ticket_fetcher, session_ticket_handler=self._session_ticket_handler, )</s> ===========changed ref 2=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 1 <s>er=self._session_ticket_fetcher, session_ticket_handler=self._session_ticket_handler, ) self._connections[header.destination_cid] = connection self._connections[connection.host_cid] = connection if connection is not None: connection.receive_datagram(cast(bytes, data), addr, now=self._loop.time()) self._consume_events(connection) + self._send_pending(connection) ===========changed ref 3=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def _consume_events(self, connection: QuicConnection) -> None: # process events event = connection.next_event() while event is not None: if isinstance(event, aioquic.quic.events.ConnectionTerminated): # remove the connection for cid, conn in list(self._connections.items()): if conn == connection: del self._connections[cid] self._http.pop(connection, None) self._timer.pop(connection, None) return elif isinstance(event, aioquic.quic.events.ProtocolNegotiated): if event.alpn_protocol == "h3-22": self._http[connection] = H3Connection(connection) elif event.alpn_protocol == "hq-22": self._http[connection] = H0Connection(connection) elif isinstance(event, aioquic.quic.events.ConnectionIdIssued): self._connections[event.connection_id] = connection elif isinstance(event, aioquic.quic.events.ConnectionIdRetired): assert self._connections[event.connection_id] == connection del self._connections[event.connection_id] #  pass event to the HTTP layer http = self._http.get(connection) if http is not None: for http_event in http.handle_event(event): if isinstance(http_event, RequestReceived): asyncio.ensure_future( + handle_http_request( + self._application, + http, + http_event, + partial(self._send_pending, connection), + ) - handle_http_request(self._application, http, http_event) ) event = connection.next_event() - # send datagrams - for data, addr in connection.datagrams_to_send(now=self._loop.time()): - self._transport.sendto(data, addr) - </s> ===========changed ref 4=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def _consume_events(self, connection: QuicConnection) -> None: # offset: 1 <s>to_send(now=self._loop.time()): - self._transport.sendto(data, addr) - - # re-arm timer - next_timer_at = connection.get_timer() - (timer, timer_at) = self._timer.get(connection, (None, None)) - if timer is not None and timer_at != next_timer_at: - timer.cancel() - timer = None - if timer is None and timer_at is not None: - timer = self._loop.call_at( - next_timer_at, partial(self._handle_timer, connection) - ) - self._timer[connection] = (timer, next_timer_at) -
examples.http3-server/handle_http_request
Modified
aiortc~aioquic
7c4d13b05fc7179891ccac355ad6526da46620ca
[http3-server] send pending datagrams when from ASGI send()
# module: examples.http3-server def handle_http_request( application: AsgiApplication, connection: HttpConnection, event: aioquic.h3.events.RequestReceived, + send_pending: Callable[[], None], ) -> None: <0> """ <1> Pass HTTP requests to the ASGI application. <2> """ <3> stream_id = event.stream_id <4> <5> headers = [] <6> raw_path = b"" <7> method = "" <8> for header, value in event.headers: <9> if header == b":authority": <10> headers.append((b"host", value + ":{}".format(args.port).encode("utf8"))) <11> elif header == b":method": <12> method = value.decode("utf8") <13> elif header == b":path": <14> raw_path = value <15> elif header and not header.startswith(b":"): <16> headers.append((header, value)) <17> <18> if b"?" in raw_path: <19> path_bytes, query_string = raw_path.split(b"?", maxsplit=1) <20> else: <21> path_bytes, query_string = raw_path, b"" <22> <23> scope = { <24> "headers": headers, <25> "http_version": "0.9" if isinstance(connection, H0Connection) else "3", <26> "method": method, <27> "path": path_bytes.decode("utf8"), <28> "query_string": query_string, <29> "raw_path": raw_path, <30> "root_path": "", <31> "scheme": "https", <32> "type": "http", <33> } <34> <35> # FIXME: actually handle request body <36> queue: asyncio.Queue[Dict] = asyncio.Queue() <37> queue.put_nowait({"type": "http.request", "body": b"", "more_body": False}) <38> <39> async def receive(): <40> return await queue.get() <41> <42> async def send(event): <43> if</s>
===========below chunk 0=========== # module: examples.http3-server def handle_http_request( application: AsgiApplication, connection: HttpConnection, event: aioquic.h3.events.RequestReceived, + send_pending: Callable[[], None], ) -> None: # offset: 1 connection.send_headers( stream_id=stream_id, headers=[(b":status", str(event["status"]).encode("ascii"))] + [(k, v) for k, v in event["headers"]], ) elif event["type"] == "http.response.body": connection.send_data( stream_id=stream_id, data=event["body"], end_stream=False ) await application(scope, receive, send) connection.send_data(stream_id=stream_id, data=b"", end_stream=True) ===========unchanged ref 0=========== at: aioquic.h0.connection H0Connection(quic: QuicConnection) at: aioquic.h0.connection.H0Connection send_headers(stream_id: int, headers: List[Tuple[bytes, bytes]]) -> None at: aioquic.h3.connection.H3Connection send_headers(stream_id: int, headers: Headers) -> None at: aioquic.h3.events RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.h3.events.RequestReceived headers: Headers stream_id: int stream_ended: bool at: aioquic.tls SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) at: aioquic.tls.SessionTicket age_add: int cipher_suite: CipherSuite not_valid_after: datetime.datetime not_valid_before: datetime.datetime resumption_secret: bytes server_name: str ticket: bytes max_early_data_size: Optional[int] = None other_extensions: List[Tuple[int, bytes]] = field(default_factory=list) at: asyncio.queues Queue(maxsize: int=..., *, loop: Optional[AbstractEventLoop]=...) at: asyncio.queues.Queue __class_getitem__ = classmethod(GenericAlias) put_nowait(item: _T) -> None get() -> _T at: examples.http3-server AsgiApplication = Callable HttpConnection = Union[H0Connection, H3Connection] args = parser.parse_args() ===========unchanged ref 1=========== at: examples.http3-server.SessionTicketStore.__init__ self.tickets: Dict[bytes, SessionTicket] = {} at: typing Callable = _CallableType(collections.abc.Callable, 2) Dict = _alias(dict, 2, inst=False, name='Dict') at: typing.MutableMapping pop(key: _KT) -> _VT pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T] ===========changed ref 0=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def _handle_timer(self, connection: QuicConnection) -> None: (timer, timer_at) = self._timer.pop(connection) now = max(timer_at, self._loop.time()) connection.handle_timer(now=now) self._consume_events(connection) + self._send_pending(connection) ===========changed ref 1=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): + def _send_pending(self, connection: QuicConnection) -> None: + # send datagrams + for data, addr in connection.datagrams_to_send(now=self._loop.time()): + self._transport.sendto(data, addr) + + # re-arm timer + next_timer_at = connection.get_timer() + (timer, timer_at) = self._timer.get(connection, (None, None)) + if timer is not None and timer_at != next_timer_at: + timer.cancel() + timer = None + if timer is None and timer_at is not None: + timer = self._loop.call_at( + next_timer_at, partial(self._handle_timer, connection) + ) + self._timer[connection] = (timer, next_timer_at) + ===========changed ref 2=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: data = cast(bytes, data) buf = Buffer(data=data) header = pull_quic_header(buf, host_cid_length=8) # version negotiation if ( header.version is not None and header.version not in self._configuration.supported_versions ): self._transport.sendto( encode_quic_version_negotiation( source_cid=header.destination_cid, destination_cid=header.source_cid, supported_versions=self._configuration.supported_versions, ), addr, ) return connection = self._connections.get(header.destination_cid, None) original_connection_id: Optional[bytes] = None if connection is None and header.packet_type == PACKET_TYPE_INITIAL: # stateless retry if self._retry is not None: if not header.token: # create a retry token self._transport.sendto( encode_quic_retry( version=header.version, source_cid=os.urandom(8), destination_cid=header.source_cid, original_destination_cid=header.destination_cid, retry_token=self._retry.create_token( addr, header.destination_cid ), ), addr, ) return else: # validate retry token try: original_connection_id = self._retry.validate_token( addr, header.token ) except ValueError: return # create new connection connection = QuicConnection( configuration=self._configuration, original_connection_id=original_connection_id, session_ticket_fetcher=self._session_ticket_fetcher, session_ticket_handler=self._session_ticket_handler, )</s> ===========changed ref 3=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 1 <s>er=self._session_ticket_fetcher, session_ticket_handler=self._session_ticket_handler, ) self._connections[header.destination_cid] = connection self._connections[connection.host_cid] = connection if connection is not None: connection.receive_datagram(cast(bytes, data), addr, now=self._loop.time()) self._consume_events(connection) + self._send_pending(connection)
examples.http3-client/HttpClient.get
Modified
aiortc~aioquic
d1c8f58b1b46b6891bc88fbad96540c2f203f20e
[examples] fix :authority header handling
<13>:<add> (b":authority", netloc.encode("utf8")), <del> (b":authority", self._quic.configuration.server_name.encode("utf8")),
# module: examples.http3-client class HttpClient(QuicConnectionProtocol): + def get(self, netloc: str, path: str) -> Deque[Event]: - def get(self, path: str) -> Deque[Event]: <0> """ <1> Perform a GET request. <2> """ <3> if not self._connect_called: <4> self._quic.connect(self._server_addr, now=self._loop.time()) <5> self._connect_called = True <6> <7> stream_id = self._quic.get_next_available_stream_id() <8> self._http.send_headers( <9> stream_id=stream_id, <10> headers=[ <11> (b":method", b"GET"), <12> (b":scheme", b"https"), <13> (b":authority", self._quic.configuration.server_name.encode("utf8")), <14> (b":path", path.encode("utf8")), <15> ], <16> ) <17> self._http.send_data(stream_id=stream_id, data=b"", end_stream=True) <18> <19> waiter = self._loop.create_future() <20> self._request_events[stream_id] = deque() <21> self._request_waiter[stream_id] = waiter <22> self._send_pending() <23> <24> return await asyncio.shield(waiter) <25>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol _send_pending() -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._loop = loop self._quic = quic at: aioquic.h0.connection.H0Connection send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: List[Tuple[bytes, bytes]]) -> None at: aioquic.h3.connection.H3Connection send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers) -> None at: aioquic.h3.events Event() at: aioquic.quic.connection.QuicConnection connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None get_next_available_stream_id(is_unidirectional=False) -> int at: asyncio.events.AbstractEventLoop time() -> float create_future() -> Future[Any] at: asyncio.tasks shield(arg: _FutureT[_T], *, loop: Optional[AbstractEventLoop]=...) -> Future[_T] at: collections deque(iterable: Iterable[_T]=..., maxlen: Optional[int]=...) at: examples.http3-client.HttpClient.__init__ self._connect_called = False self._http = H3Connection(self._quic) self._http: HttpConnection self._http = H0Connection(self._quic) self._server_addr = server_addr self._request_events: Dict[int, Deque[Event]] = {} self._request_waiter: Dict[int, asyncio.Future[Deque[Event]]] = {} at: typing Deque = _alias(collections.deque, 1, name='Deque')
examples.http3-client/run
Modified
aiortc~aioquic
d1c8f58b1b46b6891bc88fbad96540c2f203f20e
[examples] fix :authority header handling
<34>:<add> http_events = await client.get(parsed.netloc, parsed.path) <del> http_events = await client.get(parsed.path)
# module: examples.http3-client def run(url: str, legacy_http: bool, **kwargs) -> None: <0> # parse URL <1> parsed = urlparse(url) <2> assert parsed.scheme == "https", "Only HTTPS URLs are supported." <3> if ":" in parsed.netloc: <4> server_name, port_str = parsed.netloc.split(":") <5> port = int(port_str) <6> else: <7> server_name = parsed.netloc <8> port = 443 <9> <10> # lookup remote address <11> infos = await loop.getaddrinfo(server_name, port, type=socket.SOCK_DGRAM) <12> server_addr = infos[0][4] <13> if len(server_addr) == 2: <14> server_addr = ("::ffff:" + server_addr[0], server_addr[1], 0, 0) <15> <16> # prepare QUIC connection <17> _, client = await loop.create_datagram_endpoint( <18> lambda: HttpClient( <19> configuration=QuicConfiguration( <20> alpn_protocols=["hq-22" if legacy_http else "h3-22"], <21> is_client=True, <22> server_name=server_name, <23> **kwargs <24> ), <25> server_addr=server_addr, <26> session_ticket_handler=save_session_ticket, <27> ), <28> local_addr=("::", 0), <29> ) <30> client = cast(HttpClient, client) <31> <32> # perform request <33> start = time.time() <34> http_events = await client.get(parsed.path) <35> elapsed = time.time() - start <36> <37> # print speed <38> octets = 0 <39> for http_event in http_events: <40> if isinstance(http_event, DataReceived): <41> octets += len(http_event.data) <42> logger.info( <43> "Received %d bytes in %.1f s (%.3f Mbps)" <44> % (octets, elapsed, octets *</s>
===========below chunk 0=========== # module: examples.http3-client def run(url: str, legacy_http: bool, **kwargs) -> None: # offset: 1 ) # print response for http_event in http_events: if isinstance(http_event, ResponseReceived): headers = b"" for k, v in http_event.headers: headers += k + b": " + v + b"\r\n" if headers: sys.stderr.buffer.write(headers + b"\r\n") sys.stderr.buffer.flush() elif isinstance(http_event, DataReceived): sys.stdout.buffer.write(http_event.data) sys.stdout.buffer.flush() # close QUIC connection client.close() await client.wait_closed() ===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol close() -> None wait_closed() -> None at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: asyncio.events.AbstractEventLoop getaddrinfo(host: Optional[str], port: Union[str, int, None], *, family: int=..., type: int=..., proto: int=..., flags: int=...) -> List[Tuple[AddressFamily, SocketKind, int, str, Union[Tuple[str, int], Tuple[str, int, int, int]]]] ===========unchanged ref 1=========== create_datagram_endpoint(protocol_factory: _ProtocolFactory, local_addr: Optional[Tuple[str, int]]=..., remote_addr: Optional[Tuple[str, int]]=..., *, family: int=..., proto: int=..., flags: int=..., reuse_address: Optional[bool]=..., reuse_port: Optional[bool]=..., allow_broadcast: Optional[bool]=..., sock: Optional[socket]=...) -> _TransProtPair at: examples.http3-client logger = logging.getLogger("client") HttpClient(*, configuration: QuicConfiguration, server_addr: NetworkAddress, session_ticket_handler: Optional[SessionTicketHandler]=None) save_session_ticket(ticket) loop = asyncio.get_event_loop() at: examples.http3-client.HttpClient get(netloc: str, path: str) -> Deque[Event] get(self, netloc: str, path: str) -> Deque[Event] at: logging.Logger info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None at: socket SOCK_DGRAM: SocketKind at: sys stdout: TextIO stderr: TextIO at: time time() -> float at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any at: typing.BinaryIO __slots__ = () write(s: AnyStr) -> int at: typing.IO __slots__ = () flush() -> None at: typing.TextIO __slots__ = () ===========unchanged ref 2=========== at: urllib.parse urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes ===========changed ref 0=========== # module: examples.http3-client class HttpClient(QuicConnectionProtocol): + def get(self, netloc: str, path: str) -> Deque[Event]: - def get(self, path: str) -> Deque[Event]: """ Perform a GET request. """ if not self._connect_called: self._quic.connect(self._server_addr, now=self._loop.time()) self._connect_called = True stream_id = self._quic.get_next_available_stream_id() self._http.send_headers( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", b"https"), + (b":authority", netloc.encode("utf8")), - (b":authority", self._quic.configuration.server_name.encode("utf8")), (b":path", path.encode("utf8")), ], ) self._http.send_data(stream_id=stream_id, data=b"", end_stream=True) waiter = self._loop.create_future() self._request_events[stream_id] = deque() self._request_waiter[stream_id] = waiter self._send_pending() return await asyncio.shield(waiter)
examples.http3-server/handle_http_request
Modified
aiortc~aioquic
d1c8f58b1b46b6891bc88fbad96540c2f203f20e
[examples] fix :authority header handling
<10>:<add> headers.append((b"host", value)) <del> headers.append((b"host", value + ":{}".format(args.port).encode("utf8")))
# module: examples.http3-server def handle_http_request( application: AsgiApplication, connection: HttpConnection, event: aioquic.h3.events.RequestReceived, send_pending: Callable[[], None], ) -> None: <0> """ <1> Pass HTTP requests to the ASGI application. <2> """ <3> stream_id = event.stream_id <4> <5> headers = [] <6> raw_path = b"" <7> method = "" <8> for header, value in event.headers: <9> if header == b":authority": <10> headers.append((b"host", value + ":{}".format(args.port).encode("utf8"))) <11> elif header == b":method": <12> method = value.decode("utf8") <13> elif header == b":path": <14> raw_path = value <15> elif header and not header.startswith(b":"): <16> headers.append((header, value)) <17> <18> if b"?" in raw_path: <19> path_bytes, query_string = raw_path.split(b"?", maxsplit=1) <20> else: <21> path_bytes, query_string = raw_path, b"" <22> <23> scope = { <24> "headers": headers, <25> "http_version": "0.9" if isinstance(connection, H0Connection) else "3", <26> "method": method, <27> "path": path_bytes.decode("utf8"), <28> "query_string": query_string, <29> "raw_path": raw_path, <30> "root_path": "", <31> "scheme": "https", <32> "type": "http", <33> } <34> <35> # FIXME: actually handle request body <36> queue: asyncio.Queue[Dict] = asyncio.Queue() <37> queue.put_nowait({"type": "http.request", "body": b"", "more_body": False}) <38> <39> async def receive(): <40> return await queue.get() <41> <42> async def send(event): <43> if event</s>
===========below chunk 0=========== # module: examples.http3-server def handle_http_request( application: AsgiApplication, connection: HttpConnection, event: aioquic.h3.events.RequestReceived, send_pending: Callable[[], None], ) -> None: # offset: 1 connection.send_headers( stream_id=stream_id, headers=[(b":status", str(event["status"]).encode("ascii"))] + [(k, v) for k, v in event["headers"]], ) elif event["type"] == "http.response.body": connection.send_data( stream_id=stream_id, data=event["body"], end_stream=False ) send_pending() await application(scope, receive, send) connection.send_data(stream_id=stream_id, data=b"", end_stream=True) send_pending() ===========unchanged ref 0=========== at: aioquic.h0.connection H0Connection(quic: QuicConnection) at: aioquic.h0.connection.H0Connection send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: List[Tuple[bytes, bytes]]) -> None at: aioquic.h3.connection.H3Connection send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers) -> None at: aioquic.h3.events RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.h3.events.RequestReceived headers: Headers stream_id: int stream_ended: bool at: asyncio.queues Queue(maxsize: int=..., *, loop: Optional[AbstractEventLoop]=...) at: asyncio.queues.Queue __class_getitem__ = classmethod(GenericAlias) put_nowait(item: _T) -> None get() -> _T at: examples.http3-server AsgiApplication = Callable HttpConnection = Union[H0Connection, H3Connection] at: typing Callable = _CallableType(collections.abc.Callable, 2) Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: examples.http3-client class HttpClient(QuicConnectionProtocol): + def get(self, netloc: str, path: str) -> Deque[Event]: - def get(self, path: str) -> Deque[Event]: """ Perform a GET request. """ if not self._connect_called: self._quic.connect(self._server_addr, now=self._loop.time()) self._connect_called = True stream_id = self._quic.get_next_available_stream_id() self._http.send_headers( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", b"https"), + (b":authority", netloc.encode("utf8")), - (b":authority", self._quic.configuration.server_name.encode("utf8")), (b":path", path.encode("utf8")), ], ) self._http.send_data(stream_id=stream_id, data=b"", end_stream=True) waiter = self._loop.create_future() self._request_events[stream_id] = deque() self._request_waiter[stream_id] = waiter self._send_pending() return await asyncio.shield(waiter) ===========changed ref 1=========== # module: examples.http3-client def run(url: str, legacy_http: bool, **kwargs) -> None: # parse URL parsed = urlparse(url) assert parsed.scheme == "https", "Only HTTPS URLs are supported." if ":" in parsed.netloc: server_name, port_str = parsed.netloc.split(":") port = int(port_str) else: server_name = parsed.netloc port = 443 # lookup remote address infos = await loop.getaddrinfo(server_name, port, type=socket.SOCK_DGRAM) server_addr = infos[0][4] if len(server_addr) == 2: server_addr = ("::ffff:" + server_addr[0], server_addr[1], 0, 0) # prepare QUIC connection _, client = await loop.create_datagram_endpoint( lambda: HttpClient( configuration=QuicConfiguration( alpn_protocols=["hq-22" if legacy_http else "h3-22"], is_client=True, server_name=server_name, **kwargs ), server_addr=server_addr, session_ticket_handler=save_session_ticket, ), local_addr=("::", 0), ) client = cast(HttpClient, client) # perform request start = time.time() + http_events = await client.get(parsed.netloc, parsed.path) - http_events = await client.get(parsed.path) elapsed = time.time() - start # print speed octets = 0 for http_event in http_events: if isinstance(http_event, DataReceived): octets += len(http_event.data) logger.info( "Received %d bytes in %.1f s (%.3f Mbps)" % (octets, elapsed, octets * 8 / elapsed / 1000000) ) # print response for http_event in http</s> ===========changed ref 2=========== # module: examples.http3-client def run(url: str, legacy_http: bool, **kwargs) -> None: # offset: 1 <s>octets, elapsed, octets * 8 / elapsed / 1000000) ) # print response for http_event in http_events: if isinstance(http_event, ResponseReceived): headers = b"" for k, v in http_event.headers: headers += k + b": " + v + b"\r\n" if headers: sys.stderr.buffer.write(headers + b"\r\n") sys.stderr.buffer.flush() elif isinstance(http_event, DataReceived): sys.stdout.buffer.write(http_event.data) sys.stdout.buffer.flush() # close QUIC connection client.close() await client.wait_closed()
aioquic.asyncio.server/QuicServer.__init__
Modified
aiortc~aioquic
398d5a4076faf46fcc1e3fd38293df257c581c5a
[http3-server] use QuicConnectionProtocol
<1>:<add> self._loop = asyncio.get_event_loop() <2>:<del> self._loop = asyncio.get_event_loop()
# module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def __init__( self, *, configuration: QuicConfiguration, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: <0> self._configuration = configuration <1> self._protocols: Dict[bytes, QuicConnectionProtocol] = {} <2> self._loop = asyncio.get_event_loop() <3> self._session_ticket_fetcher = session_ticket_fetcher <4> self._session_ticket_handler = session_ticket_handler <5> self._transport: Optional[asyncio.DatagramTransport] = None <6> <7> self._stream_handler = stream_handler <8> <9> if stateless_retry: <10> self._retry = QuicRetryTokenHandler() <11> else: <12> self._retry = None <13>
===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.asyncio.protocol QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None] QuicConnectionProtocol(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.asyncio.server.QuicServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.retry QuicRetryTokenHandler() at: aioquic.tls SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] at: asyncio.events get_event_loop() -> AbstractEventLoop at: asyncio.transports DatagramTransport(extra: Optional[Mapping[Any, Any]]=...) at: typing Dict = _alias(dict, 2, inst=False, name='Dict')
aioquic.asyncio.server/QuicServer.datagram_received
Modified
aiortc~aioquic
398d5a4076faf46fcc1e3fd38293df257c581c5a
[http3-server] use QuicConnectionProtocol
# module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: <0> data = cast(bytes, data) <1> buf = Buffer(data=data) <2> header = pull_quic_header(buf, host_cid_length=8) <3> <4> # version negotiation <5> if ( <6> header.version is not None <7> and header.version not in self._configuration.supported_versions <8> ): <9> self._transport.sendto( <10> encode_quic_version_negotiation( <11> source_cid=header.destination_cid, <12> destination_cid=header.source_cid, <13> supported_versions=self._configuration.supported_versions, <14> ), <15> addr, <16> ) <17> return <18> <19> protocol = self._protocols.get(header.destination_cid, None) <20> original_connection_id: Optional[bytes] = None <21> if protocol is None and header.packet_type == PACKET_TYPE_INITIAL: <22> # stateless retry <23> if self._retry is not None: <24> if not header.token: <25> # create a retry token <26> self._transport.sendto( <27> encode_quic_retry( <28> version=header.version, <29> source_cid=os.urandom(8), <30> destination_cid=header.source_cid, <31> original_destination_cid=header.destination_cid, <32> retry_token=self._retry.create_token( <33> addr, header.destination_cid <34> ), <35> ), <36> addr, <37> ) <38> return <39> else: <40> # validate retry token <41> try: <42> original_connection_id = self._retry.validate_token( <43> addr, header.token <44> ) <45> except ValueError: <46> return <47> <48> # create new connection <49> connection = QuicConnection( <50> configuration=</s>
===========below chunk 0=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 1 original_connection_id=original_connection_id, session_ticket_fetcher=self._session_ticket_fetcher, session_ticket_handler=self._session_ticket_handler, ) protocol = QuicConnectionProtocol( connection, stream_handler=self._stream_handler ) protocol._connection_id_issued_handler = partial( self._connection_id_issued, protocol=protocol ) protocol._connection_id_retired_handler = partial( self._connection_id_retired, protocol=protocol ) self._protocols[header.destination_cid] = protocol protocol.connection_made(self._transport) self._protocols[connection.host_cid] = protocol if protocol is not None: protocol.datagram_received(data, addr) ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.asyncio.protocol QuicConnectionProtocol(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.asyncio.protocol.QuicConnectionProtocol connection_made(transport: asyncio.BaseTransport) -> None datagram_received(data: Union[bytes, Text], addr: NetworkAddress) -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None at: aioquic.asyncio.server.QuicServer _connection_id_issued(cid: bytes, protocol: QuicConnectionProtocol) _connection_id_retired(cid: bytes, protocol: QuicConnectionProtocol) -> None at: aioquic.asyncio.server.QuicServer.__init__ self._configuration = configuration self._protocols: Dict[bytes, QuicConnectionProtocol] = {} self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler self._transport: Optional[asyncio.DatagramTransport] = None self._stream_handler = stream_handler self._retry = QuicRetryTokenHandler() self._retry = None at: aioquic.asyncio.server.QuicServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None quic_logger: Optional[QuicLogger] = None ===========unchanged ref 1=========== secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.quic.connection NetworkAddress = Any QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.quic.connection.QuicConnection.__init__ self.host_cid = self._host_cids[0].cid at: aioquic.quic.connection.QuicConnection.receive_datagram self.host_cid = context.host_cid at: aioquic.quic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 pull_quic_header(buf: Buffer, host_cid_length: Optional[int]=None) -> QuicHeader encode_quic_retry(version: int, source_cid: bytes, destination_cid: bytes, original_destination_cid: bytes, retry_token: bytes) -> bytes encode_quic_version_negotiation(source_cid: bytes, destination_cid: bytes, supported_versions: List[QuicProtocolVersion]) -> bytes at: aioquic.quic.packet.QuicHeader is_long_header: bool version: Optional[int] packet_type: int destination_cid: bytes source_cid: bytes original_destination_cid: bytes = b"" token: bytes = b"" rest_length: int = 0 at: aioquic.quic.retry.QuicRetryTokenHandler create_token(addr: NetworkAddress, destination_cid: bytes) -> bytes ===========unchanged ref 2=========== validate_token(addr: NetworkAddress, token: bytes) -> bytes at: asyncio.protocols.DatagramProtocol __slots__ = () datagram_received(self, data: bytes, addr: Tuple[str, int]) -> None at: asyncio.transports.DatagramTransport __slots__ = () sendto(data: Any, addr: Optional[_Address]=...) -> None at: functools partial(func: Callable[..., _T], *args: Any, **kwargs: Any) partial(func, *args, **keywords, /) -> function with partial application() at: os urandom(size: int, /) -> bytes at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any Text = str at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co] ===========changed ref 0=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def __init__( self, *, configuration: QuicConfiguration, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: self._configuration = configuration + self._loop = asyncio.get_event_loop() self._protocols: Dict[bytes, QuicConnectionProtocol] = {} - self._loop = asyncio.get_event_loop() self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler self._transport: Optional[asyncio.DatagramTransport] = None self._stream_handler = stream_handler if stateless_retry: self._retry = QuicRetryTokenHandler() else: self._retry = None
examples.http3-server/HttpServer.__init__
Modified
aiortc~aioquic
398d5a4076faf46fcc1e3fd38293df257c581c5a
[http3-server] use QuicConnectionProtocol
<1>:<del> self._connections: Dict[bytes, QuicConnection] = {} <3>:<del> self._http: Dict[QuicConnection, HttpConnection] = {} <5>:<add> self._protocols: Dict[bytes, QuicConnectionProtocol] = {} <7>:<del> self._timer: Dict[QuicConnection, Tuple[asyncio.TimerHandle, float]] = {}
# module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def __init__( self, *, application: AsgiApplication, configuration: QuicConfiguration, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, ) -> None: <0> self._application = application <1> self._connections: Dict[bytes, QuicConnection] = {} <2> self._configuration = configuration <3> self._http: Dict[QuicConnection, HttpConnection] = {} <4> self._loop = asyncio.get_event_loop() <5> self._session_ticket_fetcher = session_ticket_fetcher <6> self._session_ticket_handler = session_ticket_handler <7> self._timer: Dict[QuicConnection, Tuple[asyncio.TimerHandle, float]] = {} <8> self._transport: Optional[asyncio.DatagramTransport] = None <9> <10> if stateless_retry: <11> self._retry = QuicRetryTokenHandler() <12> else: <13> self._retry = None <14>
===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.asyncio.protocol QuicConnectionProtocol(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.retry QuicRetryTokenHandler() at: aioquic.tls SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] at: asyncio.events get_event_loop() -> AbstractEventLoop at: asyncio.protocols DatagramProtocol() at: asyncio.transports DatagramTransport(extra: Optional[Mapping[Any, Any]]=...) at: examples.http3-server AsgiApplication = Callable at: examples.http3-server.HttpServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def __init__( self, *, configuration: QuicConfiguration, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: self._configuration = configuration + self._loop = asyncio.get_event_loop() self._protocols: Dict[bytes, QuicConnectionProtocol] = {} - self._loop = asyncio.get_event_loop() self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler self._transport: Optional[asyncio.DatagramTransport] = None self._stream_handler = stream_handler if stateless_retry: self._retry = QuicRetryTokenHandler() else: self._retry = None ===========changed ref 1=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: data = cast(bytes, data) buf = Buffer(data=data) header = pull_quic_header(buf, host_cid_length=8) # version negotiation if ( header.version is not None and header.version not in self._configuration.supported_versions ): self._transport.sendto( encode_quic_version_negotiation( source_cid=header.destination_cid, destination_cid=header.source_cid, supported_versions=self._configuration.supported_versions, ), addr, ) return protocol = self._protocols.get(header.destination_cid, None) original_connection_id: Optional[bytes] = None if protocol is None and header.packet_type == PACKET_TYPE_INITIAL: # stateless retry if self._retry is not None: if not header.token: # create a retry token self._transport.sendto( encode_quic_retry( version=header.version, source_cid=os.urandom(8), destination_cid=header.source_cid, original_destination_cid=header.destination_cid, retry_token=self._retry.create_token( addr, header.destination_cid ), ), addr, ) return else: # validate retry token try: original_connection_id = self._retry.validate_token( addr, header.token ) except ValueError: return # create new connection connection = QuicConnection( configuration=self._configuration, original_connection_id=original_connection_id, session_ticket_fetcher=self._session_ticket_fetcher, session_ticket_handler=self._session_ticket_handler</s> ===========changed ref 2=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 1 <s>_ticket_fetcher=self._session_ticket_fetcher, session_ticket_handler=self._session_ticket_handler, ) protocol = QuicConnectionProtocol( connection, stream_handler=self._stream_handler ) + protocol.connection_made(self._transport) + protocol._connection_id_issued_handler = partial( self._connection_id_issued, protocol=protocol ) protocol._connection_id_retired_handler = partial( self._connection_id_retired, protocol=protocol ) self._protocols[header.destination_cid] = protocol - protocol.connection_made(self._transport) - self._protocols[connection.host_cid] = protocol if protocol is not None: protocol.datagram_received(data, addr)
examples.http3-server/HttpServer.close
Modified
aiortc~aioquic
398d5a4076faf46fcc1e3fd38293df257c581c5a
[http3-server] use QuicConnectionProtocol
<0>:<add> for protocol in set(self._protocols.values()): <del> for connection in set(self._connections.values()): <1>:<add> protocol.close() <del> connection.close() <2>:<add> self._protocols.clear() <del> self._connections.clear()
# module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def close(self): <0> for connection in set(self._connections.values()): <1> connection.close() <2> self._connections.clear() <3> self._transport.close() <4>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol close() -> None at: asyncio.transports.BaseTransport __slots__ = ('_extra',) close() -> None at: examples.http3-server.HttpServer.__init__ self._protocols: Dict[bytes, QuicConnectionProtocol] = {} self._transport: Optional[asyncio.DatagramTransport] = None at: examples.http3-server.HttpServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) ===========changed ref 0=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def __init__( self, *, application: AsgiApplication, configuration: QuicConfiguration, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, ) -> None: self._application = application - self._connections: Dict[bytes, QuicConnection] = {} self._configuration = configuration - self._http: Dict[QuicConnection, HttpConnection] = {} self._loop = asyncio.get_event_loop() + self._protocols: Dict[bytes, QuicConnectionProtocol] = {} self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler - self._timer: Dict[QuicConnection, Tuple[asyncio.TimerHandle, float]] = {} self._transport: Optional[asyncio.DatagramTransport] = None if stateless_retry: self._retry = QuicRetryTokenHandler() else: self._retry = None ===========changed ref 1=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def __init__( self, *, configuration: QuicConfiguration, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: self._configuration = configuration + self._loop = asyncio.get_event_loop() self._protocols: Dict[bytes, QuicConnectionProtocol] = {} - self._loop = asyncio.get_event_loop() self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler self._transport: Optional[asyncio.DatagramTransport] = None self._stream_handler = stream_handler if stateless_retry: self._retry = QuicRetryTokenHandler() else: self._retry = None ===========changed ref 2=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: data = cast(bytes, data) buf = Buffer(data=data) header = pull_quic_header(buf, host_cid_length=8) # version negotiation if ( header.version is not None and header.version not in self._configuration.supported_versions ): self._transport.sendto( encode_quic_version_negotiation( source_cid=header.destination_cid, destination_cid=header.source_cid, supported_versions=self._configuration.supported_versions, ), addr, ) return protocol = self._protocols.get(header.destination_cid, None) original_connection_id: Optional[bytes] = None if protocol is None and header.packet_type == PACKET_TYPE_INITIAL: # stateless retry if self._retry is not None: if not header.token: # create a retry token self._transport.sendto( encode_quic_retry( version=header.version, source_cid=os.urandom(8), destination_cid=header.source_cid, original_destination_cid=header.destination_cid, retry_token=self._retry.create_token( addr, header.destination_cid ), ), addr, ) return else: # validate retry token try: original_connection_id = self._retry.validate_token( addr, header.token ) except ValueError: return # create new connection connection = QuicConnection( configuration=self._configuration, original_connection_id=original_connection_id, session_ticket_fetcher=self._session_ticket_fetcher, session_ticket_handler=self._session_ticket_handler</s> ===========changed ref 3=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 1 <s>_ticket_fetcher=self._session_ticket_fetcher, session_ticket_handler=self._session_ticket_handler, ) protocol = QuicConnectionProtocol( connection, stream_handler=self._stream_handler ) + protocol.connection_made(self._transport) + protocol._connection_id_issued_handler = partial( self._connection_id_issued, protocol=protocol ) protocol._connection_id_retired_handler = partial( self._connection_id_retired, protocol=protocol ) self._protocols[header.destination_cid] = protocol - protocol.connection_made(self._transport) - self._protocols[connection.host_cid] = protocol if protocol is not None: protocol.datagram_received(data, addr)
examples.http3-server/HttpServer.datagram_received
Modified
aiortc~aioquic
398d5a4076faf46fcc1e3fd38293df257c581c5a
[http3-server] use QuicConnectionProtocol
<19>:<add> protocol = self._protocols.get(header.destination_cid, None) <del> connection = self._connections.get(header.destination_cid, None) <21>:<add> if protocol is None and header.packet_type == PACKET_TYPE_INITIAL: <del> if connection is None and header.packet_type == PACKET_TYPE_INITIAL:
# module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: <0> data = cast(bytes, data) <1> buf = Buffer(data=data) <2> header = pull_quic_header(buf, host_cid_length=8) <3> <4> # version negotiation <5> if ( <6> header.version is not None <7> and header.version not in self._configuration.supported_versions <8> ): <9> self._transport.sendto( <10> encode_quic_version_negotiation( <11> source_cid=header.destination_cid, <12> destination_cid=header.source_cid, <13> supported_versions=self._configuration.supported_versions, <14> ), <15> addr, <16> ) <17> return <18> <19> connection = self._connections.get(header.destination_cid, None) <20> original_connection_id: Optional[bytes] = None <21> if connection is None and header.packet_type == PACKET_TYPE_INITIAL: <22> # stateless retry <23> if self._retry is not None: <24> if not header.token: <25> # create a retry token <26> self._transport.sendto( <27> encode_quic_retry( <28> version=header.version, <29> source_cid=os.urandom(8), <30> destination_cid=header.source_cid, <31> original_destination_cid=header.destination_cid, <32> retry_token=self._retry.create_token( <33> addr, header.destination_cid <34> ), <35> ), <36> addr, <37> ) <38> return <39> else: <40> # validate retry token <41> try: <42> original_connection_id = self._retry.validate_token( <43> addr, header.token <44> ) <45> except ValueError: <46> return <47> <48> # create new connection <49> connection = QuicConnection( <50> configuration=self._configuration,</s>
===========below chunk 0=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 1 session_ticket_fetcher=self._session_ticket_fetcher, session_ticket_handler=self._session_ticket_handler, ) self._connections[header.destination_cid] = connection self._connections[connection.host_cid] = connection if connection is not None: connection.receive_datagram(cast(bytes, data), addr, now=self._loop.time()) self._consume_events(connection) self._send_pending(connection) ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.asyncio.protocol.QuicConnectionProtocol connection_made(transport: asyncio.BaseTransport) -> None datagram_received(data: Union[bytes, Text], addr: NetworkAddress) -> None at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.quic.connection.QuicConnection.__init__ self.host_cid = self._host_cids[0].cid at: aioquic.quic.connection.QuicConnection.receive_datagram self.host_cid = context.host_cid at: aioquic.quic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 pull_quic_header(buf: Buffer, host_cid_length: Optional[int]=None) -> QuicHeader encode_quic_retry(version: int, source_cid: bytes, destination_cid: bytes, original_destination_cid: bytes, retry_token: bytes) -> bytes ===========unchanged ref 1=========== encode_quic_version_negotiation(source_cid: bytes, destination_cid: bytes, supported_versions: List[QuicProtocolVersion]) -> bytes at: aioquic.quic.packet.QuicHeader is_long_header: bool version: Optional[int] packet_type: int destination_cid: bytes source_cid: bytes original_destination_cid: bytes = b"" token: bytes = b"" rest_length: int = 0 at: aioquic.quic.retry.QuicRetryTokenHandler create_token(addr: NetworkAddress, destination_cid: bytes) -> bytes validate_token(addr: NetworkAddress, token: bytes) -> bytes at: asyncio.transports.DatagramTransport __slots__ = () sendto(data: Any, addr: Optional[_Address]=...) -> None at: examples.http3-server HttpServerProtocol(quic: QuicConnection, server: HttpServer) at: examples.http3-server.HttpServer.__init__ self._configuration = configuration self._protocols: Dict[bytes, QuicConnectionProtocol] = {} self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler self._transport: Optional[asyncio.DatagramTransport] = None self._retry = QuicRetryTokenHandler() self._retry = None at: examples.http3-server.HttpServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: os urandom(size: int, /) -> bytes at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any ===========unchanged ref 2=========== at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co] ===========changed ref 0=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def close(self): + for protocol in set(self._protocols.values()): - for connection in set(self._connections.values()): + protocol.close() - connection.close() + self._protocols.clear() - self._connections.clear() self._transport.close() ===========changed ref 1=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def __init__( self, *, application: AsgiApplication, configuration: QuicConfiguration, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, ) -> None: self._application = application - self._connections: Dict[bytes, QuicConnection] = {} self._configuration = configuration - self._http: Dict[QuicConnection, HttpConnection] = {} self._loop = asyncio.get_event_loop() + self._protocols: Dict[bytes, QuicConnectionProtocol] = {} self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler - self._timer: Dict[QuicConnection, Tuple[asyncio.TimerHandle, float]] = {} self._transport: Optional[asyncio.DatagramTransport] = None if stateless_retry: self._retry = QuicRetryTokenHandler() else: self._retry = None ===========changed ref 2=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def __init__( self, *, configuration: QuicConfiguration, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: self._configuration = configuration + self._loop = asyncio.get_event_loop() self._protocols: Dict[bytes, QuicConnectionProtocol] = {} - self._loop = asyncio.get_event_loop() self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler self._transport: Optional[asyncio.DatagramTransport] = None self._stream_handler = stream_handler if stateless_retry: self._retry = QuicRetryTokenHandler() else: self._retry = None
examples.http3-server/handle_http_request
Modified
aiortc~aioquic
3f38ca120070c4e45e471e5856d126ddf0a9dde5
[http3-server] add "server" and "date" headers to response
# module: examples.http3-server def handle_http_request( application: AsgiApplication, connection: HttpConnection, event: aioquic.h3.events.RequestReceived, send_pending: Callable[[], None], ) -> None: <0> """ <1> Pass HTTP requests to the ASGI application. <2> """ <3> stream_id = event.stream_id <4> <5> headers = [] <6> raw_path = b"" <7> method = "" <8> for header, value in event.headers: <9> if header == b":authority": <10> headers.append((b"host", value)) <11> elif header == b":method": <12> method = value.decode("utf8") <13> elif header == b":path": <14> raw_path = value <15> elif header and not header.startswith(b":"): <16> headers.append((header, value)) <17> <18> if b"?" in raw_path: <19> path_bytes, query_string = raw_path.split(b"?", maxsplit=1) <20> else: <21> path_bytes, query_string = raw_path, b"" <22> <23> scope = { <24> "headers": headers, <25> "http_version": "0.9" if isinstance(connection, H0Connection) else "3", <26> "method": method, <27> "path": path_bytes.decode("utf8"), <28> "query_string": query_string, <29> "raw_path": raw_path, <30> "root_path": "", <31> "scheme": "https", <32> "type": "http", <33> } <34> <35> # FIXME: actually handle request body <36> queue: asyncio.Queue[Dict] = asyncio.Queue() <37> queue.put_nowait({"type": "http.request", "body": b"", "more_body": False}) <38> <39> async def receive(): <40> return await queue.get() <41> <42> async def send(event): <43> if event["type"] == "http.response.start": <44> connection</s>
===========below chunk 0=========== # module: examples.http3-server def handle_http_request( application: AsgiApplication, connection: HttpConnection, event: aioquic.h3.events.RequestReceived, send_pending: Callable[[], None], ) -> None: # offset: 1 stream_id=stream_id, headers=[(b":status", str(event["status"]).encode("ascii"))] + [(k, v) for k, v in event["headers"]], ) elif event["type"] == "http.response.body": connection.send_data( stream_id=stream_id, data=event["body"], end_stream=False ) send_pending() await application(scope, receive, send) connection.send_data(stream_id=stream_id, data=b"", end_stream=True) send_pending() ===========unchanged ref 0=========== at: aioquic.h0.connection H0Connection(quic: QuicConnection) at: aioquic.h0.connection.H0Connection send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: List[Tuple[bytes, bytes]]) -> None at: aioquic.h3.connection.H3Connection send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers) -> None at: aioquic.h3.events RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.h3.events.RequestReceived headers: Headers stream_id: int stream_ended: bool at: asyncio.queues Queue(maxsize: int=..., *, loop: Optional[AbstractEventLoop]=...) at: asyncio.queues.Queue __class_getitem__ = classmethod(GenericAlias) put_nowait(item: _T) -> None get() -> _T at: email.utils formatdate(timeval: Optional[float]=..., localtime: bool=..., usegmt: bool=...) -> str at: examples.http3-server AsgiApplication = Callable HttpConnection = Union[H0Connection, H3Connection] at: time time() -> float at: typing Callable = _CallableType(collections.abc.Callable, 2) Dict = _alias(dict, 2, inst=False, name='Dict')
examples.http3-server/HttpServerProtocol.__init__
Modified
aiortc~aioquic
d48e26a1395bf79774086e5281475d330eff67f4
[http3-server] pass request body to ASGI app
<1>:<add> self._handlers: Dict[int, HttpRequestHandler] = {}
# module: examples.http3-server class HttpServerProtocol(QuicConnectionProtocol): def __init__(self, quic: QuicConnection, server: HttpServer): <0> super().__init__(quic) <1> self._http: Optional[HttpConnection] = None <2> self._server = server <3>
===========unchanged ref 0=========== at: aioquic.quic.packet encode_quic_retry(version: int, source_cid: bytes, destination_cid: bytes, original_destination_cid: bytes, retry_token: bytes) -> bytes at: aioquic.quic.packet.QuicHeader is_long_header: bool version: Optional[int] packet_type: int destination_cid: bytes source_cid: bytes original_destination_cid: bytes = b"" token: bytes = b"" rest_length: int = 0 at: asyncio.transports.DatagramTransport __slots__ = () sendto(data: Any, addr: Optional[_Address]=...) -> None at: examples.http3-server.HttpServer.__init__ self._transport: Optional[asyncio.DatagramTransport] = None at: examples.http3-server.HttpServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: examples.http3-server.HttpServer.datagram_received header = pull_quic_header(buf, host_cid_length=8) ===========changed ref 0=========== # module: examples.http3-server + class HttpRequestHandler: + def receive(self) -> Dict: + return await self.queue.get() + ===========changed ref 1=========== # module: examples.http3-server + class HttpRequestHandler: + def run_asgi(self, app: AsgiApplication) -> None: + await application(self.scope, self.receive, self.send) + + self.connection.send_data(stream_id=self.stream_id, data=b"", end_stream=True) + self.send_pending() + ===========changed ref 2=========== # module: examples.http3-server + class HttpRequestHandler: + def __init__( + self, + *, + connection: HttpConnection, + scope: Dict, + send_pending: Callable[[], None], + stream_id: int, + ): + self.connection = connection + self.queue: asyncio.Queue[Dict] = asyncio.Queue() + self.scope = scope + self.send_pending = send_pending + self.stream_id = stream_id + ===========changed ref 3=========== # module: examples.http3-server + class HttpRequestHandler: + def send(self, message: Dict): + if message["type"] == "http.response.start": + self.connection.send_headers( + stream_id=self.stream_id, + headers=[ + (b":status", str(message["status"]).encode("ascii")), + (b"server", b"aioquic"), + (b"date", formatdate(time.time(), usegmt=True).encode()), + ] + + [(k, v) for k, v in message["headers"]], + ) + elif message["type"] == "http.response.body": + self.connection.send_data( + stream_id=self.stream_id, data=message["body"], end_stream=False + ) + self.send_pending() +
examples.http3-server/HttpServerProtocol._handle_event
Modified
aiortc~aioquic
d48e26a1395bf79774086e5281475d330eff67f4
[http3-server] pass request body to ASGI app
<20>:<del> if isinstance(http_event, RequestReceived): <21>:<del> asyncio.ensure_future( <22>:<del> handle_http_request( <23>:<del> self._server._application, <24>:<del> self._http, <25>:<del> http_event, <26>:<del> self._send_pending, <27>:<del> ) <28>:<del> ) <29>:<add> self.handle_http_event(http_event)
# module: examples.http3-server class HttpServerProtocol(QuicConnectionProtocol): def _handle_event(self, event: QuicEvent): <0> if isinstance(event, aioquic.quic.events.ConnectionTerminated): <1> # remove the connection <2> for cid, protocol in list(self._server._protocols.items()): <3> if protocol == self: <4> del self._server._protocols[cid] <5> return <6> elif isinstance(event, aioquic.quic.events.ProtocolNegotiated): <7> if event.alpn_protocol == "h3-22": <8> self._http = H3Connection(self._quic) <9> elif event.alpn_protocol == "hq-22": <10> self._http = H0Connection(self._quic) <11> elif isinstance(event, aioquic.quic.events.ConnectionIdIssued): <12> self._server._protocols[event.connection_id] = self <13> elif isinstance(event, aioquic.quic.events.ConnectionIdRetired): <14> assert self._server._protocols[event.connection_id] == self <15> del self._server._protocols[event.connection_id] <16> <17> #  pass event to the HTTP layer <18> if self._http is not None: <19> for http_event in self._http.handle_event(event): <20> if isinstance(http_event, RequestReceived): <21> asyncio.ensure_future( <22> handle_http_request( <23> self._server._application, <24> self._http, <25> http_event, <26> self._send_pending, <27> ) <28> ) <29>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol connection_made(transport: asyncio.BaseTransport) -> None at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.quic.packet.QuicHeader destination_cid: bytes source_cid: bytes token: bytes = b"" at: aioquic.quic.retry.QuicRetryTokenHandler create_token(addr: NetworkAddress, destination_cid: bytes) -> bytes validate_token(addr: NetworkAddress, token: bytes) -> bytes at: examples.http3-server HttpServerProtocol(quic: QuicConnection, server: HttpServer) at: examples.http3-server.HttpServer.__init__ self._configuration = configuration self._protocols: Dict[bytes, QuicConnectionProtocol] = {} self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler self._transport: Optional[asyncio.DatagramTransport] = None self._retry = QuicRetryTokenHandler() self._retry = None at: examples.http3-server.HttpServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: examples.http3-server.HttpServer.datagram_received header = pull_quic_header(buf, host_cid_length=8) at: os urandom(size: int, /) -> bytes ===========changed ref 0=========== # module: examples.http3-server class HttpServerProtocol(QuicConnectionProtocol): def __init__(self, quic: QuicConnection, server: HttpServer): super().__init__(quic) + self._handlers: Dict[int, HttpRequestHandler] = {} self._http: Optional[HttpConnection] = None self._server = server ===========changed ref 1=========== # module: examples.http3-server + class HttpRequestHandler: + def receive(self) -> Dict: + return await self.queue.get() + ===========changed ref 2=========== # module: examples.http3-server + class HttpRequestHandler: + def run_asgi(self, app: AsgiApplication) -> None: + await application(self.scope, self.receive, self.send) + + self.connection.send_data(stream_id=self.stream_id, data=b"", end_stream=True) + self.send_pending() + ===========changed ref 3=========== # module: examples.http3-server + class HttpRequestHandler: + def __init__( + self, + *, + connection: HttpConnection, + scope: Dict, + send_pending: Callable[[], None], + stream_id: int, + ): + self.connection = connection + self.queue: asyncio.Queue[Dict] = asyncio.Queue() + self.scope = scope + self.send_pending = send_pending + self.stream_id = stream_id + ===========changed ref 4=========== # module: examples.http3-server + class HttpRequestHandler: + def send(self, message: Dict): + if message["type"] == "http.response.start": + self.connection.send_headers( + stream_id=self.stream_id, + headers=[ + (b":status", str(message["status"]).encode("ascii")), + (b"server", b"aioquic"), + (b"date", formatdate(time.time(), usegmt=True).encode()), + ] + + [(k, v) for k, v in message["headers"]], + ) + elif message["type"] == "http.response.body": + self.connection.send_data( + stream_id=self.stream_id, data=message["body"], end_stream=False + ) + self.send_pending() +
aioquic.asyncio.protocol/QuicConnectionProtocol._send_pending
Modified
aiortc~aioquic
12f227b56149961adfcfae9398616af10c1c4454
[asyncio] make quic_event_received public API
<5>:<add> self.quic_event_received(event) <del> self._handle_event(event)
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def _send_pending(self) -> None: <0> self._send_task = None <1> <2> # process events <3> event = self._quic.next_event() <4> while event is not None: <5> self._handle_event(event) <6> event = self._quic.next_event() <7> <8> # send datagrams <9> for data, addr in self._quic.datagrams_to_send(now=self._loop.time()): <10> self._transport.sendto(data, addr) <11> <12> # re-arm timer <13> timer_at = self._quic.get_timer() <14> if self._timer is not None and self._timer_at != timer_at: <15> self._timer.cancel() <16> self._timer = None <17> if self._timer is None and timer_at is not None: <18> self._timer = self._loop.call_at(timer_at, self._handle_timer) <19> self._timer_at = timer_at <20>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol quic_event_received(event: events.QuicEvent) -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._loop = loop self._quic = quic self._send_task: Optional[asyncio.Handle] = None self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transport: Optional[asyncio.DatagramTransport] = None at: aioquic.asyncio.protocol.QuicConnectionProtocol._handle_timer self._timer = None self._timer_at = None at: aioquic.asyncio.protocol.QuicConnectionProtocol._send_pending self._timer_at = timer_at at: aioquic.asyncio.protocol.QuicConnectionProtocol._send_soon self._send_task = self._loop.call_soon(self._send_pending) at: aioquic.asyncio.protocol.QuicConnectionProtocol.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: aioquic.quic.connection.QuicConnection datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_timer() -> Optional[float] next_event() -> Optional[events.QuicEvent] at: asyncio.events.AbstractEventLoop time() -> float at: asyncio.events.TimerHandle __slots__ = ['_scheduled', '_when'] cancel() -> None at: asyncio.transports.DatagramTransport __slots__ = () sendto(data: Any, addr: Optional[_Address]=...) -> None ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): + # overridable + + def quic_event_received(self, event: events.QuicEvent) -> None: + if isinstance(event, events.ConnectionIdIssued): + self._connection_id_issued_handler(event.connection_id) + elif isinstance(event, events.ConnectionIdRetired): + self._connection_id_retired_handler(event.connection_id) + elif isinstance(event, events.ConnectionTerminated): + for reader in self._stream_readers.values(): + reader.feed_eof() + if not self._connected_waiter.done(): + self._connected_waiter.set_exception(ConnectionError) + self._closed.set() + elif isinstance(event, events.HandshakeCompleted): + self._connected_waiter.set_result(None) + elif isinstance(event, events.PingAcknowledged): + waiter = self._ping_waiter + self._ping_waiter = None + waiter.set_result(None) + elif isinstance(event, events.StreamDataReceived): + reader = self._stream_readers.get(event.stream_id, None) + if reader is None: + reader, writer = self._create_stream(event.stream_id) + self._stream_handler(reader, writer) + reader.feed_data(event.data) + if event.end_stream: + reader.feed_eof() + ===========changed ref 1=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): - def _handle_event(self, event: events.QuicEvent) -> None: - if isinstance(event, events.ConnectionIdIssued): - self._connection_id_issued_handler(event.connection_id) - elif isinstance(event, events.ConnectionIdRetired): - self._connection_id_retired_handler(event.connection_id) - elif isinstance(event, events.ConnectionTerminated): - for reader in self._stream_readers.values(): - reader.feed_eof() - if not self._connected_waiter.done(): - self._connected_waiter.set_exception(ConnectionError) - self._closed.set() - elif isinstance(event, events.HandshakeCompleted): - self._connected_waiter.set_result(None) - elif isinstance(event, events.PingAcknowledged): - waiter = self._ping_waiter - self._ping_waiter = None - waiter.set_result(None) - elif isinstance(event, events.StreamDataReceived): - reader = self._stream_readers.get(event.stream_id, None) - if reader is None: - reader, writer = self._create_stream(event.stream_id) - self._stream_handler(reader, writer) - reader.feed_data(event.data) - if event.end_stream: - reader.feed_eof() -
aioquic.h0.connection/H0Connection.handle_event
Modified
aiortc~aioquic
cb553fac2d6c8dd992698aec2655bf846be79ceb
[http] rename Event to HttpEvent
<0>:<add> http_events: List[HttpEvent] = [] <del> http_events: List[Event] = []
# module: aioquic.h0.connection class H0Connection: + def handle_event(self, event: QuicEvent) -> List[HttpEvent]: - def handle_event(self, event: QuicEvent) -> List[Event]: <0> http_events: List[Event] = [] <1> <2> if isinstance(event, StreamDataReceived) and (event.stream_id % 4) == 0: <3> data = event.data <4> if not self._headers_received.get(event.stream_id, False): <5> if self._is_client: <6> http_events.append( <7> ResponseReceived( <8> headers=[], stream_ended=False, stream_id=event.stream_id <9> ) <10> ) <11> else: <12> method, path = data.rstrip().split(b" ", 1) <13> http_events.append( <14> RequestReceived( <15> headers=[(b":method", method), (b":path", path)], <16> stream_ended=False, <17> stream_id=event.stream_id, <18> ) <19> ) <20> data = b"" <21> self._headers_received[event.stream_id] = True <22> <23> http_events.append( <24> DataReceived( <25> data=data, stream_ended=event.end_stream, stream_id=event.stream_id <26> ) <27> ) <28> <29> return http_events <30>
===========unchanged ref 0=========== at: aioquic.h0.connection.H0Connection.__init__ self._headers_received: Dict[int, bool] = {} self._is_client = quic.configuration.is_client at: aioquic.h3.events HttpEvent() DataReceived(data: bytes, stream_id: int, stream_ended: bool) RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.h3.events.DataReceived data: bytes stream_id: int stream_ended: bool at: aioquic.h3.events.RequestReceived headers: Headers stream_id: int stream_ended: bool at: aioquic.h3.events.ResponseReceived headers: Headers stream_id: int stream_ended: bool at: aioquic.quic.events QuicEvent() StreamDataReceived(data: bytes, end_stream: bool, stream_id: int) at: typing List = _alias(list, 1, inst=False, name='List') at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co] ===========changed ref 0=========== # module: aioquic.h3.events - class Event: - """ - Base class for HTTP/3 events. - """ - - pass - ===========changed ref 1=========== # module: aioquic.h3.events - class Event: - """ - Base class for HTTP/3 events. - """ - - pass -
aioquic.h3.connection/H3Connection._receive_stream_data_bidi
Modified
aiortc~aioquic
cb553fac2d6c8dd992698aec2655bf846be79ceb
[http] rename Event to HttpEvent
<3>:<add> http_events: List[HttpEvent] = [] <del> http_events: List[Event] = []
# module: aioquic.h3.connection class H3Connection: def _receive_stream_data_bidi( self, stream_id: int, data: bytes, stream_ended: bool + ) -> List[HttpEvent]: - ) -> List[Event]: <0> """ <1> Client-initiated bidirectional streams carry requests and responses. <2> """ <3> http_events: List[Event] = [] <4> <5> stream = self._stream[stream_id] <6> stream.buffer += data <7> if stream_ended: <8> stream.ended = True <9> if stream.blocked: <10> return http_events <11> <12> # shortcut DATA frame bits <13> if ( <14> stream.frame_size is not None <15> and stream.frame_type == FrameType.DATA <16> and len(stream.buffer) < stream.frame_size <17> ): <18> http_events.append( <19> DataReceived( <20> data=stream.buffer, stream_id=stream_id, stream_ended=False <21> ) <22> ) <23> stream.frame_size -= len(stream.buffer) <24> stream.buffer = b"" <25> return http_events <26> <27> # some peers (e.g. f5) end the stream with no data <28> if stream_ended and not stream.buffer: <29> http_events.append( <30> DataReceived(data=b"", stream_id=stream_id, stream_ended=True) <31> ) <32> return http_events <33> <34> buf = Buffer(data=stream.buffer) <35> consumed = 0 <36> <37> while not buf.eof(): <38> # fetch next frame header <39> if stream.frame_size is None: <40> try: <41> stream.frame_type = buf.pull_uint_var() <42> stream.frame_size = buf.pull_uint_var() <43> except BufferReadError: <44> break <45> consumed = buf.tell() <46> <47> # check how much data is available <48> chunk_size = min(stream.</s>
===========below chunk 0=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data_bidi( self, stream_id: int, data: bytes, stream_ended: bool + ) -> List[HttpEvent]: - ) -> List[Event]: # offset: 1 if ( stream.frame_type == FrameType.HEADERS and chunk_size < stream.frame_size ): break # read available data frame_data = buf.pull_bytes(chunk_size) consumed = buf.tell() # detect end of frame stream.frame_size -= chunk_size if not stream.frame_size: stream.frame_size = None if stream.frame_type == FrameType.DATA and (stream_ended or frame_data): http_events.append( DataReceived( data=frame_data, stream_id=stream_id, stream_ended=stream_ended and buf.eof(), ) ) elif stream.frame_type == FrameType.HEADERS: try: decoder, headers = self._decoder.feed_header(stream_id, frame_data) except StreamBlocked: stream.blocked = True break self._quic.send_stream_data(self._local_decoder_stream_id, decoder) cls = ResponseReceived if self._is_client else RequestReceived http_events.append( cls( headers=headers, stream_id=stream_id, stream_ended=stream_ended and buf.eof(), ) ) # remove processed data from buffer stream.buffer = stream.buffer[consumed:] return http_events ===========unchanged ref 0=========== at: aioquic._buffer BufferReadError(*args: object) Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer eof() -> bool tell() -> int pull_bytes(length: int) -> bytes pull_uint_var() -> int at: aioquic.h3.connection FrameType(x: Union[str, bytes, bytearray], base: int) FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: aioquic.h3.connection.H3Connection.__init__ self._is_client = quic.configuration.is_client self._quic = quic self._decoder = Decoder(self._max_table_capacity, self._blocked_streams) self._stream: Dict[int, H3Stream] = {} self._local_decoder_stream_id: Optional[int] = None at: aioquic.h3.connection.H3Connection._init_connection self._local_decoder_stream_id = self._create_uni_stream( StreamType.QPACK_DECODER ) at: aioquic.h3.connection.H3Stream.__init__ self.blocked = False self.buffer = b"" self.ended = False self.frame_size: Optional[int] = None self.frame_type: Optional[int] = None at: aioquic.h3.events HttpEvent() DataReceived(data: bytes, stream_id: int, stream_ended: bool) RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.h3.events.DataReceived data: bytes stream_id: int stream_ended: bool ===========unchanged ref 1=========== at: aioquic.h3.events.RequestReceived headers: Headers stream_id: int stream_ended: bool at: aioquic.h3.events.ResponseReceived headers: Headers stream_id: int stream_ended: bool at: aioquic.quic.connection.QuicConnection send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.h3.events - class Event: - """ - Base class for HTTP/3 events. - """ - - pass - ===========changed ref 1=========== # module: aioquic.h3.events - class Event: - """ - Base class for HTTP/3 events. - """ - - pass - ===========changed ref 2=========== # module: aioquic.h0.connection class H0Connection: + def handle_event(self, event: QuicEvent) -> List[HttpEvent]: - def handle_event(self, event: QuicEvent) -> List[Event]: + http_events: List[HttpEvent] = [] - http_events: List[Event] = [] if isinstance(event, StreamDataReceived) and (event.stream_id % 4) == 0: data = event.data if not self._headers_received.get(event.stream_id, False): if self._is_client: http_events.append( ResponseReceived( headers=[], stream_ended=False, stream_id=event.stream_id ) ) else: method, path = data.rstrip().split(b" ", 1) http_events.append( RequestReceived( headers=[(b":method", method), (b":path", path)], stream_ended=False, stream_id=event.stream_id, ) ) data = b"" self._headers_received[event.stream_id] = True http_events.append( DataReceived( data=data, stream_ended=event.end_stream, stream_id=event.stream_id ) ) return http_events
aioquic.h3.connection/H3Connection._receive_stream_data_uni
Modified
aiortc~aioquic
cb553fac2d6c8dd992698aec2655bf846be79ceb
[http] rename Event to HttpEvent
<0>:<add> http_events: List[HttpEvent] = [] <del> http_events: List[Event] = []
# module: aioquic.h3.connection class H3Connection: + def _receive_stream_data_uni(self, stream_id: int, data: bytes) -> List[HttpEvent]: - def _receive_stream_data_uni(self, stream_id: int, data: bytes) -> List[Event]: <0> http_events: List[Event] = [] <1> <2> stream = self._stream[stream_id] <3> stream.buffer += data <4> <5> buf = Buffer(data=stream.buffer) <6> consumed = 0 <7> unblocked_streams: Set[int] = set() <8> <9> while not buf.eof(): <10> # fetch stream type for unidirectional streams <11> if stream.stream_type is None: <12> try: <13> stream.stream_type = buf.pull_uint_var() <14> except BufferReadError: <15> break <16> consumed = buf.tell() <17> <18> if stream.stream_type == StreamType.CONTROL: <19> assert self._peer_control_stream_id is None <20> self._peer_control_stream_id = stream_id <21> elif stream.stream_type == StreamType.QPACK_DECODER: <22> assert self._peer_decoder_stream_id is None <23> self._peer_decoder_stream_id = stream_id <24> elif stream.stream_type == StreamType.QPACK_ENCODER: <25> assert self._peer_encoder_stream_id is None <26> self._peer_encoder_stream_id = stream_id <27> <28> if stream_id == self._peer_control_stream_id: <29> # fetch next frame <30> try: <31> frame_type = buf.pull_uint_var() <32> frame_length = buf.pull_uint_var() <33> frame_data = buf.pull_bytes(frame_length) <34> except BufferReadError: <35> break <36> consumed = buf.tell() <37> <38> # unidirectional control stream <39> if frame_type == FrameType.SETTINGS: <40> settings =</s>
===========below chunk 0=========== # module: aioquic.h3.connection class H3Connection: + def _receive_stream_data_uni(self, stream_id: int, data: bytes) -> List[HttpEvent]: - def _receive_stream_data_uni(self, stream_id: int, data: bytes) -> List[Event]: # offset: 1 encoder = self._encoder.apply_settings( max_table_capacity=settings.get( Setting.QPACK_MAX_TABLE_CAPACITY, 0 ), blocked_streams=settings.get(Setting.QPACK_BLOCKED_STREAMS, 0), ) self._quic.send_stream_data(self._local_encoder_stream_id, encoder) else: # fetch unframed data data = buf.pull_bytes(buf.capacity - buf.tell()) consumed = buf.tell() if stream_id == self._peer_decoder_stream_id: self._encoder.feed_decoder(data) elif stream_id == self._peer_encoder_stream_id: unblocked_streams.update(self._decoder.feed_encoder(data)) # remove processed data from buffer stream.buffer = stream.buffer[consumed:] # process unblocked streams for stream_id in unblocked_streams: stream = self._stream[stream_id] decoder, headers = self._decoder.resume_header(stream_id) stream.blocked = False cls = ResponseReceived if self._is_client else RequestReceived http_events.append( cls( headers=headers, stream_id=stream_id, stream_ended=stream.ended and not stream.buffer, ) ) http_events.extend( self._receive_stream_data_bidi(stream_id, b"", stream.ended) ) return http_events ===========unchanged ref 0=========== at: aioquic._buffer BufferReadError(*args: object) Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer eof() -> bool tell() -> int pull_bytes(length: int) -> bytes pull_uint_var() -> int at: aioquic.h3.connection FrameType(x: Union[str, bytes, bytearray], base: int) FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Setting(x: Union[str, bytes, bytearray], base: int) Setting(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, bytearray], base: int) parse_settings(data: bytes) -> Dict[int, int] at: aioquic.h3.connection.H3Connection _receive_stream_data_bidi(self, stream_id: int, data: bytes, stream_ended: bool) -> List[HttpEvent] _receive_stream_data_bidi(stream_id: int, data: bytes, stream_ended: bool) -> List[HttpEvent] at: aioquic.h3.connection.H3Connection.__init__ self._is_client = quic.configuration.is_client self._quic = quic self._decoder = Decoder(self._max_table_capacity, self._blocked_streams) self._encoder = Encoder() self._stream: Dict[int, H3Stream] = {} self._local_encoder_stream_id: Optional[int] = None self._peer_control_stream_id: Optional[int] = None self._peer_decoder_stream_id: Optional[int] = None self._peer_encoder_stream_id: Optional[int] = None ===========unchanged ref 1=========== at: aioquic.h3.connection.H3Connection._init_connection self._local_encoder_stream_id = self._create_uni_stream( StreamType.QPACK_ENCODER ) at: aioquic.h3.events HttpEvent() RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.quic.connection.QuicConnection send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None at: typing List = _alias(list, 1, inst=False, name='List') Set = _alias(set, 1, inst=False, name='Set') at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co] ===========changed ref 0=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data_bidi( self, stream_id: int, data: bytes, stream_ended: bool + ) -> List[HttpEvent]: - ) -> List[Event]: """ Client-initiated bidirectional streams carry requests and responses. """ + http_events: List[HttpEvent] = [] - http_events: List[Event] = [] stream = self._stream[stream_id] stream.buffer += data if stream_ended: stream.ended = True if stream.blocked: return http_events # shortcut DATA frame bits if ( stream.frame_size is not None and stream.frame_type == FrameType.DATA and len(stream.buffer) < stream.frame_size ): http_events.append( DataReceived( data=stream.buffer, stream_id=stream_id, stream_ended=False ) ) stream.frame_size -= len(stream.buffer) stream.buffer = b"" return http_events # some peers (e.g. f5) end the stream with no data if stream_ended and not stream.buffer: http_events.append( DataReceived(data=b"", stream_id=stream_id, stream_ended=True) ) return http_events buf = Buffer(data=stream.buffer) consumed = 0 while not buf.eof(): # fetch next frame header if stream.frame_size is None: try: stream.frame_type = buf.pull_uint_var() stream.frame_size = buf.pull_uint_var() except BufferReadError: break consumed = buf.tell() # check how much data is available chunk_size = min(stream.frame_size, buf.capacity - consumed) if ( stream.frame_type == FrameType.HEADERS and chunk_size < stream</s>
examples.http3-client/HttpClient.__init__
Modified
aiortc~aioquic
cb553fac2d6c8dd992698aec2655bf846be79ceb
[http] rename Event to HttpEvent
<11>:<add> self._request_events: Dict[int, Deque[HttpEvent]] = {} <del> self._request_events: Dict[int, Deque[Event]] = {} <12>:<add> self._request_waiter: Dict[int, asyncio.Future[Deque[HttpEvent]]] = {} <del> self._request_waiter: Dict[int, asyncio.Future[Deque[Event]]] = {}
# module: examples.http3-client class HttpClient(QuicConnectionProtocol): def __init__( self, *, configuration: QuicConfiguration, server_addr: NetworkAddress, session_ticket_handler: Optional[SessionTicketHandler] = None ): <0> super().__init__( <1> quic=QuicConnection( <2> configuration=configuration, <3> session_ticket_handler=session_ticket_handler, <4> ) <5> ) <6> <7> self._connect_called = False <8> self._http: HttpConnection <9> self._server_addr = server_addr <10> <11> self._request_events: Dict[int, Deque[Event]] = {} <12> self._request_waiter: Dict[int, asyncio.Future[Deque[Event]]] = {} <13> <14> if configuration.alpn_protocols[0].startswith("hq-"): <15> self._http = H0Connection(self._quic) <16> else: <17> self._http = H3Connection(self._quic) <18>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol __init__(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) __init__(self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._quic = quic at: aioquic.h0.connection H0Connection(quic: QuicConnection) at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.events HttpEvent() at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.quic.connection NetworkAddress = Any ===========unchanged ref 1=========== QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.tls SessionTicketHandler = Callable[[SessionTicket], None] at: asyncio.futures Future(*, loop: Optional[AbstractEventLoop]=...) Future = _CFuture = _asyncio.Future at: examples.http3-client HttpConnection = Union[H0Connection, H3Connection] at: examples.http3-client.HttpClient.get self._connect_called = True at: typing Deque = _alias(collections.deque, 1, name='Deque') Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: aioquic.h3.events - class Event: - """ - Base class for HTTP/3 events. - """ - - pass - ===========changed ref 1=========== # module: aioquic.h3.events - class Event: - """ - Base class for HTTP/3 events. - """ - - pass - ===========changed ref 2=========== # module: aioquic.h0.connection class H0Connection: + def handle_event(self, event: QuicEvent) -> List[HttpEvent]: - def handle_event(self, event: QuicEvent) -> List[Event]: + http_events: List[HttpEvent] = [] - http_events: List[Event] = [] if isinstance(event, StreamDataReceived) and (event.stream_id % 4) == 0: data = event.data if not self._headers_received.get(event.stream_id, False): if self._is_client: http_events.append( ResponseReceived( headers=[], stream_ended=False, stream_id=event.stream_id ) ) else: method, path = data.rstrip().split(b" ", 1) http_events.append( RequestReceived( headers=[(b":method", method), (b":path", path)], stream_ended=False, stream_id=event.stream_id, ) ) data = b"" self._headers_received[event.stream_id] = True http_events.append( DataReceived( data=data, stream_ended=event.end_stream, stream_id=event.stream_id ) ) return http_events ===========changed ref 3=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data_bidi( self, stream_id: int, data: bytes, stream_ended: bool + ) -> List[HttpEvent]: - ) -> List[Event]: """ Client-initiated bidirectional streams carry requests and responses. """ + http_events: List[HttpEvent] = [] - http_events: List[Event] = [] stream = self._stream[stream_id] stream.buffer += data if stream_ended: stream.ended = True if stream.blocked: return http_events # shortcut DATA frame bits if ( stream.frame_size is not None and stream.frame_type == FrameType.DATA and len(stream.buffer) < stream.frame_size ): http_events.append( DataReceived( data=stream.buffer, stream_id=stream_id, stream_ended=False ) ) stream.frame_size -= len(stream.buffer) stream.buffer = b"" return http_events # some peers (e.g. f5) end the stream with no data if stream_ended and not stream.buffer: http_events.append( DataReceived(data=b"", stream_id=stream_id, stream_ended=True) ) return http_events buf = Buffer(data=stream.buffer) consumed = 0 while not buf.eof(): # fetch next frame header if stream.frame_size is None: try: stream.frame_type = buf.pull_uint_var() stream.frame_size = buf.pull_uint_var() except BufferReadError: break consumed = buf.tell() # check how much data is available chunk_size = min(stream.frame_size, buf.capacity - consumed) if ( stream.frame_type == FrameType.HEADERS and chunk_size < stream</s>
examples.http3-server/HttpServerProtocol.quic_event_received
Modified
aiortc~aioquic
cb553fac2d6c8dd992698aec2655bf846be79ceb
[http] rename Event to HttpEvent
<20>:<add> self.http_event_received(http_event) <del> self.handle_http_event(http_event)
# module: examples.http3-server class HttpServerProtocol(QuicConnectionProtocol): def quic_event_received(self, event: QuicEvent): <0> if isinstance(event, aioquic.quic.events.ConnectionTerminated): <1> # remove the connection <2> for cid, protocol in list(self._server._protocols.items()): <3> if protocol == self: <4> del self._server._protocols[cid] <5> return <6> elif isinstance(event, aioquic.quic.events.ProtocolNegotiated): <7> if event.alpn_protocol == "h3-22": <8> self._http = H3Connection(self._quic) <9> elif event.alpn_protocol == "hq-22": <10> self._http = H0Connection(self._quic) <11> elif isinstance(event, aioquic.quic.events.ConnectionIdIssued): <12> self._server._protocols[event.connection_id] = self <13> elif isinstance(event, aioquic.quic.events.ConnectionIdRetired): <14> assert self._server._protocols[event.connection_id] == self <15> del self._server._protocols[event.connection_id] <16> <17> #  pass event to the HTTP layer <18> if self._http is not None: <19> for http_event in self._http.handle_event(event): <20> self.handle_http_event(http_event) <21>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol quic_event_received(self, event: events.QuicEvent) -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._quic = quic at: aioquic.h0.connection H0Connection(quic: QuicConnection) at: aioquic.h0.connection.H0Connection handle_event(event: QuicEvent) -> List[HttpEvent] at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection handle_event(event: QuicEvent) -> List[HttpEvent] at: aioquic.quic.events QuicEvent() ConnectionIdIssued(connection_id: bytes) ConnectionIdRetired(connection_id: bytes) ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str) ProtocolNegotiated(alpn_protocol: Optional[str]) at: examples.http3-server.HttpServer.__init__ self._protocols: Dict[bytes, QuicConnectionProtocol] = {} at: examples.http3-server.HttpServerProtocol http_event_received(event: HttpEvent) -> None at: examples.http3-server.HttpServerProtocol.__init__ self._http: Optional[HttpConnection] = None self._server = server ===========changed ref 0=========== # module: aioquic.h0.connection class H0Connection: + def handle_event(self, event: QuicEvent) -> List[HttpEvent]: - def handle_event(self, event: QuicEvent) -> List[Event]: + http_events: List[HttpEvent] = [] - http_events: List[Event] = [] if isinstance(event, StreamDataReceived) and (event.stream_id % 4) == 0: data = event.data if not self._headers_received.get(event.stream_id, False): if self._is_client: http_events.append( ResponseReceived( headers=[], stream_ended=False, stream_id=event.stream_id ) ) else: method, path = data.rstrip().split(b" ", 1) http_events.append( RequestReceived( headers=[(b":method", method), (b":path", path)], stream_ended=False, stream_id=event.stream_id, ) ) data = b"" self._headers_received[event.stream_id] = True http_events.append( DataReceived( data=data, stream_ended=event.end_stream, stream_id=event.stream_id ) ) return http_events ===========changed ref 1=========== # module: aioquic.h3.events - class Event: - """ - Base class for HTTP/3 events. - """ - - pass - ===========changed ref 2=========== # module: aioquic.h3.events - class Event: - """ - Base class for HTTP/3 events. - """ - - pass - ===========changed ref 3=========== # module: examples.http3-client class HttpClient(QuicConnectionProtocol): def __init__( self, *, configuration: QuicConfiguration, server_addr: NetworkAddress, session_ticket_handler: Optional[SessionTicketHandler] = None ): super().__init__( quic=QuicConnection( configuration=configuration, session_ticket_handler=session_ticket_handler, ) ) self._connect_called = False self._http: HttpConnection self._server_addr = server_addr + self._request_events: Dict[int, Deque[HttpEvent]] = {} - self._request_events: Dict[int, Deque[Event]] = {} + self._request_waiter: Dict[int, asyncio.Future[Deque[HttpEvent]]] = {} - self._request_waiter: Dict[int, asyncio.Future[Deque[Event]]] = {} if configuration.alpn_protocols[0].startswith("hq-"): self._http = H0Connection(self._quic) else: self._http = H3Connection(self._quic) ===========changed ref 4=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data_bidi( self, stream_id: int, data: bytes, stream_ended: bool + ) -> List[HttpEvent]: - ) -> List[Event]: """ Client-initiated bidirectional streams carry requests and responses. """ + http_events: List[HttpEvent] = [] - http_events: List[Event] = [] stream = self._stream[stream_id] stream.buffer += data if stream_ended: stream.ended = True if stream.blocked: return http_events # shortcut DATA frame bits if ( stream.frame_size is not None and stream.frame_type == FrameType.DATA and len(stream.buffer) < stream.frame_size ): http_events.append( DataReceived( data=stream.buffer, stream_id=stream_id, stream_ended=False ) ) stream.frame_size -= len(stream.buffer) stream.buffer = b"" return http_events # some peers (e.g. f5) end the stream with no data if stream_ended and not stream.buffer: http_events.append( DataReceived(data=b"", stream_id=stream_id, stream_ended=True) ) return http_events buf = Buffer(data=stream.buffer) consumed = 0 while not buf.eof(): # fetch next frame header if stream.frame_size is None: try: stream.frame_type = buf.pull_uint_var() stream.frame_size = buf.pull_uint_var() except BufferReadError: break consumed = buf.tell() # check how much data is available chunk_size = min(stream.frame_size, buf.capacity - consumed) if ( stream.frame_type == FrameType.HEADERS and chunk_size < stream</s>
aioquic.quic.connection/QuicConnection.connect
Modified
aiortc~aioquic
59e9a17d1d538135021a3923c7560fed0aaee65b
[connection] remove protocol_version argument from connect()
<10>:<del> :param protocol_version: An optional QUIC protocol version. <18>:<del> if protocol_version is not None: <19>:<del> self._version = protocol_version <20>:<del> else: <21>:<add> self._version = self._configuration.supported_versions[0] <del> self._version = max(self._configuration.supported_versions)
# module: aioquic.quic.connection class QuicConnection: - def connect( - self, addr: NetworkAddress, now: float, protocol_version: Optional[int] = None - ) -> None: + def connect(self, addr: NetworkAddress, now: float) -> None: <0> """ <1> Initiate the TLS handshake. <2> <3> This method can only be called for clients and a single time. <4> <5> After calling this method call :meth:`datagrams_to_send` to retrieve data <6> which needs to be sent. <7> <8> :param addr: The network address of the remote peer. <9> :param now: The current time. <10> :param protocol_version: An optional QUIC protocol version. <11> """ <12> assert ( <13> self._is_client and not self._connect_called <14> ), "connect() can only be called for clients and a single time" <15> self._connect_called = True <16> <17> self._network_paths = [QuicNetworkPath(addr, is_validated=True)] <18> if protocol_version is not None: <19> self._version = protocol_version <20> else: <21> self._version = max(self._configuration.supported_versions) <22> self._connect(now=now) <23>
===========unchanged ref 0=========== at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.quic.connection NetworkAddress = Any QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None) at: aioquic.quic.connection.QuicConnection _connect(now: float) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._configuration = configuration self._is_client = configuration.is_client self._connect_called = False self._network_paths: List[QuicNetworkPath] = [] self._version: Optional[int] = None at: aioquic.quic.connection.QuicConnection.receive_datagram self._version = QuicProtocolVersion(header.version) self._version = QuicProtocolVersion(max(common)) self._network_paths = [network_path] at: aioquic.quic.connection.QuicNetworkPath addr: NetworkAddress bytes_received: int = 0 bytes_sent: int = 0 is_validated: bool = False local_challenge: Optional[bytes] = None remote_challenge: Optional[bytes] = None ===========unchanged ref 1=========== at: typing Tuple = _TupleType(tuple, -1, inst=False, name='Tuple') List = _alias(list, 1, inst=False, name='List')
aioquic.asyncio.protocol/QuicConnectionProtocol.connect
Modified
aiortc~aioquic
59e9a17d1d538135021a3923c7560fed0aaee65b
[connection] remove protocol_version argument from connect()
<5>:<del> self._quic.connect( <6>:<del> addr, now=self._loop.time(), protocol_version=protocol_version <7>:<del> ) <8>:<add> self._quic.connect(addr, now=self._loop.time())
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): + def connect(self, addr: NetworkAddress) -> None: - def connect(self, addr: NetworkAddress, protocol_version: int) -> None: <0> """ <1> Initiate the TLS handshake. <2> <3> This method can only be called for clients and a single time. <4> """ <5> self._quic.connect( <6> addr, now=self._loop.time(), protocol_version=protocol_version <7> ) <8> self._send_pending() <9>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol _send_pending() -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._loop = loop self._quic = quic at: aioquic.quic.connection NetworkAddress = Any at: aioquic.quic.connection.QuicConnection connect(addr: NetworkAddress, now: float) -> None at: asyncio.events.AbstractEventLoop time() -> float ===========changed ref 0=========== # module: aioquic.quic.connection class QuicConnection: - def connect( - self, addr: NetworkAddress, now: float, protocol_version: Optional[int] = None - ) -> None: + def connect(self, addr: NetworkAddress, now: float) -> None: """ Initiate the TLS handshake. This method can only be called for clients and a single time. After calling this method call :meth:`datagrams_to_send` to retrieve data which needs to be sent. :param addr: The network address of the remote peer. :param now: The current time. - :param protocol_version: An optional QUIC protocol version. """ assert ( self._is_client and not self._connect_called ), "connect() can only be called for clients and a single time" self._connect_called = True self._network_paths = [QuicNetworkPath(addr, is_validated=True)] - if protocol_version is not None: - self._version = protocol_version - else: + self._version = self._configuration.supported_versions[0] - self._version = max(self._configuration.supported_versions) self._connect(now=now)
aioquic.asyncio.client/connect
Modified
aiortc~aioquic
59e9a17d1d538135021a3923c7560fed0aaee65b
[connection] remove protocol_version argument from connect()
<s>] = None, - protocol_version: Optional[int] = None, quic_logger: Optional[QuicLogger] = None, secrets_log_file: Optional[TextIO] = None, session_ticket: Optional[SessionTicket] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, + supported_versions: Optional[List[int]] = None, ) -> AsyncGenerator[QuicConnectionProtocol, None]: <0> """ <1> Connect to a QUIC server at the given `host` and `port`. <2> <3> :meth:`connect()` returns an awaitable. Awaiting it yields a <4> :class:`~aioquic.asyncio.QuicConnectionProtocol` which can be used to <5> create streams. <6> <7> :func:`connect` also accepts the following optional arguments: <8> <9> * ``alpn_protocols`` is a list of ALPN protocols to offer in the <10> ClientHello. <11> * ``secrets_log_file`` is a file-like object in which to log traffic <12> secrets. This is useful to analyze traffic captures with Wireshark. <13> * ``session_ticket`` is a TLS session ticket which should be used for <14> resumption. <15> * ``session_ticket_handler`` is a callback which is invoked by the TLS <16> engine when a new session ticket is received. <17> * ``stream_handler`` is a callback which is invoked whenever a stream is <18> created. It must accept two arguments: a :class:`asyncio.StreamReader` <19> and a :class:`asyncio.StreamWriter`. <20> """ <21> loop = asyncio.get_event_loop() <22> <23> # if host is not an IP address, pass it to enable SNI <24> try: <25> ipaddress.ip_address(host) <26> server_name = None <27> except ValueError: <28> server_name = host <29> <30> # lookup remote address <31> infos = await loop.getaddrinfo(host, port, type=socket.SOCK_DGRAM) <32> addr</s>
===========below chunk 0=========== <s> <del> protocol_version: Optional[int] = None, quic_logger: Optional[QuicLogger] = None, secrets_log_file: Optional[TextIO] = None, session_ticket: Optional[SessionTicket] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, + supported_versions: Optional[List[int]] = None, ) -> AsyncGenerator[QuicConnectionProtocol, None]: # offset: 1 if len(addr) == 2: addr = ("::ffff:" + addr[0], addr[1], 0, 0) configuration = QuicConfiguration( alpn_protocols=alpn_protocols, is_client=True, quic_logger=quic_logger, secrets_log_file=secrets_log_file, server_name=server_name, session_ticket=session_ticket, ) if idle_timeout is not None: configuration.idle_timeout = idle_timeout connection = QuicConnection( configuration=configuration, session_ticket_handler=session_ticket_handler ) # connect _, protocol = await loop.create_datagram_endpoint( lambda: QuicConnectionProtocol(connection, stream_handler=stream_handler), local_addr=("::", 0), ) protocol = cast(QuicConnectionProtocol, protocol) protocol.connect(addr, protocol_version) await protocol.wait_connected() try: yield protocol finally: protocol.close() await protocol.wait_closed() ===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.asyncio.compat asynccontextmanager = _asynccontextmanager asynccontextmanager = None at: aioquic.asyncio.protocol QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None] QuicConnectionProtocol(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.asyncio.protocol.QuicConnectionProtocol connect(addr: NetworkAddress, protocol_version: int) -> None wait_connected() -> None at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) ===========unchanged ref 1=========== at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.quic.logger QuicLogger() at: aioquic.tls SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) SessionTicketHandler = Callable[[SessionTicket], None] at: asyncio.events get_event_loop() -> AbstractEventLoop at: asyncio.events.AbstractEventLoop getaddrinfo(host: Optional[str], port: Union[str, int, None], *, family: int=..., type: int=..., proto: int=..., flags: int=...) -> List[Tuple[AddressFamily, SocketKind, int, str, Union[Tuple[str, int], Tuple[str, int, int, int]]]] create_datagram_endpoint(protocol_factory: _ProtocolFactory, local_addr: Optional[Tuple[str, int]]=..., remote_addr: Optional[Tuple[str, int]]=..., *, family: int=..., proto: int=..., flags: int=..., reuse_address: Optional[bool]=..., reuse_port: Optional[bool]=..., allow_broadcast: Optional[bool]=..., sock: Optional[socket]=...) -> _TransProtPair at: contextlib asynccontextmanager(func: Callable[..., AsyncIterator[_T]]) -> Callable[..., AsyncContextManager[_T]] at: ipaddress ip_address(address: object) -> Any at: socket SOCK_DGRAM: SocketKind ===========unchanged ref 2=========== at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any List = _alias(list, 1, inst=False, name='List') AsyncGenerator = _alias(collections.abc.AsyncGenerator, 2) TextIO() ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): + def connect(self, addr: NetworkAddress) -> None: - def connect(self, addr: NetworkAddress, protocol_version: int) -> None: """ Initiate the TLS handshake. This method can only be called for clients and a single time. """ - self._quic.connect( - addr, now=self._loop.time(), protocol_version=protocol_version - ) + self._quic.connect(addr, now=self._loop.time()) self._send_pending() ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: - def connect( - self, addr: NetworkAddress, now: float, protocol_version: Optional[int] = None - ) -> None: + def connect(self, addr: NetworkAddress, now: float) -> None: """ Initiate the TLS handshake. This method can only be called for clients and a single time. After calling this method call :meth:`datagrams_to_send` to retrieve data which needs to be sent. :param addr: The network address of the remote peer. :param now: The current time. - :param protocol_version: An optional QUIC protocol version. """ assert ( self._is_client and not self._connect_called ), "connect() can only be called for clients and a single time" self._connect_called = True self._network_paths = [QuicNetworkPath(addr, is_validated=True)] - if protocol_version is not None: - self._version = protocol_version - else: + self._version = self._configuration.supported_versions[0] - self._version = max(self._configuration.supported_versions) self._connect(now=now)
tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_version_negotiation
Modified
aiortc~aioquic
59e9a17d1d538135021a3923c7560fed0aaee65b
[connection] remove protocol_version argument from connect()
<4>:<add> "127.0.0.1", <add> quic_logger=QuicLogger(), <add> supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_22], <del> "127.0.0.1", protocol_version=0x1A2A3A4A, quic_logger=QuicLogger()
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_version_negotiation(self): <0> server, response = run( <1> asyncio.gather( <2> run_server(), <3> run_client( <4> "127.0.0.1", protocol_version=0x1A2A3A4A, quic_logger=QuicLogger() <5> ), <6> ) <7> ) <8> self.assertEqual(response, b"gnip") <9> server.close() <10>
===========unchanged ref 0=========== at: aioquic.quic.logger QuicLogger() at: aioquic.quic.packet QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) ===========unchanged ref 1=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 2=========== at: tests.test_asyncio run_client(host, port=4433, request=b"ping", *, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None) at: tests.utils run(coro) ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): + def connect(self, addr: NetworkAddress) -> None: - def connect(self, addr: NetworkAddress, protocol_version: int) -> None: """ Initiate the TLS handshake. This method can only be called for clients and a single time. """ - self._quic.connect( - addr, now=self._loop.time(), protocol_version=protocol_version - ) + self._quic.connect(addr, now=self._loop.time()) self._send_pending() ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: - def connect( - self, addr: NetworkAddress, now: float, protocol_version: Optional[int] = None - ) -> None: + def connect(self, addr: NetworkAddress, now: float) -> None: """ Initiate the TLS handshake. This method can only be called for clients and a single time. After calling this method call :meth:`datagrams_to_send` to retrieve data which needs to be sent. :param addr: The network address of the remote peer. :param now: The current time. - :param protocol_version: An optional QUIC protocol version. """ assert ( self._is_client and not self._connect_called ), "connect() can only be called for clients and a single time" self._connect_called = True self._network_paths = [QuicNetworkPath(addr, is_validated=True)] - if protocol_version is not None: - self._version = protocol_version - else: + self._version = self._configuration.supported_versions[0] - self._version = max(self._configuration.supported_versions) self._connect(now=now) ===========changed ref 2=========== <s>] = None, - protocol_version: Optional[int] = None, quic_logger: Optional[QuicLogger] = None, secrets_log_file: Optional[TextIO] = None, session_ticket: Optional[SessionTicket] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, + supported_versions: Optional[List[int]] = None, ) -> AsyncGenerator[QuicConnectionProtocol, None]: """ Connect to a QUIC server at the given `host` and `port`. :meth:`connect()` returns an awaitable. Awaiting it yields a :class:`~aioquic.asyncio.QuicConnectionProtocol` which can be used to create streams. :func:`connect` also accepts the following optional arguments: * ``alpn_protocols`` is a list of ALPN protocols to offer in the ClientHello. * ``secrets_log_file`` is a file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. * ``session_ticket`` is a TLS session ticket which should be used for resumption. * ``session_ticket_handler`` is a callback which is invoked by the TLS engine when a new session ticket is received. * ``stream_handler`` is a callback which is invoked whenever a stream is created. It must accept two arguments: a :class:`asyncio.StreamReader` and a :class:`asyncio.StreamWriter`. """ loop = asyncio.get_event_loop() # if host is not an IP address, pass it to enable SNI try: ipaddress.ip_address(host) server_name = None except ValueError: server_name = host # lookup remote address infos = await loop.getaddrinfo(host, port, type=socket.SOCK_DGRAM) addr = infos[0][4] if len(addr) == 2: addr = ("::ffff:" + addr[0], addr[1</s>
examples.interop/test_version_negotiation
Modified
aiortc~aioquic
59e9a17d1d538135021a3923c7560fed0aaee65b
[connection] remove protocol_version argument from connect()
<1>:<add> config.host, <add> config.port, <add> supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_22], <add> **kwargs <del> config.host, config.port, protocol_version=0x1A2A3A4A, **kwargs
# module: examples.interop def test_version_negotiation(config, **kwargs): <0> async with connect( <1> config.host, config.port, protocol_version=0x1A2A3A4A, **kwargs <2> ) as connection: <3> await connection.ping() <4> if connection._quic._version_negotiation_count == 1: <5> config.result |= Result.V <6>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] connect(*args, **kwds) at: aioquic.quic.packet QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) ===========changed ref 0=========== <s>] = None, - protocol_version: Optional[int] = None, quic_logger: Optional[QuicLogger] = None, secrets_log_file: Optional[TextIO] = None, session_ticket: Optional[SessionTicket] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, + supported_versions: Optional[List[int]] = None, ) -> AsyncGenerator[QuicConnectionProtocol, None]: """ Connect to a QUIC server at the given `host` and `port`. :meth:`connect()` returns an awaitable. Awaiting it yields a :class:`~aioquic.asyncio.QuicConnectionProtocol` which can be used to create streams. :func:`connect` also accepts the following optional arguments: * ``alpn_protocols`` is a list of ALPN protocols to offer in the ClientHello. * ``secrets_log_file`` is a file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. * ``session_ticket`` is a TLS session ticket which should be used for resumption. * ``session_ticket_handler`` is a callback which is invoked by the TLS engine when a new session ticket is received. * ``stream_handler`` is a callback which is invoked whenever a stream is created. It must accept two arguments: a :class:`asyncio.StreamReader` and a :class:`asyncio.StreamWriter`. """ loop = asyncio.get_event_loop() # if host is not an IP address, pass it to enable SNI try: ipaddress.ip_address(host) server_name = None except ValueError: server_name = host # lookup remote address infos = await loop.getaddrinfo(host, port, type=socket.SOCK_DGRAM) addr = infos[0][4] if len(addr) == 2: addr = ("::ffff:" + addr[0], addr[1</s> ===========changed ref 1=========== <s> <del> protocol_version: Optional[int] = None, quic_logger: Optional[QuicLogger] = None, secrets_log_file: Optional[TextIO] = None, session_ticket: Optional[SessionTicket] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, + supported_versions: Optional[List[int]] = None, ) -> AsyncGenerator[QuicConnectionProtocol, None]: # offset: 1 <s>0][4] if len(addr) == 2: addr = ("::ffff:" + addr[0], addr[1], 0, 0) configuration = QuicConfiguration( alpn_protocols=alpn_protocols, is_client=True, quic_logger=quic_logger, secrets_log_file=secrets_log_file, server_name=server_name, session_ticket=session_ticket, ) if idle_timeout is not None: configuration.idle_timeout = idle_timeout + if supported_versions is not None: + configuration.supported_versions = supported_versions connection = QuicConnection( configuration=configuration, session_ticket_handler=session_ticket_handler ) # connect _, protocol = await loop.create_datagram_endpoint( lambda: QuicConnectionProtocol(connection, stream_handler=stream_handler), local_addr=("::", 0), ) protocol = cast(QuicConnectionProtocol, protocol) + protocol.connect(addr) - protocol.connect(addr, protocol_version) await protocol.wait_connected() try: yield protocol finally: protocol.close() await protocol.wait_closed() ===========changed ref 2=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): + def connect(self, addr: NetworkAddress) -> None: - def connect(self, addr: NetworkAddress, protocol_version: int) -> None: """ Initiate the TLS handshake. This method can only be called for clients and a single time. """ - self._quic.connect( - addr, now=self._loop.time(), protocol_version=protocol_version - ) + self._quic.connect(addr, now=self._loop.time()) self._send_pending() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_version_negotiation(self): server, response = run( asyncio.gather( run_server(), run_client( + "127.0.0.1", + quic_logger=QuicLogger(), + supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_22], - "127.0.0.1", protocol_version=0x1A2A3A4A, quic_logger=QuicLogger() ), ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 4=========== # module: aioquic.quic.connection class QuicConnection: - def connect( - self, addr: NetworkAddress, now: float, protocol_version: Optional[int] = None - ) -> None: + def connect(self, addr: NetworkAddress, now: float) -> None: """ Initiate the TLS handshake. This method can only be called for clients and a single time. After calling this method call :meth:`datagrams_to_send` to retrieve data which needs to be sent. :param addr: The network address of the remote peer. :param now: The current time. - :param protocol_version: An optional QUIC protocol version. """ assert ( self._is_client and not self._connect_called ), "connect() can only be called for clients and a single time" self._connect_called = True self._network_paths = [QuicNetworkPath(addr, is_validated=True)] - if protocol_version is not None: - self._version = protocol_version - else: + self._version = self._configuration.supported_versions[0] - self._version = max(self._configuration.supported_versions) self._connect(now=now)
aioquic.quic.connection/QuicConnection.__init__
Modified
aiortc~aioquic
b1726533664f07af26f63f561be78628c245d897
[interop] use QLOG to check for version negotiation and retry
<15>:<del> self._version_negotiation_count = 0
# module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: <0> if configuration.is_client: <1> assert ( <2> original_connection_id is None <3> ), "Cannot set original_connection_id for a client" <4> else: <5> assert ( <6> configuration.certificate is not None <7> ), "SSL certificate is required for a server" <8> assert ( <9> configuration.private_key is not None <10> ), "SSL private key is required for a server" <11> <12> # counters for debugging <13> self._quic_logger = configuration.quic_logger <14> self._stateless_retry_count = 0 <15> self._version_negotiation_count = 0 <16> <17> # configuration <18> self._configuration = configuration <19> self._is_client = configuration.is_client <20> <21> self._ack_delay = K_GRANULARITY <22> self._close_at: Optional[float] = None <23> self._close_event: Optional[events.ConnectionTerminated] = None <24> self._connect_called = False <25> self._cryptos: Dict[tls.Epoch, CryptoPair] = {} <26> self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} <27> self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} <28> self._events: Deque[events.QuicEvent] = deque() <29> self._handshake_complete = False <30> self._handshake_confirmed = False <31> self._host_cids = [ <32> QuicConnectionId( <33> cid=os.urandom(8), <34> sequence_number=0, <35> stateless_reset_token=os.urandom(16), <36> was_sent=</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 1 ) ] self.host_cid = self._host_cids[0].cid self._host_cid_seq = 1 self._local_active_connection_id_limit = 8 self._local_max_data = MAX_DATA_WINDOW self._local_max_data_sent = MAX_DATA_WINDOW self._local_max_data_used = 0 self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW self._local_max_stream_data_uni = MAX_DATA_WINDOW self._local_max_streams_bidi = 128 self._local_max_streams_uni = 128 self._logger = QuicConnectionAdapter( logger, {"host_cid": dump_cid(self.host_cid)} ) self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) self._loss_at: Optional[float] = None self._network_paths: List[QuicNetworkPath] = [] self._original_connection_id = original_connection_id self._packet_number = 0 self._parameters_received = False self._peer_cid = os.urandom(8) self._peer_cid_seq: Optional[int] = None self._peer_cid_available: List[QuicConnectionId] = [] self._peer_token = b"" self._</s> ===========below chunk 1=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 2 <s>._peer_cid_available: List[QuicConnectionId] = [] self._peer_token = b"" self._remote_active_connection_id_limit = 0 self._remote_idle_timeout = 0.0 # seconds self._remote_max_data = 0 self._remote_max_data_used = 0 self._remote_max_stream_data_bidi_local = 0 self._remote_max_stream_data_bidi_remote = 0 self._remote_max_stream_data_uni = 0 self._remote_max_streams_bidi = 0 self._remote_max_streams_uni = 0 self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._spin_bit = False self._spin_bit_peer = False self._spin_highest_pn = 0 self._state = QuicConnectionState.FIRSTFLIGHT self._streams: Dict[int, QuicStream] = {} self._streams_blocked_bidi: List[QuicStream] = [] self._streams_blocked_uni: List[QuicStream] = [] self._version: Optional[int] = None # things to send self._close_pending = False self._ping_pending: List[int] = [] self._probe_pending = False self._retire_connection_ids: List[int] = [] self._streams_blocked_pending = False # callbacks self._session_ticket_</s> ===========below chunk 2=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 3 <s> = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler # frame handlers self.__frame_handlers = [ (self._handle_padding_frame, EPOCHS("IZHO")), (self._handle_padding_frame, EPOCHS("ZO")), (self._handle_ack_frame, EPOCHS("IHO")), (self._handle_ack_frame, EPOCHS("IHO")), (self._handle_reset_stream_frame, EPOCHS("ZO")), (self._handle_stop_sending_frame, EPOCHS("ZO")), (self._handle_crypto_frame, EPOCHS("IHO")), (self._handle_new_token_frame, EPOCHS("O")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_max_data_frame, EPOCHS("ZO")), (self</s> ===========below chunk 3=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 4 <s>_max_stream_data_frame, EPOCHS("ZO")), (self._handle_max_streams_bidi_frame, EPOCHS("ZO")), (self._handle_max_streams_uni_frame, EPOCHS("ZO")), (self._handle_data_blocked_frame, EPOCHS("ZO")), (self._handle_stream_data_blocked_frame, EPOCHS("ZO")), (self._handle_streams_blocked_frame, EPOCHS("ZO")), (self._handle_streams_blocked_frame, EPOCHS("ZO")), (self._handle_new_connection_id_frame, EPOCHS("ZO")), (self._handle_retire_connection_id_frame, EPOCHS("O")), (self._handle_path_challenge_frame, EPOCHS("ZO")), (self._handle_path_response_frame, EPOCHS("O")), (self._handle_connection_close_frame, EPOCHS("IZHO")), (self._handle_connection_close_frame, EPOCHS("ZO")), ]
examples.interop/test_version_negotiation
Modified
aiortc~aioquic
b1726533664f07af26f63f561be78628c245d897
[interop] use QLOG to check for version negotiation and retry
<0>:<add> quic_logger = QuicLogger() <3>:<add> quic_logger=quic_logger, <7>:<del> if connection._quic._version_negotiation_count == 1: <8>:<del> config.result |= Result.V
# module: examples.interop def test_version_negotiation(config, **kwargs): <0> async with connect( <1> config.host, <2> config.port, <3> supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_22], <4> **kwargs <5> ) as connection: <6> await connection.ping() <7> if connection._quic._version_negotiation_count == 1: <8> config.result |= Result.V <9>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(*args, **kwds) connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None, supported_versions: Optional[List[int]]=None) -> AsyncGenerator[QuicConnectionProtocol, None] at: aioquic.quic.logger QuicLogger() at: aioquic.quic.packet QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) ===========changed ref 0=========== # module: aioquic.quic.logger PACKET_TYPE_NAMES = { + PACKET_TYPE_INITIAL: "INITIAL", - PACKET_TYPE_INITIAL: "initial", + PACKET_TYPE_HANDSHAKE: "HANDSHAKE", - PACKET_TYPE_HANDSHAKE: "handshake", PACKET_TYPE_ZERO_RTT: "0RTT", PACKET_TYPE_ONE_RTT: "1RTT", + PACKET_TYPE_RETRY: "RETRY", - PACKET_TYPE_RETRY: "retry", } ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: if configuration.is_client: assert ( original_connection_id is None ), "Cannot set original_connection_id for a client" else: assert ( configuration.certificate is not None ), "SSL certificate is required for a server" assert ( configuration.private_key is not None ), "SSL private key is required for a server" # counters for debugging self._quic_logger = configuration.quic_logger self._stateless_retry_count = 0 - self._version_negotiation_count = 0 # configuration self._configuration = configuration self._is_client = configuration.is_client self._ack_delay = K_GRANULARITY self._close_at: Optional[float] = None self._close_event: Optional[events.ConnectionTerminated] = None self._connect_called = False self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} self._events: Deque[events.QuicEvent] = deque() self._handshake_complete = False self._handshake_confirmed = False self._host_cids = [ QuicConnectionId( cid=os.urandom(8), sequence_number=0, stateless_reset_token=os.urandom(16), was_sent=True, ) ] self.host_cid = self._host_cids[0].cid self._host_cid_seq =</s> ===========changed ref 2=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 1 <s> ] self.host_cid = self._host_cids[0].cid self._host_cid_seq = 1 self._local_active_connection_id_limit = 8 self._local_max_data = MAX_DATA_WINDOW self._local_max_data_sent = MAX_DATA_WINDOW self._local_max_data_used = 0 self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW self._local_max_stream_data_uni = MAX_DATA_WINDOW self._local_max_streams_bidi = 128 self._local_max_streams_uni = 128 self._logger = QuicConnectionAdapter( logger, {"host_cid": dump_cid(self.host_cid)} ) self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) self._loss_at: Optional[float] = None self._network_paths: List[QuicNetworkPath] = [] self._original_connection_id = original_connection_id self._packet_number = 0 self._parameters_received = False self._peer_cid = os.urandom(8) self._peer_cid_seq: Optional[int] = None self</s> ===========changed ref 3=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 2 <s>_cid_available: List[QuicConnectionId] = [] self._peer_token = b"" self._remote_active_connection_id_limit = 0 self._remote_idle_timeout = 0.0 # seconds self._remote_max_data = 0 self._remote_max_data_used = 0 self._remote_max_stream_data_bidi_local = 0 self._remote_max_stream_data_bidi_remote = 0 self._remote_max_stream_data_uni = 0 self._remote_max_streams_bidi = 0 self._remote_max_streams_uni = 0 self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._spin_bit = False self._spin_bit_peer = False self._spin_highest_pn = 0 self._state = QuicConnectionState.FIRSTFLIGHT self._streams: Dict[int, QuicStream] = {} self._streams_blocked_bidi: List[QuicStream] = [] self._streams_blocked_uni: List[QuicStream] = [] self._version: Optional[int] = None # things to send self._close_pending = False self._ping_pending: List[int] = [] self._probe_pending = False self._retire_connection_ids: List[int] = [] self._streams_blocked_pending = False # callbacks self._session_ticket_fetcher</s>
examples.interop/test_stateless_retry
Modified
aiortc~aioquic
b1726533664f07af26f63f561be78628c245d897
[interop] use QLOG to check for version negotiation and retry
<0>:<add> quic_logger = QuicLogger() <add> async with connect( <add> config.host, config.retry_port, quic_logger=quic_logger, **kwargs <add> ) as connection: <del> async with connect(config.host, config.retry_port, **kwargs) as connection: <2>:<del> if connection._quic._stateless_retry_count == 1: <3>:<del> config.result |= Result.S
# module: examples.interop def test_stateless_retry(config, **kwargs): <0> async with connect(config.host, config.retry_port, **kwargs) as connection: <1> await connection.ping() <2> if connection._quic._stateless_retry_count == 1: <3> config.result |= Result.S <4>
===========unchanged ref 0=========== at: examples.interop Result() ===========changed ref 0=========== # module: examples.interop def test_version_negotiation(config, **kwargs): + quic_logger = QuicLogger() async with connect( config.host, config.port, + quic_logger=quic_logger, supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_22], **kwargs ) as connection: await connection.ping() - if connection._quic._version_negotiation_count == 1: - config.result |= Result.V ===========changed ref 1=========== # module: aioquic.quic.logger PACKET_TYPE_NAMES = { + PACKET_TYPE_INITIAL: "INITIAL", - PACKET_TYPE_INITIAL: "initial", + PACKET_TYPE_HANDSHAKE: "HANDSHAKE", - PACKET_TYPE_HANDSHAKE: "handshake", PACKET_TYPE_ZERO_RTT: "0RTT", PACKET_TYPE_ONE_RTT: "1RTT", + PACKET_TYPE_RETRY: "RETRY", - PACKET_TYPE_RETRY: "retry", } ===========changed ref 2=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: if configuration.is_client: assert ( original_connection_id is None ), "Cannot set original_connection_id for a client" else: assert ( configuration.certificate is not None ), "SSL certificate is required for a server" assert ( configuration.private_key is not None ), "SSL private key is required for a server" # counters for debugging self._quic_logger = configuration.quic_logger self._stateless_retry_count = 0 - self._version_negotiation_count = 0 # configuration self._configuration = configuration self._is_client = configuration.is_client self._ack_delay = K_GRANULARITY self._close_at: Optional[float] = None self._close_event: Optional[events.ConnectionTerminated] = None self._connect_called = False self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} self._events: Deque[events.QuicEvent] = deque() self._handshake_complete = False self._handshake_confirmed = False self._host_cids = [ QuicConnectionId( cid=os.urandom(8), sequence_number=0, stateless_reset_token=os.urandom(16), was_sent=True, ) ] self.host_cid = self._host_cids[0].cid self._host_cid_seq =</s> ===========changed ref 3=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 1 <s> ] self.host_cid = self._host_cids[0].cid self._host_cid_seq = 1 self._local_active_connection_id_limit = 8 self._local_max_data = MAX_DATA_WINDOW self._local_max_data_sent = MAX_DATA_WINDOW self._local_max_data_used = 0 self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW self._local_max_stream_data_uni = MAX_DATA_WINDOW self._local_max_streams_bidi = 128 self._local_max_streams_uni = 128 self._logger = QuicConnectionAdapter( logger, {"host_cid": dump_cid(self.host_cid)} ) self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) self._loss_at: Optional[float] = None self._network_paths: List[QuicNetworkPath] = [] self._original_connection_id = original_connection_id self._packet_number = 0 self._parameters_received = False self._peer_cid = os.urandom(8) self._peer_cid_seq: Optional[int] = None self</s> ===========changed ref 4=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 2 <s>_cid_available: List[QuicConnectionId] = [] self._peer_token = b"" self._remote_active_connection_id_limit = 0 self._remote_idle_timeout = 0.0 # seconds self._remote_max_data = 0 self._remote_max_data_used = 0 self._remote_max_stream_data_bidi_local = 0 self._remote_max_stream_data_bidi_remote = 0 self._remote_max_stream_data_uni = 0 self._remote_max_streams_bidi = 0 self._remote_max_streams_uni = 0 self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._spin_bit = False self._spin_bit_peer = False self._spin_highest_pn = 0 self._state = QuicConnectionState.FIRSTFLIGHT self._streams: Dict[int, QuicStream] = {} self._streams_blocked_bidi: List[QuicStream] = [] self._streams_blocked_uni: List[QuicStream] = [] self._version: Optional[int] = None # things to send self._close_pending = False self._ping_pending: List[int] = [] self._probe_pending = False self._retire_connection_ids: List[int] = [] self._streams_blocked_pending = False # callbacks self._session_ticket_fetcher</s>
aioquic.quic.connection/QuicConnection.__init__
Modified
aiortc~aioquic
7883a5f8281e3e76f95e77d55ffc0933223b8568
[interop] use QLOG to monitor spin bit
# module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: <0> if configuration.is_client: <1> assert ( <2> original_connection_id is None <3> ), "Cannot set original_connection_id for a client" <4> else: <5> assert ( <6> configuration.certificate is not None <7> ), "SSL certificate is required for a server" <8> assert ( <9> configuration.private_key is not None <10> ), "SSL private key is required for a server" <11> <12> # counters for debugging <13> self._quic_logger = configuration.quic_logger <14> self._stateless_retry_count = 0 <15> <16> # configuration <17> self._configuration = configuration <18> self._is_client = configuration.is_client <19> <20> self._ack_delay = K_GRANULARITY <21> self._close_at: Optional[float] = None <22> self._close_event: Optional[events.ConnectionTerminated] = None <23> self._connect_called = False <24> self._cryptos: Dict[tls.Epoch, CryptoPair] = {} <25> self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} <26> self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} <27> self._events: Deque[events.QuicEvent] = deque() <28> self._handshake_complete = False <29> self._handshake_confirmed = False <30> self._host_cids = [ <31> QuicConnectionId( <32> cid=os.urandom(8), <33> sequence_number=0, <34> stateless_reset_token=os.urandom(16), <35> was_sent=True, <36> ) <37> ] <38> self</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 1 self._host_cid_seq = 1 self._local_active_connection_id_limit = 8 self._local_max_data = MAX_DATA_WINDOW self._local_max_data_sent = MAX_DATA_WINDOW self._local_max_data_used = 0 self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW self._local_max_stream_data_uni = MAX_DATA_WINDOW self._local_max_streams_bidi = 128 self._local_max_streams_uni = 128 self._logger = QuicConnectionAdapter( logger, {"host_cid": dump_cid(self.host_cid)} ) self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) self._loss_at: Optional[float] = None self._network_paths: List[QuicNetworkPath] = [] self._original_connection_id = original_connection_id self._packet_number = 0 self._parameters_received = False self._peer_cid = os.urandom(8) self._peer_cid_seq: Optional[int] = None self._peer_cid_available: List[QuicConnectionId] = [] self._peer_token = b"" self._remote_active_connection_id_limit = 0 self._remote_idle_timeout = 0.0</s> ===========below chunk 1=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 2 <s> b"" self._remote_active_connection_id_limit = 0 self._remote_idle_timeout = 0.0 # seconds self._remote_max_data = 0 self._remote_max_data_used = 0 self._remote_max_stream_data_bidi_local = 0 self._remote_max_stream_data_bidi_remote = 0 self._remote_max_stream_data_uni = 0 self._remote_max_streams_bidi = 0 self._remote_max_streams_uni = 0 self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._spin_bit = False self._spin_bit_peer = False self._spin_highest_pn = 0 self._state = QuicConnectionState.FIRSTFLIGHT self._streams: Dict[int, QuicStream] = {} self._streams_blocked_bidi: List[QuicStream] = [] self._streams_blocked_uni: List[QuicStream] = [] self._version: Optional[int] = None # things to send self._close_pending = False self._ping_pending: List[int] = [] self._probe_pending = False self._retire_connection_ids: List[int] = [] self._streams_blocked_pending = False # callbacks self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler</s> ===========below chunk 2=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 3 <s> # frame handlers self.__frame_handlers = [ (self._handle_padding_frame, EPOCHS("IZHO")), (self._handle_padding_frame, EPOCHS("ZO")), (self._handle_ack_frame, EPOCHS("IHO")), (self._handle_ack_frame, EPOCHS("IHO")), (self._handle_reset_stream_frame, EPOCHS("ZO")), (self._handle_stop_sending_frame, EPOCHS("ZO")), (self._handle_crypto_frame, EPOCHS("IHO")), (self._handle_new_token_frame, EPOCHS("O")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_max_data_frame, EPOCHS("ZO")), (self._handle_max_stream_data_frame, EPOCHS("ZO")), (self._</s> ===========below chunk 3=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 4 <s>max_streams_bidi_frame, EPOCHS("ZO")), (self._handle_max_streams_uni_frame, EPOCHS("ZO")), (self._handle_data_blocked_frame, EPOCHS("ZO")), (self._handle_stream_data_blocked_frame, EPOCHS("ZO")), (self._handle_streams_blocked_frame, EPOCHS("ZO")), (self._handle_streams_blocked_frame, EPOCHS("ZO")), (self._handle_new_connection_id_frame, EPOCHS("ZO")), (self._handle_retire_connection_id_frame, EPOCHS("O")), (self._handle_path_challenge_frame, EPOCHS("ZO")), (self._handle_path_response_frame, EPOCHS("O")), (self._handle_connection_close_frame, EPOCHS("IZHO")), (self._handle_connection_close_frame, EPOCHS("ZO")), ]
examples.interop/test_spin_bit
Modified
aiortc~aioquic
7883a5f8281e3e76f95e77d55ffc0933223b8568
[interop] use QLOG to monitor spin bit
<0>:<add> quic_logger = QuicLogger() <add> async with connect( <add> config.host, config.port, quic_logger=quic_logger, **kwargs <add> ) as connection: <del> async with connect(config.host, config.port, **kwargs) as connection: <1>:<del> spin_bits = set() <4>:<add> <add> # check log <add> spin_bits = set() <add> for stamp, category, event, data in quic_logger.to_dict()["traces"][0][ <add> "events" <add> ]: <add> if category == "CONNECTIVITY" and event == "SPIN_BIT_UPDATE": <add> spin_bits.add(data["state"]) <del> spin_bits.add(connection._quic._spin_bit_peer)
# module: examples.interop def test_spin_bit(config, **kwargs): <0> async with connect(config.host, config.port, **kwargs) as connection: <1> spin_bits = set() <2> for i in range(5): <3> await connection.ping() <4> spin_bits.add(connection._quic._spin_bit_peer) <5> if len(spin_bits) == 2: <6> config.result |= Result.P <7>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(*args, **kwds) connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None, supported_versions: Optional[List[int]]=None) -> AsyncGenerator[QuicConnectionProtocol, None] at: aioquic.asyncio.protocol.QuicConnectionProtocol ping() -> None at: aioquic.quic.logger QuicLogger() ===========changed ref 0=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: if configuration.is_client: assert ( original_connection_id is None ), "Cannot set original_connection_id for a client" else: assert ( configuration.certificate is not None ), "SSL certificate is required for a server" assert ( configuration.private_key is not None ), "SSL private key is required for a server" # counters for debugging self._quic_logger = configuration.quic_logger self._stateless_retry_count = 0 # configuration self._configuration = configuration self._is_client = configuration.is_client self._ack_delay = K_GRANULARITY self._close_at: Optional[float] = None self._close_event: Optional[events.ConnectionTerminated] = None self._connect_called = False self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} self._events: Deque[events.QuicEvent] = deque() self._handshake_complete = False self._handshake_confirmed = False self._host_cids = [ QuicConnectionId( cid=os.urandom(8), sequence_number=0, stateless_reset_token=os.urandom(16), was_sent=True, ) ] self.host_cid = self._host_cids[0].cid self._host_cid_seq = 1 self._local_active_connection_id_limit</s> ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 1 <s>cids[0].cid self._host_cid_seq = 1 self._local_active_connection_id_limit = 8 self._local_max_data = MAX_DATA_WINDOW self._local_max_data_sent = MAX_DATA_WINDOW self._local_max_data_used = 0 self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW self._local_max_stream_data_uni = MAX_DATA_WINDOW self._local_max_streams_bidi = 128 self._local_max_streams_uni = 128 self._logger = QuicConnectionAdapter( logger, {"host_cid": dump_cid(self.host_cid)} ) self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) self._loss_at: Optional[float] = None self._network_paths: List[QuicNetworkPath] = [] self._original_connection_id = original_connection_id self._packet_number = 0 self._parameters_received = False self._peer_cid = os.urandom(8) self._peer_cid_seq: Optional[int] = None self._peer_cid_available: List[QuicConnectionId]</s> ===========changed ref 2=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 2 <s> self._peer_token = b"" self._remote_active_connection_id_limit = 0 self._remote_idle_timeout = 0.0 # seconds self._remote_max_data = 0 self._remote_max_data_used = 0 self._remote_max_stream_data_bidi_local = 0 self._remote_max_stream_data_bidi_remote = 0 self._remote_max_stream_data_uni = 0 self._remote_max_streams_bidi = 0 self._remote_max_streams_uni = 0 self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._spin_bit = False - self._spin_bit_peer = False self._spin_highest_pn = 0 self._state = QuicConnectionState.FIRSTFLIGHT self._streams: Dict[int, QuicStream] = {} self._streams_blocked_bidi: List[QuicStream] = [] self._streams_blocked_uni: List[QuicStream] = [] self._version: Optional[int] = None # things to send self._close_pending = False self._ping_pending: List[int] = [] self._probe_pending = False self._retire_connection_ids: List[int] = [] self._streams_blocked_pending = False # callbacks self._session_ticket_fetcher = session_ticket_fetcher self._session_</s>
aioquic.quic.connection/QuicConnection._handle_ack_frame
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<8>:<add> <add> # log frame <add> if context.quic_logger_frames is not None: <add> context.quic_logger_frames.append( <add> { <add> "ack_delay": str( <add> (ack_delay_encoded << self._loss.ack_delay_exponent) // 1000 <add> ), <add> "acked_ranges": [[x.start, x.stop - 1] for x in ack_rangeset], <add> "type": "ack", <add> } <add> )
# module: aioquic.quic.connection class QuicConnection: def _handle_ack_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: <0> """ <1> Handle an ACK frame. <2> """ <3> ack_rangeset, ack_delay_encoded = pull_ack_frame(buf) <4> if frame_type == QuicFrameType.ACK_ECN: <5> buf.pull_uint_var() <6> buf.pull_uint_var() <7> buf.pull_uint_var() <8> <9> self._loss.on_ack_received( <10> space=self._spaces[context.epoch], <11> ack_rangeset=ack_rangeset, <12> ack_delay_encoded=ack_delay_encoded, <13> now=context.time, <14> ) <15> <16> # check if we can discard handshake keys <17> if ( <18> not self._handshake_confirmed <19> and self._handshake_complete <20> and context.epoch == tls.Epoch.ONE_RTT <21> ): <22> self._discard_epoch(tls.Epoch.HANDSHAKE) <23> self._handshake_confirmed = True <24>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer pull_uint_var() -> int at: aioquic.quic.connection QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, time: float) at: aioquic.quic.connection.QuicConnection _discard_epoch(epoch: tls.Epoch) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._handshake_complete = False self._handshake_confirmed = False self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} at: aioquic.quic.connection.QuicConnection._handle_crypto_frame self._handshake_complete = True at: aioquic.quic.connection.QuicConnection._initialize self._spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } at: aioquic.quic.connection.QuicReceiveContext epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath time: float at: aioquic.quic.packet QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) pull_ack_frame(buf: Buffer) -> Tuple[RangeSet, int] ===========unchanged ref 1=========== at: aioquic.quic.recovery.QuicPacketRecovery on_ack_received(space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay_encoded: int, now: float) -> None at: aioquic.tls Epoch() ===========changed ref 0=========== # module: aioquic.quic.connection @dataclass class QuicReceiveContext: epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath + quic_logger_frames: Optional[List[Any]] time: float ===========changed ref 1=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. """ certificate: Any = None """ The server's TLS certificate. See :func:`cryptography.x509.load_pem_x509_certificate`. .. note:: This is only used by servers. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. """ private_key: Any = None """ The server's TLS private key. See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. .. note:: This is only used by servers. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ + supported_versions: List[int] = field( - supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) ===========changed ref 2=========== # module: aioquic.quic.connection class QuicConnection: def receive_datagram(self, data: bytes, addr: NetworkAddress, now: float) -> None: """ Handle an incoming datagram. :param data: The datagram which was received. :param addr: The network address from which the datagram was received. :param now: The current time. """ # stop handling packets when closing if self._state in END_STATES: return data = cast(bytes, data) if self._quic_logger is not None: self._quic_logger.log_event( category="transport", event="datagram_received", data={"byte_length": len(data), "count": 1}, ) buf = Buffer(data=data) while not buf.eof(): start_off = buf.tell() try: header = pull_quic_header(buf, host_cid_length=len(self.host_cid)) except ValueError: return # check destination CID matches destination_cid_seq: Optional[int] = None for connection_id in self._host_cids: if header.destination_cid == connection_id.cid: destination_cid_seq = connection_id.sequence_number break if self._is_client and destination_cid_seq is None: return # check protocol version if self._is_client and header.version == QuicProtocolVersion.NEGOTIATION: # version negotiation versions = [] while not buf.eof(): versions.append(buf.pull_uint32()) if self._quic_logger is not None: self._quic_logger.log_event( category="transport", event="packet_received", data={ "type": "VERSION_NEGOTIATION", "header": {}, "frames": [], }, ) common = set(self._configuration.supported_versions).intersection( versions</s>
aioquic.asyncio.protocol/QuicConnectionProtocol.__init__
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<16>:<add> self._connection_terminated_handler: Callable[[], None] = lambda: None
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None ): <0> loop = asyncio.get_event_loop() <1> <2> self._closed = asyncio.Event() <3> self._connected_waiter = loop.create_future() <4> self._loop = loop <5> self._ping_waiter: Optional[asyncio.Future[None]] = None <6> self._quic = quic <7> self._send_task: Optional[asyncio.Handle] = None <8> self._stream_readers: Dict[int, asyncio.StreamReader] = {} <9> self._timer: Optional[asyncio.TimerHandle] = None <10> self._timer_at: Optional[float] = None <11> self._transport: Optional[asyncio.DatagramTransport] = None <12> <13> # callbacks <14> self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None <15> self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None <16> if stream_handler is not None: <17> self._stream_handler = stream_handler <18> else: <19> self._stream_handler = lambda r, w: None <20>
===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.asyncio.protocol QuicConnectionIdHandler = Callable[[bytes], None] QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None] at: aioquic.asyncio.protocol.QuicConnectionProtocol._handle_timer self._timer = None self._timer_at = None at: aioquic.asyncio.protocol.QuicConnectionProtocol._send_pending self._send_task = None self._ping_waiter = None self._timer = self._loop.call_at(timer_at, self._handle_timer) self._timer = None self._timer_at = timer_at at: aioquic.asyncio.protocol.QuicConnectionProtocol._send_soon self._send_task = self._loop.call_soon(self._send_pending) at: aioquic.asyncio.protocol.QuicConnectionProtocol.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: aioquic.asyncio.protocol.QuicConnectionProtocol.ping self._ping_waiter = self._loop.create_future() at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: asyncio.events Handle(callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop, context: Optional[Context]=...) TimerHandle(when: float, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop, context: Optional[Context]=...) get_event_loop() -> AbstractEventLoop at: asyncio.events.AbstractEventLoop create_future() -> Future[Any] ===========unchanged ref 1=========== at: asyncio.futures Future(*, loop: Optional[AbstractEventLoop]=...) Future = _CFuture = _asyncio.Future at: asyncio.locks Event(*, loop: Optional[AbstractEventLoop]=...) at: asyncio.streams StreamReader(limit: int=..., loop: Optional[events.AbstractEventLoop]=...) at: asyncio.transports DatagramTransport(extra: Optional[Mapping[Any, Any]]=...) at: typing Callable = _CallableType(collections.abc.Callable, 2) Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: aioquic.quic.connection @dataclass class QuicReceiveContext: epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath + quic_logger_frames: Optional[List[Any]] time: float ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: def _handle_ack_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle an ACK frame. """ ack_rangeset, ack_delay_encoded = pull_ack_frame(buf) if frame_type == QuicFrameType.ACK_ECN: buf.pull_uint_var() buf.pull_uint_var() buf.pull_uint_var() + + # log frame + if context.quic_logger_frames is not None: + context.quic_logger_frames.append( + { + "ack_delay": str( + (ack_delay_encoded << self._loss.ack_delay_exponent) // 1000 + ), + "acked_ranges": [[x.start, x.stop - 1] for x in ack_rangeset], + "type": "ack", + } + ) self._loss.on_ack_received( space=self._spaces[context.epoch], ack_rangeset=ack_rangeset, ack_delay_encoded=ack_delay_encoded, now=context.time, ) # check if we can discard handshake keys if ( not self._handshake_confirmed and self._handshake_complete and context.epoch == tls.Epoch.ONE_RTT ): self._discard_epoch(tls.Epoch.HANDSHAKE) self._handshake_confirmed = True ===========changed ref 2=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. """ certificate: Any = None """ The server's TLS certificate. See :func:`cryptography.x509.load_pem_x509_certificate`. .. note:: This is only used by servers. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. """ private_key: Any = None """ The server's TLS private key. See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. .. note:: This is only used by servers. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ + supported_versions: List[int] = field( - supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )
aioquic.asyncio.protocol/QuicConnectionProtocol.quic_event_received
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<0>:<del> if isinstance(event, events.ConnectionIdIssued): <1>:<del> self._connection_id_issued_handler(event.connection_id) <2>:<del> elif isinstance(event, events.ConnectionIdRetired): <3>:<del> self._connection_id_retired_handler(event.connection_id) <4>:<add> # FIXME: move this to a subclass <add> if isinstance(event, events.ConnectionTerminated): <del> elif isinstance(event, events.ConnectionTerminated): <7>:<del> if not self._connected_waiter.done(): <8>:<del> self._connected_waiter.set_exception(ConnectionError) <9>:<del> self._closed.set() <10>:<del> elif isinstance(event, events.HandshakeCompleted): <11>:<del> self._connected_waiter.set_result(None) <12>:<del> elif isinstance(event, events.PingAcknowledged): <13>:<del> waiter = self._ping_waiter <14>:<del> self._ping_waiter = None <15>:<del> waiter.set_result(None)
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): # overridable def quic_event_received(self, event: events.QuicEvent) -> None: <0> if isinstance(event, events.ConnectionIdIssued): <1> self._connection_id_issued_handler(event.connection_id) <2> elif isinstance(event, events.ConnectionIdRetired): <3> self._connection_id_retired_handler(event.connection_id) <4> elif isinstance(event, events.ConnectionTerminated): <5> for reader in self._stream_readers.values(): <6> reader.feed_eof() <7> if not self._connected_waiter.done(): <8> self._connected_waiter.set_exception(ConnectionError) <9> self._closed.set() <10> elif isinstance(event, events.HandshakeCompleted): <11> self._connected_waiter.set_result(None) <12> elif isinstance(event, events.PingAcknowledged): <13> waiter = self._ping_waiter <14> self._ping_waiter = None <15> waiter.set_result(None) <16> elif isinstance(event, events.StreamDataReceived): <17> reader = self._stream_readers.get(event.stream_id, None) <18> if reader is None: <19> reader, writer = self._create_stream(event.stream_id) <20> self._stream_handler(reader, writer) <21> reader.feed_data(event.data) <22> if event.end_stream: <23> reader.feed_eof() <24>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol QuicStreamAdapter(protocol: QuicConnectionProtocol, stream_id: int) at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._stream_handler = lambda r, w: None self._stream_handler = stream_handler at: aioquic.quic.events QuicEvent() ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str) StreamDataReceived(data: bytes, end_stream: bool, stream_id: int) at: asyncio.streams StreamWriter(transport: transports.BaseTransport, protocol: protocols.BaseProtocol, reader: Optional[StreamReader], loop: events.AbstractEventLoop) StreamReader(limit: int=..., loop: Optional[events.AbstractEventLoop]=...) at: asyncio.streams.StreamReader _source_traceback = None feed_eof() -> None feed_data(data: bytes) -> None at: typing Tuple = _TupleType(tuple, -1, inst=False, name='Tuple') at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co] ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None ): loop = asyncio.get_event_loop() self._closed = asyncio.Event() self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None self._quic = quic self._send_task: Optional[asyncio.Handle] = None self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None + self._connection_terminated_handler: Callable[[], None] = lambda: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None ===========changed ref 1=========== # module: aioquic.quic.connection @dataclass class QuicReceiveContext: epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath + quic_logger_frames: Optional[List[Any]] time: float ===========changed ref 2=========== # module: aioquic.quic.connection class QuicConnection: def _handle_ack_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle an ACK frame. """ ack_rangeset, ack_delay_encoded = pull_ack_frame(buf) if frame_type == QuicFrameType.ACK_ECN: buf.pull_uint_var() buf.pull_uint_var() buf.pull_uint_var() + + # log frame + if context.quic_logger_frames is not None: + context.quic_logger_frames.append( + { + "ack_delay": str( + (ack_delay_encoded << self._loss.ack_delay_exponent) // 1000 + ), + "acked_ranges": [[x.start, x.stop - 1] for x in ack_rangeset], + "type": "ack", + } + ) self._loss.on_ack_received( space=self._spaces[context.epoch], ack_rangeset=ack_rangeset, ack_delay_encoded=ack_delay_encoded, now=context.time, ) # check if we can discard handshake keys if ( not self._handshake_confirmed and self._handshake_complete and context.epoch == tls.Epoch.ONE_RTT ): self._discard_epoch(tls.Epoch.HANDSHAKE) self._handshake_confirmed = True ===========changed ref 3=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. """ certificate: Any = None """ The server's TLS certificate. See :func:`cryptography.x509.load_pem_x509_certificate`. .. note:: This is only used by servers. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. """ private_key: Any = None """ The server's TLS private key. See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. .. note:: This is only used by servers. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ + supported_versions: List[int] = field( - supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )
aioquic.asyncio.protocol/QuicConnectionProtocol._send_pending
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<5>:<add> if isinstance(event, events.ConnectionIdIssued): <add> self._connection_id_issued_handler(event.connection_id) <add> elif isinstance(event, events.ConnectionIdRetired): <add> self._connection_id_retired_handler(event.connection_id) <add> elif isinstance(event, events.ConnectionTerminated): <add> self._connection_terminated_handler() <add> if not self._connected_waiter.done(): <add> self._connected_waiter.set_exception(ConnectionError) <add> self._closed.set() <add> elif isinstance(event, events.HandshakeCompleted): <add> self._connected_waiter.set_result(None) <add> elif isinstance(event, events.PingAcknowledged): <add> waiter = self._ping_waiter <add> self._ping_waiter = None <add> waiter.set_result(None)
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def _send_pending(self) -> None: <0> self._send_task = None <1> <2> # process events <3> event = self._quic.next_event() <4> while event is not None: <5> self.quic_event_received(event) <6> event = self._quic.next_event() <7> <8> # send datagrams <9> for data, addr in self._quic.datagrams_to_send(now=self._loop.time()): <10> self._transport.sendto(data, addr) <11> <12> # re-arm timer <13> timer_at = self._quic.get_timer() <14> if self._timer is not None and self._timer_at != timer_at: <15> self._timer.cancel() <16> self._timer = None <17> if self._timer is None and timer_at is not None: <18> self._timer = self._loop.call_at(timer_at, self._handle_timer) <19> self._timer_at = timer_at <20>
===========unchanged ref 0=========== at: _asyncio.Future done() set_exception(exception, /) set_result(result, /) at: aioquic.asyncio.protocol.QuicConnectionProtocol quic_event_received(self, event: events.QuicEvent) -> None quic_event_received(event: events.QuicEvent) -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._closed = asyncio.Event() self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None self._quic = quic self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transport: Optional[asyncio.DatagramTransport] = None self._connection_terminated_handler: Callable[[], None] = lambda: None at: aioquic.asyncio.protocol.QuicConnectionProtocol._handle_timer self._timer = None self._timer_at = None at: aioquic.asyncio.protocol.QuicConnectionProtocol._send_pending self._timer = self._loop.call_at(timer_at, self._handle_timer) self._timer = None self._timer_at = timer_at at: aioquic.asyncio.protocol.QuicConnectionProtocol.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: aioquic.asyncio.protocol.QuicConnectionProtocol.ping self._ping_waiter = self._loop.create_future() at: aioquic.quic.connection.QuicConnection datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_timer() -> Optional[float] next_event() -> Optional[events.QuicEvent] ===========unchanged ref 1=========== at: aioquic.quic.events HandshakeCompleted(alpn_protocol: Optional[str], early_data_accepted: bool, session_resumed: bool) PingAcknowledged(uid: int) at: asyncio.events.AbstractEventLoop time() -> float at: asyncio.events.TimerHandle __slots__ = ['_scheduled', '_when'] cancel() -> None at: asyncio.futures.Future _state = _PENDING _result = None _exception = None _loop = None _source_traceback = None _cancel_message = None _cancelled_exc = None _asyncio_future_blocking = False __log_traceback = False __class_getitem__ = classmethod(GenericAlias) done() -> bool set_result(result: _T, /) -> None set_exception(exception: Union[type, BaseException], /) -> None __iter__ = __await__ # make compatible with 'yield from'. at: asyncio.locks.Event set() -> None at: asyncio.transports.DatagramTransport __slots__ = () sendto(data: Any, addr: Optional[_Address]=...) -> None ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): # overridable def quic_event_received(self, event: events.QuicEvent) -> None: - if isinstance(event, events.ConnectionIdIssued): - self._connection_id_issued_handler(event.connection_id) - elif isinstance(event, events.ConnectionIdRetired): - self._connection_id_retired_handler(event.connection_id) + # FIXME: move this to a subclass + if isinstance(event, events.ConnectionTerminated): - elif isinstance(event, events.ConnectionTerminated): for reader in self._stream_readers.values(): reader.feed_eof() - if not self._connected_waiter.done(): - self._connected_waiter.set_exception(ConnectionError) - self._closed.set() - elif isinstance(event, events.HandshakeCompleted): - self._connected_waiter.set_result(None) - elif isinstance(event, events.PingAcknowledged): - waiter = self._ping_waiter - self._ping_waiter = None - waiter.set_result(None) elif isinstance(event, events.StreamDataReceived): reader = self._stream_readers.get(event.stream_id, None) if reader is None: reader, writer = self._create_stream(event.stream_id) self._stream_handler(reader, writer) reader.feed_data(event.data) if event.end_stream: reader.feed_eof() ===========changed ref 1=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None ): loop = asyncio.get_event_loop() self._closed = asyncio.Event() self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None self._quic = quic self._send_task: Optional[asyncio.Handle] = None self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None + self._connection_terminated_handler: Callable[[], None] = lambda: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None ===========changed ref 2=========== # module: aioquic.quic.connection @dataclass class QuicReceiveContext: epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath + quic_logger_frames: Optional[List[Any]] time: float
aioquic.asyncio.client/connect
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<9>:<add> * ``configuration`` is a :class:`~aioquic.quic.configuration.QuicConfiguration` <add> configuration object. <add> * ``create_protocol`` allows customizing the :class:`~asyncio.Protocol` that <add> manages the connection. It should be a callable or class accepting the same <add> arguments as :class:`~aioquic.asyncio.QuicConnectionProtocol` and returning <add> an instance of :class:`~aioquic.asyncio.QuicConnectionProtocol` or a subclass. <del> * ``alpn_protocols`` is a list of ALPN protocols to offer in the <10>:<del> ClientHello. <11>:<del> * ``secrets_log_file`` is a file-like object in which to log traffic <12>:<del> secrets. This is useful to analyze traffic captures with Wireshark. <13>:<del> * ``session_ticket`` is a TLS session ticket which should be used for <14>:<del> resumption.
<s>, - secrets_log_file: Optional[TextIO] = None, - session_ticket: Optional[SessionTicket] = None, + configuration: Optional[QuicConfiguration] = None, + create_protocol: Optional[Callable] = QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, - supported_versions: Optional[List[int]] = None, ) -> AsyncGenerator[QuicConnectionProtocol, None]: <0> """ <1> Connect to a QUIC server at the given `host` and `port`. <2> <3> :meth:`connect()` returns an awaitable. Awaiting it yields a <4> :class:`~aioquic.asyncio.QuicConnectionProtocol` which can be used to <5> create streams. <6> <7> :func:`connect` also accepts the following optional arguments: <8> <9> * ``alpn_protocols`` is a list of ALPN protocols to offer in the <10> ClientHello. <11> * ``secrets_log_file`` is a file-like object in which to log traffic <12> secrets. This is useful to analyze traffic captures with Wireshark. <13> * ``session_ticket`` is a TLS session ticket which should be used for <14> resumption. <15> * ``session_ticket_handler`` is a callback which is invoked by the TLS <16> engine when a new session ticket is received. <17> * ``stream_handler`` is a callback which is invoked whenever a stream is <18> created. It must accept two arguments: a :class:`asyncio.StreamReader` <19> and a :class:`asyncio.StreamWriter`. <20> """ <21> loop = asyncio.get_event_loop() <22> <23> # if host is not an IP address, pass it to enable SNI <24> try: <25> ipaddress.ip_address(host) <26> server_name = None <27> except ValueError: <28> server_name = host <29> <30> # lookup remote address <31> infos = await loop.getaddrinfo(host, port, type=socket.SOCK_DGRAM) <32> addr</s>
===========below chunk 0=========== <s>_log_file: Optional[TextIO] = None, - session_ticket: Optional[SessionTicket] = None, + configuration: Optional[QuicConfiguration] = None, + create_protocol: Optional[Callable] = QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, - supported_versions: Optional[List[int]] = None, ) -> AsyncGenerator[QuicConnectionProtocol, None]: # offset: 1 if len(addr) == 2: addr = ("::ffff:" + addr[0], addr[1], 0, 0) configuration = QuicConfiguration( alpn_protocols=alpn_protocols, is_client=True, quic_logger=quic_logger, secrets_log_file=secrets_log_file, server_name=server_name, session_ticket=session_ticket, ) if idle_timeout is not None: configuration.idle_timeout = idle_timeout if supported_versions is not None: configuration.supported_versions = supported_versions connection = QuicConnection( configuration=configuration, session_ticket_handler=session_ticket_handler ) # connect _, protocol = await loop.create_datagram_endpoint( lambda: QuicConnectionProtocol(connection, stream_handler=stream_handler), local_addr=("::", 0), ) protocol = cast(QuicConnectionProtocol, protocol) protocol.connect(addr) await protocol.wait_connected() try: yield protocol finally: protocol.close() await protocol.wait_closed() ===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.asyncio.protocol QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None] QuicConnectionProtocol(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.asyncio.protocol.QuicConnectionProtocol close() -> None connect(addr: NetworkAddress) -> None wait_closed() -> None wait_connected() -> None at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) ===========unchanged ref 1=========== at: aioquic.tls SessionTicketHandler = Callable[[SessionTicket], None] at: asyncio.events get_event_loop() -> AbstractEventLoop at: asyncio.events.AbstractEventLoop getaddrinfo(host: Optional[str], port: Union[str, int, None], *, family: int=..., type: int=..., proto: int=..., flags: int=...) -> List[Tuple[AddressFamily, SocketKind, int, str, Union[Tuple[str, int], Tuple[str, int, int, int]]]] create_datagram_endpoint(protocol_factory: _ProtocolFactory, local_addr: Optional[Tuple[str, int]]=..., remote_addr: Optional[Tuple[str, int]]=..., *, family: int=..., proto: int=..., flags: int=..., reuse_address: Optional[bool]=..., reuse_port: Optional[bool]=..., allow_broadcast: Optional[bool]=..., sock: Optional[socket]=...) -> _TransProtPair at: ipaddress ip_address(address: object) -> Any at: socket SOCK_DGRAM: SocketKind at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any Callable = _CallableType(collections.abc.Callable, 2) AsyncGenerator = _alias(collections.abc.AsyncGenerator, 2) ===========changed ref 0=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. """ certificate: Any = None """ The server's TLS certificate. See :func:`cryptography.x509.load_pem_x509_certificate`. .. note:: This is only used by servers. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. """ private_key: Any = None """ The server's TLS private key. See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. .. note:: This is only used by servers. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ + supported_versions: List[int] = field( - supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) ===========changed ref 1=========== # module: aioquic.quic.connection @dataclass class QuicReceiveContext: epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath + quic_logger_frames: Optional[List[Any]] time: float
aioquic.asyncio.server/QuicServer.__init__
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<1>:<add> self._create_protocol = create_protocol
<s> aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def __init__( self, *, configuration: QuicConfiguration, + create_protocol: Callable = QuicConnectionProtocol, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: <0> self._configuration = configuration <1> self._loop = asyncio.get_event_loop() <2> self._protocols: Dict[bytes, QuicConnectionProtocol] = {} <3> self._session_ticket_fetcher = session_ticket_fetcher <4> self._session_ticket_handler = session_ticket_handler <5> self._transport: Optional[asyncio.DatagramTransport] = None <6> <7> self._stream_handler = stream_handler <8> <9> if stateless_retry: <10> self._retry = QuicRetryTokenHandler() <11> else: <12> self._retry = None <13>
===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.asyncio.protocol QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None] QuicConnectionProtocol(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.asyncio.server.QuicServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.retry QuicRetryTokenHandler() at: aioquic.tls SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] at: asyncio.events get_event_loop() -> AbstractEventLoop at: asyncio.transports DatagramTransport(extra: Optional[Mapping[Any, Any]]=...) at: typing Callable = _CallableType(collections.abc.Callable, 2) Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. """ certificate: Any = None """ The server's TLS certificate. See :func:`cryptography.x509.load_pem_x509_certificate`. .. note:: This is only used by servers. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. """ private_key: Any = None """ The server's TLS private key. See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. .. note:: This is only used by servers. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ + supported_versions: List[int] = field( - supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) ===========changed ref 1=========== # module: aioquic.asyncio.server __all__ = ["serve"] - QuicConnectionHandler = Callable[[QuicConnectionProtocol], None] - ===========changed ref 2=========== # module: aioquic.quic.connection @dataclass class QuicReceiveContext: epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath + quic_logger_frames: Optional[List[Any]] time: float ===========changed ref 3=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None ): loop = asyncio.get_event_loop() self._closed = asyncio.Event() self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None self._quic = quic self._send_task: Optional[asyncio.Handle] = None self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None + self._connection_terminated_handler: Callable[[], None] = lambda: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None ===========changed ref 4=========== # module: aioquic.quic.connection class QuicConnection: def _handle_ack_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle an ACK frame. """ ack_rangeset, ack_delay_encoded = pull_ack_frame(buf) if frame_type == QuicFrameType.ACK_ECN: buf.pull_uint_var() buf.pull_uint_var() buf.pull_uint_var() + + # log frame + if context.quic_logger_frames is not None: + context.quic_logger_frames.append( + { + "ack_delay": str( + (ack_delay_encoded << self._loss.ack_delay_exponent) // 1000 + ), + "acked_ranges": [[x.start, x.stop - 1] for x in ack_rangeset], + "type": "ack", + } + ) self._loss.on_ack_received( space=self._spaces[context.epoch], ack_rangeset=ack_rangeset, ack_delay_encoded=ack_delay_encoded, now=context.time, ) # check if we can discard handshake keys if ( not self._handshake_confirmed and self._handshake_complete and context.epoch == tls.Epoch.ONE_RTT ): self._discard_epoch(tls.Epoch.HANDSHAKE) self._handshake_confirmed = True
aioquic.asyncio.server/QuicServer.datagram_received
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
# module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: <0> data = cast(bytes, data) <1> buf = Buffer(data=data) <2> header = pull_quic_header(buf, host_cid_length=8) <3> <4> # version negotiation <5> if ( <6> header.version is not None <7> and header.version not in self._configuration.supported_versions <8> ): <9> self._transport.sendto( <10> encode_quic_version_negotiation( <11> source_cid=header.destination_cid, <12> destination_cid=header.source_cid, <13> supported_versions=self._configuration.supported_versions, <14> ), <15> addr, <16> ) <17> return <18> <19> protocol = self._protocols.get(header.destination_cid, None) <20> original_connection_id: Optional[bytes] = None <21> if protocol is None and header.packet_type == PACKET_TYPE_INITIAL: <22> # stateless retry <23> if self._retry is not None: <24> if not header.token: <25> # create a retry token <26> self._transport.sendto( <27> encode_quic_retry( <28> version=header.version, <29> source_cid=os.urandom(8), <30> destination_cid=header.source_cid, <31> original_destination_cid=header.destination_cid, <32> retry_token=self._retry.create_token( <33> addr, header.destination_cid <34> ), <35> ), <36> addr, <37> ) <38> return <39> else: <40> # validate retry token <41> try: <42> original_connection_id = self._retry.validate_token( <43> addr, header.token <44> ) <45> except ValueError: <46> return <47> <48> # create new connection <49> connection = QuicConnection( <50> configuration=</s>
===========below chunk 0=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 1 original_connection_id=original_connection_id, session_ticket_fetcher=self._session_ticket_fetcher, session_ticket_handler=self._session_ticket_handler, ) protocol = QuicConnectionProtocol( connection, stream_handler=self._stream_handler ) protocol.connection_made(self._transport) protocol._connection_id_issued_handler = partial( self._connection_id_issued, protocol=protocol ) protocol._connection_id_retired_handler = partial( self._connection_id_retired, protocol=protocol ) self._protocols[header.destination_cid] = protocol self._protocols[connection.host_cid] = protocol if protocol is not None: protocol.datagram_received(data, addr) ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.asyncio.server.QuicServer _connection_id_issued(cid: bytes, protocol: QuicConnectionProtocol) _connection_id_retired(cid: bytes, protocol: QuicConnectionProtocol) -> None _connection_terminated(self, protocol: QuicConnectionProtocol) _connection_terminated(protocol: QuicConnectionProtocol) at: aioquic.asyncio.server.QuicServer.__init__ self._configuration = configuration self._create_protocol = create_protocol self._protocols: Dict[bytes, QuicConnectionProtocol] = {} self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler self._transport: Optional[asyncio.DatagramTransport] = None self._stream_handler = stream_handler self._retry = QuicRetryTokenHandler() self._retry = None at: aioquic.asyncio.server.QuicServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) ===========unchanged ref 1=========== at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.quic.connection.QuicConnection.__init__ self.host_cid = self._host_cids[0].cid at: aioquic.quic.connection.QuicConnection.receive_datagram self.host_cid = context.host_cid at: aioquic.quic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 pull_quic_header(buf: Buffer, host_cid_length: Optional[int]=None) -> QuicHeader encode_quic_retry(version: int, source_cid: bytes, destination_cid: bytes, original_destination_cid: bytes, retry_token: bytes) -> bytes encode_quic_version_negotiation(source_cid: bytes, destination_cid: bytes, supported_versions: List[int]) -> bytes at: aioquic.quic.packet.QuicHeader is_long_header: bool version: Optional[int] packet_type: int destination_cid: bytes source_cid: bytes original_destination_cid: bytes = b"" token: bytes = b"" rest_length: int = 0 at: aioquic.quic.retry.QuicRetryTokenHandler create_token(addr: NetworkAddress, destination_cid: bytes) -> bytes validate_token(addr: NetworkAddress, token: bytes) -> bytes at: asyncio.transports.DatagramTransport __slots__ = () sendto(data: Any, addr: Optional[_Address]=...) -> None ===========unchanged ref 2=========== at: functools partial(func: Callable[..., _T], *args: Any, **kwargs: Any) partial(func, *args, **keywords, /) -> function with partial application() at: os urandom(size: int, /) -> bytes at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co] ===========changed ref 0=========== # module: aioquic.asyncio.server __all__ = ["serve"] - QuicConnectionHandler = Callable[[QuicConnectionProtocol], None] - ===========changed ref 1=========== <s> aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def __init__( self, *, configuration: QuicConfiguration, + create_protocol: Callable = QuicConnectionProtocol, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: self._configuration = configuration + self._create_protocol = create_protocol self._loop = asyncio.get_event_loop() self._protocols: Dict[bytes, QuicConnectionProtocol] = {} self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler self._transport: Optional[asyncio.DatagramTransport] = None self._stream_handler = stream_handler if stateless_retry: self._retry = QuicRetryTokenHandler() else: self._retry = None ===========changed ref 2=========== # module: aioquic.quic.connection @dataclass class QuicReceiveContext: epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath + quic_logger_frames: Optional[List[Any]] time: float
aioquic.asyncio.server/serve
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<3>:<del> :func:`serve` requires a TLS certificate and private key, which can be <4>:<del> specified using the following arguments: <5>:<del> <6>:<del> * ``certificate`` is the server's TLS certificate. <7>:<del> See :func:`cryptography.x509.load_pem_x509_certificate`. <8>:<del> * ``private_key`` is the server's private key. <9>:<del> See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. <10>:<add> :func:`serve` requires a :class:`~aioquic.quic.configuration.QuicConfiguration` <add> containing TLS certificate and private key as the ``configuration`` argument. <13>:<add> * ``create_protocol`` allows customizing the :class:`~asyncio.Protocol` that <add> manages the connection. It should be a callable or class accepting the same <add> arguments as :class:`~aioquic.asyncio.QuicConnectionProtocol` and returning <add> an instance of :class:`~aioquic.asyncio.QuicConnectionProtocol` or a subclass. <del> * ``secrets_log_file`` is a file-like object in which to log traffic <14>:<del> secrets. This is useful to analyze traffic captures with Wireshark.
<s>Logger] = None, - stream_handler: QuicStreamHandler = None, - secrets_log_file: Optional[TextIO] = None, + configuration: QuicConfiguration, + create_protocol: Callable = QuicConnectionProtocol, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, + stream_handler: QuicStreamHandler = None, ) -> QuicServer: <0> """ <1> Start a QUIC server at the given `host` and `port`. <2> <3> :func:`serve` requires a TLS certificate and private key, which can be <4> specified using the following arguments: <5> <6> * ``certificate`` is the server's TLS certificate. <7> See :func:`cryptography.x509.load_pem_x509_certificate`. <8> * ``private_key`` is the server's private key. <9> See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. <10> <11> :func:`serve` also accepts the following optional arguments: <12> <13> * ``secrets_log_file`` is a file-like object in which to log traffic <14> secrets. This is useful to analyze traffic captures with Wireshark. <15> * ``session_ticket_fetcher`` is a callback which is invoked by the TLS <16> engine when a session ticket is presented by the peer. It should return <17> the session ticket with the specified ID or `None` if it is not found. <18> * ``session_ticket_handler`` is a callback which is invoked by the TLS <19> engine when a new session ticket is issued. It should store the session <20> ticket for future lookup. <21> * ``stateless_retry`` specifies whether a stateless retry should be <22> performed prior to handling new connections. <23> * ``stream_handler`` is a callback which is invoked whenever a stream is <24> created. It must accept two arguments: a :class:`asyncio.StreamReader` <25> and a :class:`asyncio.StreamWriter`. <26> """ <27> </s>
===========below chunk 0=========== <s> - stream_handler: QuicStreamHandler = None, - secrets_log_file: Optional[TextIO] = None, + configuration: QuicConfiguration, + create_protocol: Callable = QuicConnectionProtocol, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, + stream_handler: QuicStreamHandler = None, ) -> QuicServer: # offset: 1 configuration = QuicConfiguration( alpn_protocols=alpn_protocols, certificate=certificate, is_client=False, private_key=private_key, quic_logger=quic_logger, secrets_log_file=secrets_log_file, ) if idle_timeout is not None: configuration.idle_timeout = idle_timeout _, protocol = await loop.create_datagram_endpoint( lambda: QuicServer( configuration=configuration, session_ticket_fetcher=session_ticket_fetcher, session_ticket_handler=session_ticket_handler, stateless_retry=stateless_retry, stream_handler=stream_handler, ), local_addr=(host, port), ) return cast(QuicServer, protocol) ===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.asyncio.protocol QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None] QuicConnectionProtocol(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.asyncio.server QuicServer(*, configuration: QuicConfiguration, create_protocol: Callable=QuicConnectionProtocol, session_ticket_fetcher: Optional[SessionTicketFetcher]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stateless_retry: bool=False, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.asyncio.server.QuicServer.__init__ self._protocols: Dict[bytes, QuicConnectionProtocol] = {} at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.tls SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] at: asyncio.events get_event_loop() -> AbstractEventLoop ===========unchanged ref 1=========== at: asyncio.events.AbstractEventLoop create_datagram_endpoint(protocol_factory: _ProtocolFactory, local_addr: Optional[Tuple[str, int]]=..., remote_addr: Optional[Tuple[str, int]]=..., *, family: int=..., proto: int=..., flags: int=..., reuse_address: Optional[bool]=..., reuse_port: Optional[bool]=..., allow_broadcast: Optional[bool]=..., sock: Optional[socket]=...) -> _TransProtPair at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any Callable = _CallableType(collections.abc.Callable, 2) ===========changed ref 0=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. """ certificate: Any = None """ The server's TLS certificate. See :func:`cryptography.x509.load_pem_x509_certificate`. .. note:: This is only used by servers. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. """ private_key: Any = None """ The server's TLS private key. See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. .. note:: This is only used by servers. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ + supported_versions: List[int] = field( - supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) ===========changed ref 1=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): + def _connection_terminated(self, protocol: QuicConnectionProtocol): + for cid, proto in list(self._protocols.items()): + if proto == protocol: + del self._protocols[cid] + ===========changed ref 2=========== # module: aioquic.asyncio.server __all__ = ["serve"] - QuicConnectionHandler = Callable[[QuicConnectionProtocol], None] - ===========changed ref 3=========== <s> aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def __init__( self, *, configuration: QuicConfiguration, + create_protocol: Callable = QuicConnectionProtocol, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: self._configuration = configuration + self._create_protocol = create_protocol self._loop = asyncio.get_event_loop() self._protocols: Dict[bytes, QuicConnectionProtocol] = {} self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler self._transport: Optional[asyncio.DatagramTransport] = None self._stream_handler = stream_handler if stateless_retry: self._retry = QuicRetryTokenHandler() else: self._retry = None
tests.test_connection/client_receive_context
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<4>:<add> quic_logger_frames=[],
# module: tests.test_connection def client_receive_context(client, epoch=tls.Epoch.ONE_RTT): <0> return QuicReceiveContext( <1> epoch=epoch, <2> host_cid=client.host_cid, <3> network_path=client._network_paths[0], <4> time=asyncio.get_event_loop().time(), <5> ) <6>
===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.quic.connection QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, time: float) at: aioquic.quic.connection.QuicConnection.__init__ self.host_cid = self._host_cids[0].cid self._network_paths: List[QuicNetworkPath] = [] at: aioquic.quic.connection.QuicConnection.connect self._network_paths = [QuicNetworkPath(addr, is_validated=True)] at: aioquic.quic.connection.QuicConnection.receive_datagram self._network_paths = [network_path] self.host_cid = context.host_cid at: aioquic.quic.connection.QuicReceiveContext epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath time: float at: aioquic.tls Epoch() at: asyncio.events get_event_loop() -> AbstractEventLoop at: asyncio.events.AbstractEventLoop time() -> float ===========changed ref 0=========== # module: aioquic.quic.connection @dataclass class QuicReceiveContext: epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath + quic_logger_frames: Optional[List[Any]] time: float ===========changed ref 1=========== # module: aioquic.asyncio.server __all__ = ["serve"] - QuicConnectionHandler = Callable[[QuicConnectionProtocol], None] - ===========changed ref 2=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): + def _connection_terminated(self, protocol: QuicConnectionProtocol): + for cid, proto in list(self._protocols.items()): + if proto == protocol: + del self._protocols[cid] + ===========changed ref 3=========== <s> aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def __init__( self, *, configuration: QuicConfiguration, + create_protocol: Callable = QuicConnectionProtocol, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: self._configuration = configuration + self._create_protocol = create_protocol self._loop = asyncio.get_event_loop() self._protocols: Dict[bytes, QuicConnectionProtocol] = {} self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler self._transport: Optional[asyncio.DatagramTransport] = None self._stream_handler = stream_handler if stateless_retry: self._retry = QuicRetryTokenHandler() else: self._retry = None ===========changed ref 4=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None ): loop = asyncio.get_event_loop() self._closed = asyncio.Event() self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None self._quic = quic self._send_task: Optional[asyncio.Handle] = None self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None + self._connection_terminated_handler: Callable[[], None] = lambda: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None ===========changed ref 5=========== # module: aioquic.quic.connection class QuicConnection: def _handle_ack_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle an ACK frame. """ ack_rangeset, ack_delay_encoded = pull_ack_frame(buf) if frame_type == QuicFrameType.ACK_ECN: buf.pull_uint_var() buf.pull_uint_var() buf.pull_uint_var() + + # log frame + if context.quic_logger_frames is not None: + context.quic_logger_frames.append( + { + "ack_delay": str( + (ack_delay_encoded << self._loss.ack_delay_exponent) // 1000 + ), + "acked_ranges": [[x.start, x.stop - 1] for x in ack_rangeset], + "type": "ack", + } + ) self._loss.on_ack_received( space=self._spaces[context.epoch], ack_rangeset=ack_rangeset, ack_delay_encoded=ack_delay_encoded, now=context.time, ) # check if we can discard handshake keys if ( not self._handshake_confirmed and self._handshake_complete and context.epoch == tls.Epoch.ONE_RTT ): self._discard_epoch(tls.Epoch.HANDSHAKE) self._handshake_confirmed = True ===========changed ref 6=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): # overridable def quic_event_received(self, event: events.QuicEvent) -> None: - if isinstance(event, events.ConnectionIdIssued): - self._connection_id_issued_handler(event.connection_id) - elif isinstance(event, events.ConnectionIdRetired): - self._connection_id_retired_handler(event.connection_id) + # FIXME: move this to a subclass + if isinstance(event, events.ConnectionTerminated): - elif isinstance(event, events.ConnectionTerminated): for reader in self._stream_readers.values(): reader.feed_eof() - if not self._connected_waiter.done(): - self._connected_waiter.set_exception(ConnectionError) - self._closed.set() - elif isinstance(event, events.HandshakeCompleted): - self._connected_waiter.set_result(None) - elif isinstance(event, events.PingAcknowledged): - waiter = self._ping_waiter - self._ping_waiter = None - waiter.set_result(None) elif isinstance(event, events.StreamDataReceived): reader = self._stream_readers.get(event.stream_id, None) if reader is None: reader, writer = self._create_stream(event.stream_id) self._stream_handler(reader, writer) reader.feed_data(event.data) if event.end_stream: reader.feed_eof()
examples.http3-client/HttpClient.__init__
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<0>:<add> super().__init__(*args, **kwargs) <del> super().__init__( <1>:<del> quic=QuicConnection( <2>:<del> configuration=configuration, <3>:<del> session_ticket_handler=session_ticket_handler, <4>:<del> ) <5>:<del> ) <7>:<del> self._connect_called = False <8>:<add> self._http: Optional[HttpConnection] = None <del> self._http: HttpConnection <9>:<del> self._server_addr = server_addr <10>:<del>
# module: examples.http3-client class HttpClient(QuicConnectionProtocol): - def __init__( - self, - *, - configuration: QuicConfiguration, - server_addr: NetworkAddress, - session_ticket_handler: Optional[SessionTicketHandler] = None - ): + def __init__(self, *args, **kwargs): <0> super().__init__( <1> quic=QuicConnection( <2> configuration=configuration, <3> session_ticket_handler=session_ticket_handler, <4> ) <5> ) <6> <7> self._connect_called = False <8> self._http: HttpConnection <9> self._server_addr = server_addr <10> <11> self._request_events: Dict[int, Deque[HttpEvent]] = {} <12> self._request_waiter: Dict[int, asyncio.Future[Deque[HttpEvent]]] = {} <13> <14> if configuration.alpn_protocols[0].startswith("hq-"): <15> self._http = H0Connection(self._quic) <16> else: <17> self._http = H3Connection(self._quic) <18>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._quic = quic at: aioquic.h0.connection H0Connection(quic: QuicConnection) at: aioquic.h0.connection.H0Connection send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: List[Tuple[bytes, bytes]]) -> None at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers) -> None at: aioquic.h3.events HttpEvent() at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.quic.connection.QuicConnection get_next_available_stream_id(is_unidirectional=False) -> int at: asyncio.futures Future(*, loop: Optional[AbstractEventLoop]=...) Future = _CFuture = _asyncio.Future at: examples.http3-client HttpConnection = Union[H0Connection, H3Connection] ===========unchanged ref 1=========== configuration = QuicConfiguration( is_client=True, alpn_protocols=["hq-22" if args.legacy_http else "h3-22"] ) at: typing Deque = _alias(collections.deque, 1, name='Deque') Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: aioquic.asyncio.server __all__ = ["serve"] - QuicConnectionHandler = Callable[[QuicConnectionProtocol], None] - ===========changed ref 1=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): + def _connection_terminated(self, protocol: QuicConnectionProtocol): + for cid, proto in list(self._protocols.items()): + if proto == protocol: + del self._protocols[cid] + ===========changed ref 2=========== # module: aioquic.quic.connection @dataclass class QuicReceiveContext: epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath + quic_logger_frames: Optional[List[Any]] time: float ===========changed ref 3=========== # module: tests.test_connection def client_receive_context(client, epoch=tls.Epoch.ONE_RTT): return QuicReceiveContext( epoch=epoch, host_cid=client.host_cid, network_path=client._network_paths[0], + quic_logger_frames=[], time=asyncio.get_event_loop().time(), ) ===========changed ref 4=========== <s> aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def __init__( self, *, configuration: QuicConfiguration, + create_protocol: Callable = QuicConnectionProtocol, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: self._configuration = configuration + self._create_protocol = create_protocol self._loop = asyncio.get_event_loop() self._protocols: Dict[bytes, QuicConnectionProtocol] = {} self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler self._transport: Optional[asyncio.DatagramTransport] = None self._stream_handler = stream_handler if stateless_retry: self._retry = QuicRetryTokenHandler() else: self._retry = None ===========changed ref 5=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None ): loop = asyncio.get_event_loop() self._closed = asyncio.Event() self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None self._quic = quic self._send_task: Optional[asyncio.Handle] = None self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None + self._connection_terminated_handler: Callable[[], None] = lambda: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None ===========changed ref 6=========== # module: aioquic.quic.connection class QuicConnection: def _handle_ack_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle an ACK frame. """ ack_rangeset, ack_delay_encoded = pull_ack_frame(buf) if frame_type == QuicFrameType.ACK_ECN: buf.pull_uint_var() buf.pull_uint_var() buf.pull_uint_var() + + # log frame + if context.quic_logger_frames is not None: + context.quic_logger_frames.append( + { + "ack_delay": str( + (ack_delay_encoded << self._loss.ack_delay_exponent) // 1000 + ), + "acked_ranges": [[x.start, x.stop - 1] for x in ack_rangeset], + "type": "ack", + } + ) self._loss.on_ack_received( space=self._spaces[context.epoch], ack_rangeset=ack_rangeset, ack_delay_encoded=ack_delay_encoded, now=context.time, ) # check if we can discard handshake keys if ( not self._handshake_confirmed and self._handshake_complete and context.epoch == tls.Epoch.ONE_RTT ): self._discard_epoch(tls.Epoch.HANDSHAKE) self._handshake_confirmed = True
examples.http3-client/HttpClient.get
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<3>:<del> if not self._connect_called: <4>:<del> self._quic.connect(self._server_addr, now=self._loop.time()) <5>:<del> self._connect_called = True <6>:<del> <13>:<add> (b":authority", authority.encode("utf8")), <del> (b":authority", netloc.encode("utf8")),
# module: examples.http3-client class HttpClient(QuicConnectionProtocol): + def get(self, authority: str, path: str) -> Deque[HttpEvent]: - def get(self, netloc: str, path: str) -> Deque[HttpEvent]: <0> """ <1> Perform a GET request. <2> """ <3> if not self._connect_called: <4> self._quic.connect(self._server_addr, now=self._loop.time()) <5> self._connect_called = True <6> <7> stream_id = self._quic.get_next_available_stream_id() <8> self._http.send_headers( <9> stream_id=stream_id, <10> headers=[ <11> (b":method", b"GET"), <12> (b":scheme", b"https"), <13> (b":authority", netloc.encode("utf8")), <14> (b":path", path.encode("utf8")), <15> ], <16> ) <17> self._http.send_data(stream_id=stream_id, data=b"", end_stream=True) <18> <19> waiter = self._loop.create_future() <20> self._request_events[stream_id] = deque() <21> self._request_waiter[stream_id] = waiter <22> self._send_pending() <23> <24> return await asyncio.shield(waiter) <25>
===========unchanged ref 0=========== at: _asyncio.Future set_result(result, /) at: aioquic.asyncio.protocol.QuicConnectionProtocol quic_event_received(self, event: events.QuicEvent) -> None _send_pending() -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._loop = loop at: aioquic.h0.connection.H0Connection handle_event(event: QuicEvent) -> List[HttpEvent] at: aioquic.h3.connection.H3Connection handle_event(event: QuicEvent) -> List[HttpEvent] at: aioquic.h3.events HttpEvent() DataReceived(data: bytes, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.quic.events QuicEvent() at: asyncio.events.AbstractEventLoop create_future() -> Future[Any] at: asyncio.futures.Future _state = _PENDING _result = None _exception = None _loop = None _source_traceback = None _cancel_message = None _cancelled_exc = None _asyncio_future_blocking = False __log_traceback = False __class_getitem__ = classmethod(GenericAlias) set_result(result: _T, /) -> None __iter__ = __await__ # make compatible with 'yield from'. at: asyncio.tasks shield(arg: _FutureT[_T], *, loop: Optional[AbstractEventLoop]=...) -> Future[_T] at: collections deque(iterable: Iterable[_T]=..., maxlen: Optional[int]=...) at: collections.deque append(x: _T) -> None ===========unchanged ref 1=========== at: examples.http3-client.HttpClient.__init__ self._http = H3Connection(self._quic) self._http: Optional[HttpConnection] = None self._http = H0Connection(self._quic) self._request_events: Dict[int, Deque[HttpEvent]] = {} self._request_waiter: Dict[int, asyncio.Future[Deque[HttpEvent]]] = {} at: examples.http3-client.HttpClient.get stream_id = self._quic.get_next_available_stream_id() at: typing.MutableMapping pop(key: _KT) -> _VT pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T] ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): # overridable def quic_event_received(self, event: events.QuicEvent) -> None: - if isinstance(event, events.ConnectionIdIssued): - self._connection_id_issued_handler(event.connection_id) - elif isinstance(event, events.ConnectionIdRetired): - self._connection_id_retired_handler(event.connection_id) + # FIXME: move this to a subclass + if isinstance(event, events.ConnectionTerminated): - elif isinstance(event, events.ConnectionTerminated): for reader in self._stream_readers.values(): reader.feed_eof() - if not self._connected_waiter.done(): - self._connected_waiter.set_exception(ConnectionError) - self._closed.set() - elif isinstance(event, events.HandshakeCompleted): - self._connected_waiter.set_result(None) - elif isinstance(event, events.PingAcknowledged): - waiter = self._ping_waiter - self._ping_waiter = None - waiter.set_result(None) elif isinstance(event, events.StreamDataReceived): reader = self._stream_readers.get(event.stream_id, None) if reader is None: reader, writer = self._create_stream(event.stream_id) self._stream_handler(reader, writer) reader.feed_data(event.data) if event.end_stream: reader.feed_eof() ===========changed ref 1=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def _send_pending(self) -> None: self._send_task = None # process events event = self._quic.next_event() while event is not None: + if isinstance(event, events.ConnectionIdIssued): + self._connection_id_issued_handler(event.connection_id) + elif isinstance(event, events.ConnectionIdRetired): + self._connection_id_retired_handler(event.connection_id) + elif isinstance(event, events.ConnectionTerminated): + self._connection_terminated_handler() + if not self._connected_waiter.done(): + self._connected_waiter.set_exception(ConnectionError) + self._closed.set() + elif isinstance(event, events.HandshakeCompleted): + self._connected_waiter.set_result(None) + elif isinstance(event, events.PingAcknowledged): + waiter = self._ping_waiter + self._ping_waiter = None + waiter.set_result(None) self.quic_event_received(event) event = self._quic.next_event() # send datagrams for data, addr in self._quic.datagrams_to_send(now=self._loop.time()): self._transport.sendto(data, addr) # re-arm timer timer_at = self._quic.get_timer() if self._timer is not None and self._timer_at != timer_at: self._timer.cancel() self._timer = None if self._timer is None and timer_at is not None: self._timer = self._loop.call_at(timer_at, self._handle_timer) self._timer_at = timer_at ===========changed ref 2=========== # module: examples.http3-client class HttpClient(QuicConnectionProtocol): - def __init__( - self, - *, - configuration: QuicConfiguration, - server_addr: NetworkAddress, - session_ticket_handler: Optional[SessionTicketHandler] = None - ): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) - super().__init__( - quic=QuicConnection( - configuration=configuration, - session_ticket_handler=session_ticket_handler, - ) - ) - self._connect_called = False + self._http: Optional[HttpConnection] = None - self._http: HttpConnection - self._server_addr = server_addr - self._request_events: Dict[int, Deque[HttpEvent]] = {} self._request_waiter: Dict[int, asyncio.Future[Deque[HttpEvent]]] = {} if configuration.alpn_protocols[0].startswith("hq-"): self._http = H0Connection(self._quic) else: self._http = H3Connection(self._quic) ===========changed ref 3=========== # module: aioquic.asyncio.server __all__ = ["serve"] - QuicConnectionHandler = Callable[[QuicConnectionProtocol], None] - ===========changed ref 4=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): + def _connection_terminated(self, protocol: QuicConnectionProtocol): + for cid, proto in list(self._protocols.items()): + if proto == protocol: + del self._protocols[cid] +
examples.http3-client/HttpClient.quic_event_received
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<1>:<add> if self._http is not None: <add> for http_event in self._http.handle_event(event): <del> for http_event in self._http.handle_event(event): <2>:<del> if ( <3>:<del> isinstance(http_event, (ResponseReceived, DataReceived)) <4>:<del> and http_event.stream_id in self._request_events <5>:<del> ): <6>:<del> self._request_events[http_event.stream_id].append(http_event) <7>:<del> if http_event.stream_ended: <8>:<del> request_waiter = self._request_waiter.pop(http_event.stream_id) <9>:<del> request_waiter.set_result( <10>:<del> self._request_events.pop(http_event.stream_id) <11>:<del> ) <12>:<add> self.http_event_received(http_event) <13>:<del> if isinstance(event, ConnectionTerminated): <14>:<del> self._closed.set() <15>:<del>
# module: examples.http3-client class HttpClient(QuicConnectionProtocol): def quic_event_received(self, event: QuicEvent): <0> #  pass event to the HTTP layer <1> for http_event in self._http.handle_event(event): <2> if ( <3> isinstance(http_event, (ResponseReceived, DataReceived)) <4> and http_event.stream_id in self._request_events <5> ): <6> self._request_events[http_event.stream_id].append(http_event) <7> if http_event.stream_ended: <8> request_waiter = self._request_waiter.pop(http_event.stream_id) <9> request_waiter.set_result( <10> self._request_events.pop(http_event.stream_id) <11> ) <12> <13> if isinstance(event, ConnectionTerminated): <14> self._closed.set() <15>
===========unchanged ref 0=========== at: _pickle dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None) at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: examples.http3-client logger = logging.getLogger("client") args = parser.parse_args() at: logging.Logger info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None at: pickle dump, dumps, load, loads = _dump, _dumps, _load, _loads at: urllib.parse urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes ===========changed ref 0=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. """ certificate: Any = None """ The server's TLS certificate. See :func:`cryptography.x509.load_pem_x509_certificate`. .. note:: This is only used by servers. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. """ private_key: Any = None """ The server's TLS private key. See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. .. note:: This is only used by servers. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ + supported_versions: List[int] = field( - supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) ===========changed ref 1=========== # module: examples.http3-client class HttpClient(QuicConnectionProtocol): + def http_event_received(self, event: HttpEvent): + if ( + isinstance(event, (ResponseReceived, DataReceived)) + and event.stream_id in self._request_events + ): + self._request_events[event.stream_id].append(event) + if event.stream_ended: + request_waiter = self._request_waiter.pop(event.stream_id) + request_waiter.set_result(self._request_events.pop(event.stream_id)) + ===========changed ref 2=========== # module: examples.http3-client class HttpClient(QuicConnectionProtocol): - def __init__( - self, - *, - configuration: QuicConfiguration, - server_addr: NetworkAddress, - session_ticket_handler: Optional[SessionTicketHandler] = None - ): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) - super().__init__( - quic=QuicConnection( - configuration=configuration, - session_ticket_handler=session_ticket_handler, - ) - ) - self._connect_called = False + self._http: Optional[HttpConnection] = None - self._http: HttpConnection - self._server_addr = server_addr - self._request_events: Dict[int, Deque[HttpEvent]] = {} self._request_waiter: Dict[int, asyncio.Future[Deque[HttpEvent]]] = {} if configuration.alpn_protocols[0].startswith("hq-"): self._http = H0Connection(self._quic) else: self._http = H3Connection(self._quic) ===========changed ref 3=========== # module: examples.http3-client class HttpClient(QuicConnectionProtocol): + def get(self, authority: str, path: str) -> Deque[HttpEvent]: - def get(self, netloc: str, path: str) -> Deque[HttpEvent]: """ Perform a GET request. """ - if not self._connect_called: - self._quic.connect(self._server_addr, now=self._loop.time()) - self._connect_called = True - stream_id = self._quic.get_next_available_stream_id() self._http.send_headers( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", b"https"), + (b":authority", authority.encode("utf8")), - (b":authority", netloc.encode("utf8")), (b":path", path.encode("utf8")), ], ) self._http.send_data(stream_id=stream_id, data=b"", end_stream=True) waiter = self._loop.create_future() self._request_events[stream_id] = deque() self._request_waiter[stream_id] = waiter self._send_pending() return await asyncio.shield(waiter) ===========changed ref 4=========== # module: aioquic.asyncio.server __all__ = ["serve"] - QuicConnectionHandler = Callable[[QuicConnectionProtocol], None] - ===========changed ref 5=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): + def _connection_terminated(self, protocol: QuicConnectionProtocol): + for cid, proto in list(self._protocols.items()): + if proto == protocol: + del self._protocols[cid] + ===========changed ref 6=========== # module: aioquic.quic.connection @dataclass class QuicReceiveContext: epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath + quic_logger_frames: Optional[List[Any]] time: float ===========changed ref 7=========== # module: tests.test_connection def client_receive_context(client, epoch=tls.Epoch.ONE_RTT): return QuicReceiveContext( epoch=epoch, host_cid=client.host_cid, network_path=client._network_paths[0], + quic_logger_frames=[], time=asyncio.get_event_loop().time(), )
examples.http3-client/run
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<4>:<add> host, port_str = parsed.netloc.split(":") <del> server_name, port_str = parsed.netloc.split(":") <7>:<add> host = parsed.netloc <del> server_name = parsed.netloc <10>:<add> async with connect( <add> host, <add> port, <add> configuration=configuration, <add> create_protocol=HttpClient, <add> session_ticket_handler=save_session_ticket, <add> ) as client: <add> client = cast(HttpClient, client) <del> # lookup remote address <11>:<del> infos = await loop.getaddrinfo(server_name, port, type=socket.SOCK_DGRAM) <12>:<del> server_addr = infos[0][4] <13>:<del> if len(server_addr) == 2: <14>:<del> server_addr = ("::ffff:" + server_addr[0], server_addr[1], 0, 0) <16>:<del> # prepare QUIC connection <17>:<del> _, client = await loop.create_datagram_endpoint( <18>:<del> lambda: HttpClient( <19>:<del> configuration=QuicConfiguration( <20>:<del> alpn_protocols=["hq-22" if legacy_http else "h3-22"], <21>:<del> is_client=True, <22>:<del> server_name=server_name, <23>:<del> **kwargs <24>:<del> ), <25>:<del> server_addr=server_addr, <26>:<del> session_ticket_handler=save_session_ticket, <27>:<del> ), <28>:<del> local_addr=("::", 0), <29>:<del> ) <30>:<del> client = cast(HttpClient, client) <31>:<add> # perform request <add> start = time.time() <add> http_events = await client.get(parsed.netloc, parsed.path) <add> elapsed = time.time() - start <32>:<add> # print speed <add> octets = 0 <add> for http_event in http_events: <add> if isinstance(http_event, DataReceived): <add> octets += len(http_event.data) <add> logger.info( <add> "Received
# module: examples.http3-client + def run(url: str, configuration: QuicConfiguration) -> None: - def run(url: str, legacy_http: bool, **kwargs) -> None: <0> # parse URL <1> parsed = urlparse(url) <2> assert parsed.scheme == "https", "Only HTTPS URLs are supported." <3> if ":" in parsed.netloc: <4> server_name, port_str = parsed.netloc.split(":") <5> port = int(port_str) <6> else: <7> server_name = parsed.netloc <8> port = 443 <9> <10> # lookup remote address <11> infos = await loop.getaddrinfo(server_name, port, type=socket.SOCK_DGRAM) <12> server_addr = infos[0][4] <13> if len(server_addr) == 2: <14> server_addr = ("::ffff:" + server_addr[0], server_addr[1], 0, 0) <15> <16> # prepare QUIC connection <17> _, client = await loop.create_datagram_endpoint( <18> lambda: HttpClient( <19> configuration=QuicConfiguration( <20> alpn_protocols=["hq-22" if legacy_http else "h3-22"], <21> is_client=True, <22> server_name=server_name, <23> **kwargs <24> ), <25> server_addr=server_addr, <26> session_ticket_handler=save_session_ticket, <27> ), <28> local_addr=("::", 0), <29> ) <30> client = cast(HttpClient, client) <31> <32> # perform request <33> start = time.time() <34> http_events = await client.get(parsed.netloc, parsed.path) <35> elapsed = time.time() - start <36> <37> # print speed <38> octets = 0 <39> for http_event in http_events: <40> if isinstance(http_event, DataReceived): <41> octets += len(http_event.data) <42> logger.info( <43> "Received %d bytes in</s>
===========below chunk 0=========== # module: examples.http3-client + def run(url: str, configuration: QuicConfiguration) -> None: - def run(url: str, legacy_http: bool, **kwargs) -> None: # offset: 1 % (octets, elapsed, octets * 8 / elapsed / 1000000) ) # print response for http_event in http_events: if isinstance(http_event, ResponseReceived): headers = b"" for k, v in http_event.headers: headers += k + b": " + v + b"\r\n" if headers: sys.stderr.buffer.write(headers + b"\r\n") sys.stderr.buffer.flush() elif isinstance(http_event, DataReceived): sys.stdout.buffer.write(http_event.data) sys.stdout.buffer.flush() # close QUIC connection client.close() await client.wait_closed() ===========unchanged ref 0=========== at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.configuration.QuicConfiguration quic_logger: Optional[QuicLogger] = None at: aioquic.quic.logger QuicLogger() at: argparse ArgumentParser(prog: Optional[str]=..., usage: Optional[str]=..., description: Optional[str]=..., epilog: Optional[str]=..., parents: Sequence[ArgumentParser]=..., formatter_class: _FormatterClass=..., prefix_chars: str=..., fromfile_prefix_chars: Optional[str]=..., argument_default: Any=..., conflict_handler: str=..., add_help: bool=..., allow_abbrev: bool=...) at: argparse.ArgumentParser parse_args(args: Optional[Sequence[Text]], namespace: None) -> Namespace parse_args(args: Optional[Sequence[Text]]=...) -> Namespace parse_args(*, namespace: None) -> Namespace parse_args(args: Optional[Sequence[Text]], namespace: _N) -> _N parse_args(*, namespace: _N) -> _N ===========unchanged ref 1=========== at: argparse._ActionsContainer add_argument(*name_or_flags: Text, action: Union[Text, Type[Action]]=..., nargs: Union[int, Text]=..., const: Any=..., default: Any=..., type: Union[Callable[[Text], _T], Callable[[str], _T], FileType]=..., choices: Iterable[_T]=..., required: bool=..., help: Optional[Text]=..., metavar: Optional[Union[Text, Tuple[Text, ...]]]=..., dest: Optional[Text]=..., version: Text=..., **kwargs: Any) -> Action at: examples.http3-client logger = logging.getLogger("client") at: examples.http3-client.HttpClient get(authority: str, path: str) -> Deque[HttpEvent] get(self, authority: str, path: str) -> Deque[HttpEvent] at: examples.http3-client.run parsed = urlparse(url) client = cast(HttpClient, client) at: logging INFO = 20 DEBUG = 10 basicConfig(*, filename: Optional[StrPath]=..., filemode: str=..., format: str=..., datefmt: Optional[str]=..., style: str=..., level: Optional[_Level]=..., stream: Optional[IO[str]]=..., handlers: Optional[Iterable[Handler]]=...) -> None at: logging.Logger info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None at: sys stdout: TextIO stderr: TextIO at: time time() -> float at: typing.BinaryIO __slots__ = () write(s: AnyStr) -> int at: typing.IO __slots__ = () flush() -> None at: typing.TextIO __slots__ = () ===========changed ref 0=========== # module: examples.http3-client class HttpClient(QuicConnectionProtocol): + def get(self, authority: str, path: str) -> Deque[HttpEvent]: - def get(self, netloc: str, path: str) -> Deque[HttpEvent]: """ Perform a GET request. """ - if not self._connect_called: - self._quic.connect(self._server_addr, now=self._loop.time()) - self._connect_called = True - stream_id = self._quic.get_next_available_stream_id() self._http.send_headers( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", b"https"), + (b":authority", authority.encode("utf8")), - (b":authority", netloc.encode("utf8")), (b":path", path.encode("utf8")), ], ) self._http.send_data(stream_id=stream_id, data=b"", end_stream=True) waiter = self._loop.create_future() self._request_events[stream_id] = deque() self._request_waiter[stream_id] = waiter self._send_pending() return await asyncio.shield(waiter)
tests.test_asyncio/run_server
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<0>:<add> if configuration is None: <add> configuration = QuicConfiguration( <add> certificate=SERVER_CERTIFICATE, <add> private_key=SERVER_PRIVATE_KEY, <add> is_client=False, <add> ) <3>:<del> certificate=SERVER_CERTIFICATE, <4>:<del> private_key=SERVER_PRIVATE_KEY, <5>:<add> configuration=configuration,
# module: tests.test_asyncio + def run_server(configuration=None, **kwargs): - def run_server(**kwargs): <0> return await serve( <1> host="::", <2> port="4433", <3> certificate=SERVER_CERTIFICATE, <4> private_key=SERVER_PRIVATE_KEY, <5> stream_handler=handle_stream, <6> **kwargs <7> ) <8>
===========unchanged ref 0=========== at: aioquic.asyncio.server serve(host: str, port: int, *, configuration: QuicConfiguration, create_protocol: Callable=QuicConnectionProtocol, session_ticket_fetcher: Optional[SessionTicketFetcher]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stateless_retry: bool=False, stream_handler: QuicStreamHandler=None) -> QuicServer at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: tests.utils SERVER_CERTIFICATE = x509.load_pem_x509_certificate( load("ssl_cert.pem"), backend=default_backend() ) SERVER_PRIVATE_KEY = serialization.load_pem_private_key( load("ssl_key.pem"), password=None, backend=default_backend() ) ===========changed ref 0=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. """ certificate: Any = None """ The server's TLS certificate. See :func:`cryptography.x509.load_pem_x509_certificate`. .. note:: This is only used by servers. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. """ private_key: Any = None """ The server's TLS private key. See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. .. note:: This is only used by servers. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ + supported_versions: List[int] = field( - supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) ===========changed ref 1=========== <s>Logger] = None, - stream_handler: QuicStreamHandler = None, - secrets_log_file: Optional[TextIO] = None, + configuration: QuicConfiguration, + create_protocol: Callable = QuicConnectionProtocol, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, + stream_handler: QuicStreamHandler = None, ) -> QuicServer: """ Start a QUIC server at the given `host` and `port`. - :func:`serve` requires a TLS certificate and private key, which can be - specified using the following arguments: - - * ``certificate`` is the server's TLS certificate. - See :func:`cryptography.x509.load_pem_x509_certificate`. - * ``private_key`` is the server's private key. - See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. + :func:`serve` requires a :class:`~aioquic.quic.configuration.QuicConfiguration` + containing TLS certificate and private key as the ``configuration`` argument. :func:`serve` also accepts the following optional arguments: + * ``create_protocol`` allows customizing the :class:`~asyncio.Protocol` that + manages the connection. It should be a callable or class accepting the same + arguments as :class:`~aioquic.asyncio.QuicConnectionProtocol` and returning + an instance of :class:`~aioquic.asyncio.QuicConnectionProtocol` or a subclass. - * ``secrets_log_file`` is a file-like object in which to log traffic - secrets. This is useful to analyze traffic captures with Wireshark. * ``session_ticket_fetcher`` is a callback which is invoked by the TLS engine when a session ticket is presented by the peer. It should return the session ticket with the specified ID or `None` if it is not found. * ``</s> ===========changed ref 2=========== <s> - stream_handler: QuicStreamHandler = None, - secrets_log_file: Optional[TextIO] = None, + configuration: QuicConfiguration, + create_protocol: Callable = QuicConnectionProtocol, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, + stream_handler: QuicStreamHandler = None, ) -> QuicServer: # offset: 1 <s> by the peer. It should return the session ticket with the specified ID or `None` if it is not found. * ``session_ticket_handler`` is a callback which is invoked by the TLS engine when a new session ticket is issued. It should store the session ticket for future lookup. * ``stateless_retry`` specifies whether a stateless retry should be performed prior to handling new connections. * ``stream_handler`` is a callback which is invoked whenever a stream is created. It must accept two arguments: a :class:`asyncio.StreamReader` and a :class:`asyncio.StreamWriter`. """ loop = asyncio.get_event_loop() - configuration = QuicConfiguration( - alpn_protocols=alpn_protocols, - certificate=certificate, - is_client=False, - private_key=private_key, - quic_logger=quic_logger, - secrets_log_file=secrets_log_file, - ) - if idle_timeout is not None: - configuration.idle_timeout = idle_timeout - _, protocol = await loop.create_datagram_endpoint( lambda: QuicServer( configuration=configuration, + create_protocol=create_protocol, session_ticket_fetcher=session_ticket_fetcher, session_ticket_handler=session_ticket_handler, stateless_retry=stateless_retry,</s>
tests.test_asyncio/HighLevelTest.test_connect_and_serve_writelines
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<0>:<add> async def run_client_writelines(host, port=4433): <del> async def run_client_writelines(host, port=4433, **kwargs): <1>:<add> async with connect(host, port) as client: <del> async with connect(host, port, **kwargs) as client:
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_writelines(self): <0> async def run_client_writelines(host, port=4433, **kwargs): <1> async with connect(host, port, **kwargs) as client: <2> reader, writer = await client.create_stream() <3> assert writer.can_write_eof() is True <4> <5> writer.writelines([b"01234567", b"89012345"]) <6> writer.write_eof() <7> <8> return await reader.read() <9> <10> server, response = run( <11> asyncio.gather(run_server(), run_client_writelines("127.0.0.1")) <12> ) <13> self.assertEqual(response, b"5432109876543210") <14> server.close() <15>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(host: str, port: int, *, configuration: Optional[QuicConfiguration]=None, create_protocol: Optional[Callable]=QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] connect(*args, **kwds) at: aioquic.asyncio.protocol.QuicConnectionProtocol create_stream(is_unidirectional: bool=False) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter] at: asyncio.streams.StreamWriter writelines(data: Iterable[bytes]) -> None can_write_eof() -> bool ===========unchanged ref 1=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 2=========== at: tests.test_asyncio run_client(host, port=4433, request=b"ping", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(configuration=None, *, create_protocol: Callable=QuicConnectionProtocol) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_large data = b"Z" * 2097152 at: tests.utils run(coro) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_asyncio + def run_server(configuration=None, **kwargs): - def run_server(**kwargs): + if configuration is None: + configuration = QuicConfiguration( + certificate=SERVER_CERTIFICATE, + private_key=SERVER_PRIVATE_KEY, + is_client=False, + ) return await serve( host="::", port="4433", - certificate=SERVER_CERTIFICATE, - private_key=SERVER_PRIVATE_KEY, + configuration=configuration, stream_handler=handle_stream, **kwargs ) ===========changed ref 1=========== <s>, - secrets_log_file: Optional[TextIO] = None, - session_ticket: Optional[SessionTicket] = None, + configuration: Optional[QuicConfiguration] = None, + create_protocol: Optional[Callable] = QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, - supported_versions: Optional[List[int]] = None, ) -> AsyncGenerator[QuicConnectionProtocol, None]: """ Connect to a QUIC server at the given `host` and `port`. :meth:`connect()` returns an awaitable. Awaiting it yields a :class:`~aioquic.asyncio.QuicConnectionProtocol` which can be used to create streams. :func:`connect` also accepts the following optional arguments: + * ``configuration`` is a :class:`~aioquic.quic.configuration.QuicConfiguration` + configuration object. + * ``create_protocol`` allows customizing the :class:`~asyncio.Protocol` that + manages the connection. It should be a callable or class accepting the same + arguments as :class:`~aioquic.asyncio.QuicConnectionProtocol` and returning + an instance of :class:`~aioquic.asyncio.QuicConnectionProtocol` or a subclass. - * ``alpn_protocols`` is a list of ALPN protocols to offer in the - ClientHello. - * ``secrets_log_file`` is a file-like object in which to log traffic - secrets. This is useful to analyze traffic captures with Wireshark. - * ``session_ticket`` is a TLS session ticket which should be used for - resumption. * ``session_ticket_handler`` is a callback which is invoked by the TLS engine when a new session ticket is received. * ``stream_handler`` is a callback which is invoked whenever a stream is created. It must accept two arguments: a :class:`asyncio.StreamReader` and a :class:`asyncio.StreamWriter`. """</s>
tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_packet_loss
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<8>:<add> configuration=QuicConfiguration( <add> certificate=SERVER_CERTIFICATE, <add> idle_timeout=300.0, <add> is_client=False, <add> private_key=SERVER_PRIVATE_KEY, <add> quic_logger=QuicLogger(), <add> ), <add> stateless_retry=True, <del> idle_timeout=300.0, quic_logger=QuicLogger(), stateless_retry=True <12>:<add> configuration=QuicConfiguration( <add> is_client=True, idle_timeout=300.0, quic_logger=QuicLogger() <add> ), <del> idle_timeout=300.0, <13>:<del> quic_logger=QuicLogger(),
# module: tests.test_asyncio class HighLevelTest(TestCase): @patch("socket.socket.sendto", new_callable=lambda: sendto_with_loss) def test_connect_and_serve_with_packet_loss(self, mock_sendto): <0> """ <1> This test ensures handshake success and stream data is successfully sent <2> and received in the presence of packet loss (randomized 25% in each direction). <3> """ <4> data = b"Z" * 65536 <5> server, response = run( <6> asyncio.gather( <7> run_server( <8> idle_timeout=300.0, quic_logger=QuicLogger(), stateless_retry=True <9> ), <10> run_client( <11> "127.0.0.1", <12> idle_timeout=300.0, <13> quic_logger=QuicLogger(), <14> request=data, <15> ), <16> ) <17> ) <18> self.assertEqual(response, data) <19> server.close() <20>
===========unchanged ref 0=========== at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.logger QuicLogger() ===========unchanged ref 1=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 2=========== at: tests.test_asyncio sendto_with_loss(self, data, addr=None) run_server(configuration=None, *, create_protocol: Callable=QuicConnectionProtocol) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_writelines run_client_writelines(host, port=4433) at: tests.utils run(coro) SERVER_CERTIFICATE = x509.load_pem_x509_certificate( load("ssl_cert.pem"), backend=default_backend() ) SERVER_PRIVATE_KEY = serialization.load_pem_private_key( load("ssl_key.pem"), password=None, backend=default_backend() ) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None at: unittest.mock _patcher(target: Any, new: _T, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[_T] _patcher(target: Any, *, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[Union[MagicMock, AsyncMock]] ===========changed ref 0=========== # module: tests.test_asyncio + def run_server(configuration=None, **kwargs): - def run_server(**kwargs): + if configuration is None: + configuration = QuicConfiguration( + certificate=SERVER_CERTIFICATE, + private_key=SERVER_PRIVATE_KEY, + is_client=False, + ) return await serve( host="::", port="4433", - certificate=SERVER_CERTIFICATE, - private_key=SERVER_PRIVATE_KEY, + configuration=configuration, stream_handler=handle_stream, **kwargs ) ===========changed ref 1=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. """ certificate: Any = None """ The server's TLS certificate. See :func:`cryptography.x509.load_pem_x509_certificate`. .. note:: This is only used by servers. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. """ private_key: Any = None """ The server's TLS private key. See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. .. note:: This is only used by servers. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ + supported_versions: List[int] = field( - supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_writelines(self): + async def run_client_writelines(host, port=4433): - async def run_client_writelines(host, port=4433, **kwargs): + async with connect(host, port) as client: - async with connect(host, port, **kwargs) as client: reader, writer = await client.create_stream() assert writer.can_write_eof() is True writer.writelines([b"01234567", b"89012345"]) writer.write_eof() return await reader.read() server, response = run( asyncio.gather(run_server(), run_client_writelines("127.0.0.1")) ) self.assertEqual(response, b"5432109876543210") server.close() ===========changed ref 3=========== # module: aioquic.asyncio.server __all__ = ["serve"] - QuicConnectionHandler = Callable[[QuicConnectionProtocol], None] -
tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_session_ticket
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<23>:<add> run_client( <add> "127.0.0.1", <add> configuration=QuicConfiguration( <add> is_client=True, session_ticket=client_ticket <del> run_client("127.0.0.1", session_ticket=client_ticket), <24>:<add> ), <add> ),
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_session_ticket(self): <0> client_ticket = None <1> store = SessionTicketStore() <2> <3> def save_ticket(t): <4> nonlocal client_ticket <5> client_ticket = t <6> <7> # first request <8> server, response = run( <9> asyncio.gather( <10> run_server(session_ticket_handler=store.add), <11> run_client("127.0.0.1", session_ticket_handler=save_ticket), <12> ) <13> ) <14> self.assertEqual(response, b"gnip") <15> server.close() <16> <17> self.assertIsNotNone(client_ticket) <18> <19> # second request <20> server, response = run( <21> asyncio.gather( <22> run_server(session_ticket_fetcher=store.pop), <23> run_client("127.0.0.1", session_ticket=client_ticket), <24> ) <25> ) <26> self.assertEqual(response, b"gnip") <27> server.close() <28>
===========unchanged ref 0=========== at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.logger QuicLogger() ===========unchanged ref 1=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 2=========== at: tests.test_asyncio SessionTicketStore() run_client(host, port=4433, request=b"ping", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(configuration=None, *, create_protocol: Callable=QuicConnectionProtocol) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_packet_loss data = b"Z" * 65536 server, response = run( asyncio.gather( run_server( configuration=QuicConfiguration( certificate=SERVER_CERTIFICATE, idle_timeout=300.0, is_client=False, private_key=SERVER_PRIVATE_KEY, quic_logger=QuicLogger(), ), stateless_retry=True, ), run_client( "127.0.0.1", configuration=QuicConfiguration( is_client=True, idle_timeout=300.0, quic_logger=QuicLogger() ), request=data, ), ) ) server, response = run( asyncio.gather( run_server( configuration=QuicConfiguration( certificate=SERVER_CERTIFICATE, idle_timeout=300.0, is_client=False, private_key=SERVER_PRIVATE_KEY, quic_logger=QuicLogger(), ), stateless_retry=True, ), run_client( "127.0.0.1", configuration=QuicConfiguration( is_client=True, idle_timeout=300.0, quic_logger=QuicLogger() ), request=data, ), ) ) at: tests.test_asyncio.SessionTicketStore add(ticket) at: tests.utils run(coro) ===========unchanged ref 3=========== at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_asyncio + def run_server(configuration=None, **kwargs): - def run_server(**kwargs): + if configuration is None: + configuration = QuicConfiguration( + certificate=SERVER_CERTIFICATE, + private_key=SERVER_PRIVATE_KEY, + is_client=False, + ) return await serve( host="::", port="4433", - certificate=SERVER_CERTIFICATE, - private_key=SERVER_PRIVATE_KEY, + configuration=configuration, stream_handler=handle_stream, **kwargs ) ===========changed ref 1=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. """ certificate: Any = None """ The server's TLS certificate. See :func:`cryptography.x509.load_pem_x509_certificate`. .. note:: This is only used by servers. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. """ private_key: Any = None """ The server's TLS private key. See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. .. note:: This is only used by servers. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ + supported_versions: List[int] = field( - supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )
tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_stateless_retry_bad
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<4>:<add> run( <add> run_client( <add> "127.0.0.1", <add> configuration=QuicConfiguration(is_client=True, idle_timeout=4.0), <add> ) <add> ) <del> run(run_client("127.0.0.1", idle_timeout=4.0))
# module: tests.test_asyncio class HighLevelTest(TestCase): @patch("aioquic.quic.retry.QuicRetryTokenHandler.validate_token") def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate): <0> mock_validate.side_effect = ValueError("Decryption failed.") <1> <2> server = run(run_server(stateless_retry=True)) <3> with self.assertRaises(ConnectionError): <4> run(run_client("127.0.0.1", idle_timeout=4.0)) <5> server.close() <6>
===========unchanged ref 0=========== at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_session_ticket server, response = run( asyncio.gather( run_server(session_ticket_handler=store.add), run_client("127.0.0.1", session_ticket_handler=save_ticket), ) ) server, response = run( asyncio.gather( run_server(session_ticket_fetcher=store.pop), run_client( "127.0.0.1", configuration=QuicConfiguration( is_client=True, session_ticket=client_ticket ), ), ) ) server, response = run( asyncio.gather( run_server(session_ticket_handler=store.add), run_client("127.0.0.1", session_ticket_handler=save_ticket), ) ) server, response = run( asyncio.gather( run_server(session_ticket_fetcher=store.pop), run_client( "127.0.0.1", configuration=QuicConfiguration( is_client=True, session_ticket=client_ticket ), ), ) ) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_asyncio + def run_server(configuration=None, **kwargs): - def run_server(**kwargs): + if configuration is None: + configuration = QuicConfiguration( + certificate=SERVER_CERTIFICATE, + private_key=SERVER_PRIVATE_KEY, + is_client=False, + ) return await serve( host="::", port="4433", - certificate=SERVER_CERTIFICATE, - private_key=SERVER_PRIVATE_KEY, + configuration=configuration, stream_handler=handle_stream, **kwargs ) ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_writelines(self): + async def run_client_writelines(host, port=4433): - async def run_client_writelines(host, port=4433, **kwargs): + async with connect(host, port) as client: - async with connect(host, port, **kwargs) as client: reader, writer = await client.create_stream() assert writer.can_write_eof() is True writer.writelines([b"01234567", b"89012345"]) writer.write_eof() return await reader.read() server, response = run( asyncio.gather(run_server(), run_client_writelines("127.0.0.1")) ) self.assertEqual(response, b"5432109876543210") server.close() ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_session_ticket(self): client_ticket = None store = SessionTicketStore() def save_ticket(t): nonlocal client_ticket client_ticket = t # first request server, response = run( asyncio.gather( run_server(session_ticket_handler=store.add), run_client("127.0.0.1", session_ticket_handler=save_ticket), ) ) self.assertEqual(response, b"gnip") server.close() self.assertIsNotNone(client_ticket) # second request server, response = run( asyncio.gather( run_server(session_ticket_fetcher=store.pop), + run_client( + "127.0.0.1", + configuration=QuicConfiguration( + is_client=True, session_ticket=client_ticket - run_client("127.0.0.1", session_ticket=client_ticket), + ), + ), ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("socket.socket.sendto", new_callable=lambda: sendto_with_loss) def test_connect_and_serve_with_packet_loss(self, mock_sendto): """ This test ensures handshake success and stream data is successfully sent and received in the presence of packet loss (randomized 25% in each direction). """ data = b"Z" * 65536 server, response = run( asyncio.gather( run_server( + configuration=QuicConfiguration( + certificate=SERVER_CERTIFICATE, + idle_timeout=300.0, + is_client=False, + private_key=SERVER_PRIVATE_KEY, + quic_logger=QuicLogger(), + ), + stateless_retry=True, - idle_timeout=300.0, quic_logger=QuicLogger(), stateless_retry=True ), run_client( "127.0.0.1", + configuration=QuicConfiguration( + is_client=True, idle_timeout=300.0, quic_logger=QuicLogger() + ), - idle_timeout=300.0, - quic_logger=QuicLogger(), request=data, ), ) ) self.assertEqual(response, data) server.close() ===========changed ref 4=========== # module: aioquic.asyncio.server __all__ = ["serve"] - QuicConnectionHandler = Callable[[QuicConnectionProtocol], None] - ===========changed ref 5=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): + def _connection_terminated(self, protocol: QuicConnectionProtocol): + for cid, proto in list(self._protocols.items()): + if proto == protocol: + del self._protocols[cid] + ===========changed ref 6=========== # module: aioquic.quic.connection @dataclass class QuicReceiveContext: epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath + quic_logger_frames: Optional[List[Any]] time: float ===========changed ref 7=========== # module: tests.test_connection def client_receive_context(client, epoch=tls.Epoch.ONE_RTT): return QuicReceiveContext( epoch=epoch, host_cid=client.host_cid, network_path=client._network_paths[0], + quic_logger_frames=[], time=asyncio.get_event_loop().time(), ) ===========changed ref 8=========== # module: examples.http3-client class HttpClient(QuicConnectionProtocol): + def http_event_received(self, event: HttpEvent): + if ( + isinstance(event, (ResponseReceived, DataReceived)) + and event.stream_id in self._request_events + ): + self._request_events[event.stream_id].append(event) + if event.stream_ended: + request_waiter = self._request_waiter.pop(event.stream_id) + request_waiter.set_result(self._request_events.pop(event.stream_id)) +
tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_version_negotiation
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<5>:<add> configuration=QuicConfiguration( <add> is_client=True, <add> quic_logger=QuicLogger(), <del> quic_logger=QuicLogger(), <6>:<add> supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_22], <del> supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_22], <7>:<add> ),
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_version_negotiation(self): <0> server, response = run( <1> asyncio.gather( <2> run_server(), <3> run_client( <4> "127.0.0.1", <5> quic_logger=QuicLogger(), <6> supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_22], <7> ), <8> ) <9> ) <10> self.assertEqual(response, b"gnip") <11> server.close() <12>
===========unchanged ref 0=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 1=========== at: tests.test_asyncio run_client(host, port=4433, request=b"ping", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(configuration=None, *, create_protocol: Callable=QuicConnectionProtocol) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_sni server, response = run(asyncio.gather(run_server(), run_client("localhost"))) server, response = run(asyncio.gather(run_server(), run_client("localhost"))) at: tests.utils run(coro) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None at: unittest.mock _patcher(target: Any, new: _T, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[_T] _patcher(target: Any, *, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[Union[MagicMock, AsyncMock]] ===========changed ref 0=========== # module: tests.test_asyncio + def run_server(configuration=None, **kwargs): - def run_server(**kwargs): + if configuration is None: + configuration = QuicConfiguration( + certificate=SERVER_CERTIFICATE, + private_key=SERVER_PRIVATE_KEY, + is_client=False, + ) return await serve( host="::", port="4433", - certificate=SERVER_CERTIFICATE, - private_key=SERVER_PRIVATE_KEY, + configuration=configuration, stream_handler=handle_stream, **kwargs ) ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("aioquic.quic.retry.QuicRetryTokenHandler.validate_token") def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate): mock_validate.side_effect = ValueError("Decryption failed.") server = run(run_server(stateless_retry=True)) with self.assertRaises(ConnectionError): + run( + run_client( + "127.0.0.1", + configuration=QuicConfiguration(is_client=True, idle_timeout=4.0), + ) + ) - run(run_client("127.0.0.1", idle_timeout=4.0)) server.close() ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_writelines(self): + async def run_client_writelines(host, port=4433): - async def run_client_writelines(host, port=4433, **kwargs): + async with connect(host, port) as client: - async with connect(host, port, **kwargs) as client: reader, writer = await client.create_stream() assert writer.can_write_eof() is True writer.writelines([b"01234567", b"89012345"]) writer.write_eof() return await reader.read() server, response = run( asyncio.gather(run_server(), run_client_writelines("127.0.0.1")) ) self.assertEqual(response, b"5432109876543210") server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_session_ticket(self): client_ticket = None store = SessionTicketStore() def save_ticket(t): nonlocal client_ticket client_ticket = t # first request server, response = run( asyncio.gather( run_server(session_ticket_handler=store.add), run_client("127.0.0.1", session_ticket_handler=save_ticket), ) ) self.assertEqual(response, b"gnip") server.close() self.assertIsNotNone(client_ticket) # second request server, response = run( asyncio.gather( run_server(session_ticket_fetcher=store.pop), + run_client( + "127.0.0.1", + configuration=QuicConfiguration( + is_client=True, session_ticket=client_ticket - run_client("127.0.0.1", session_ticket=client_ticket), + ), + ), ) ) self.assertEqual(response, b"gnip") server.close()
tests.test_asyncio/HighLevelTest.test_connect_timeout
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<1>:<add> run( <add> run_client( <add> "127.0.0.1", <add> port=4400, <add> configuration=QuicConfiguration(is_client=True, idle_timeout=5), <add> ) <add> ) <del> run(run_client("127.0.0.1", port=4400, idle_timeout=5))
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_timeout(self): <0> with self.assertRaises(ConnectionError): <1> run(run_client("127.0.0.1", port=4400, idle_timeout=5)) <2>
===========unchanged ref 0=========== at: tests.test_asyncio run_server(configuration=None, *, create_protocol: Callable=QuicConnectionProtocol) at: tests.utils run(coro) at: unittest.case.TestCase assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None ===========changed ref 0=========== # module: tests.test_asyncio + def run_server(configuration=None, **kwargs): - def run_server(**kwargs): + if configuration is None: + configuration = QuicConfiguration( + certificate=SERVER_CERTIFICATE, + private_key=SERVER_PRIVATE_KEY, + is_client=False, + ) return await serve( host="::", port="4433", - certificate=SERVER_CERTIFICATE, - private_key=SERVER_PRIVATE_KEY, + configuration=configuration, stream_handler=handle_stream, **kwargs ) ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("aioquic.quic.retry.QuicRetryTokenHandler.validate_token") def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate): mock_validate.side_effect = ValueError("Decryption failed.") server = run(run_server(stateless_retry=True)) with self.assertRaises(ConnectionError): + run( + run_client( + "127.0.0.1", + configuration=QuicConfiguration(is_client=True, idle_timeout=4.0), + ) + ) - run(run_client("127.0.0.1", idle_timeout=4.0)) server.close() ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_version_negotiation(self): server, response = run( asyncio.gather( run_server(), run_client( "127.0.0.1", + configuration=QuicConfiguration( + is_client=True, + quic_logger=QuicLogger(), - quic_logger=QuicLogger(), + supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_22], - supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_22], + ), ), ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_writelines(self): + async def run_client_writelines(host, port=4433): - async def run_client_writelines(host, port=4433, **kwargs): + async with connect(host, port) as client: - async with connect(host, port, **kwargs) as client: reader, writer = await client.create_stream() assert writer.can_write_eof() is True writer.writelines([b"01234567", b"89012345"]) writer.write_eof() return await reader.read() server, response = run( asyncio.gather(run_server(), run_client_writelines("127.0.0.1")) ) self.assertEqual(response, b"5432109876543210") server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_session_ticket(self): client_ticket = None store = SessionTicketStore() def save_ticket(t): nonlocal client_ticket client_ticket = t # first request server, response = run( asyncio.gather( run_server(session_ticket_handler=store.add), run_client("127.0.0.1", session_ticket_handler=save_ticket), ) ) self.assertEqual(response, b"gnip") server.close() self.assertIsNotNone(client_ticket) # second request server, response = run( asyncio.gather( run_server(session_ticket_fetcher=store.pop), + run_client( + "127.0.0.1", + configuration=QuicConfiguration( + is_client=True, session_ticket=client_ticket - run_client("127.0.0.1", session_ticket=client_ticket), + ), + ), ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("socket.socket.sendto", new_callable=lambda: sendto_with_loss) def test_connect_and_serve_with_packet_loss(self, mock_sendto): """ This test ensures handshake success and stream data is successfully sent and received in the presence of packet loss (randomized 25% in each direction). """ data = b"Z" * 65536 server, response = run( asyncio.gather( run_server( + configuration=QuicConfiguration( + certificate=SERVER_CERTIFICATE, + idle_timeout=300.0, + is_client=False, + private_key=SERVER_PRIVATE_KEY, + quic_logger=QuicLogger(), + ), + stateless_retry=True, - idle_timeout=300.0, quic_logger=QuicLogger(), stateless_retry=True ), run_client( "127.0.0.1", + configuration=QuicConfiguration( + is_client=True, idle_timeout=300.0, quic_logger=QuicLogger() + ), - idle_timeout=300.0, - quic_logger=QuicLogger(), request=data, ), ) ) self.assertEqual(response, data) server.close() ===========changed ref 6=========== # module: aioquic.asyncio.server __all__ = ["serve"] - QuicConnectionHandler = Callable[[QuicConnectionProtocol], None] - ===========changed ref 7=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): + def _connection_terminated(self, protocol: QuicConnectionProtocol): + for cid, proto in list(self._protocols.items()): + if proto == protocol: + del self._protocols[cid] + ===========changed ref 8=========== # module: aioquic.quic.connection @dataclass class QuicReceiveContext: epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath + quic_logger_frames: Optional[List[Any]] time: float ===========changed ref 9=========== # module: tests.test_connection def client_receive_context(client, epoch=tls.Epoch.ONE_RTT): return QuicReceiveContext( epoch=epoch, host_cid=client.host_cid, network_path=client._network_paths[0], + quic_logger_frames=[], time=asyncio.get_event_loop().time(), )
tests.test_asyncio/HighLevelTest.test_change_connection_id
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<0>:<add> async def run_client_key_update(host, port=4433): <del> async def run_client_key_update(host, **kwargs): <1>:<add> async with connect(host, port) as client: <del> async with connect(host, 4433, **kwargs) as client:
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_change_connection_id(self): <0> async def run_client_key_update(host, **kwargs): <1> async with connect(host, 4433, **kwargs) as client: <2> await client.ping() <3> client.change_connection_id() <4> await client.ping() <5> <6> server, _ = run( <7> asyncio.gather( <8> run_server(stateless_retry=False), run_client_key_update("127.0.0.1") <9> ) <10> ) <11> server.close() <12>
===========unchanged ref 0=========== at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) ===========unchanged ref 1=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 2=========== at: tests.test_asyncio run_client(host, port=4433, request=b"ping", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(configuration=None, *, create_protocol: Callable=QuicConnectionProtocol) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_stateless_retry_bad server = run(run_server(stateless_retry=True)) at: tests.utils run(coro) ===========changed ref 0=========== # module: tests.test_asyncio + def run_server(configuration=None, **kwargs): - def run_server(**kwargs): + if configuration is None: + configuration = QuicConfiguration( + certificate=SERVER_CERTIFICATE, + private_key=SERVER_PRIVATE_KEY, + is_client=False, + ) return await serve( host="::", port="4433", - certificate=SERVER_CERTIFICATE, - private_key=SERVER_PRIVATE_KEY, + configuration=configuration, stream_handler=handle_stream, **kwargs ) ===========changed ref 1=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. """ certificate: Any = None """ The server's TLS certificate. See :func:`cryptography.x509.load_pem_x509_certificate`. .. note:: This is only used by servers. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. """ private_key: Any = None """ The server's TLS private key. See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. .. note:: This is only used by servers. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ + supported_versions: List[int] = field( - supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_timeout(self): with self.assertRaises(ConnectionError): + run( + run_client( + "127.0.0.1", + port=4400, + configuration=QuicConfiguration(is_client=True, idle_timeout=5), + ) + ) - run(run_client("127.0.0.1", port=4400, idle_timeout=5)) ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("aioquic.quic.retry.QuicRetryTokenHandler.validate_token") def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate): mock_validate.side_effect = ValueError("Decryption failed.") server = run(run_server(stateless_retry=True)) with self.assertRaises(ConnectionError): + run( + run_client( + "127.0.0.1", + configuration=QuicConfiguration(is_client=True, idle_timeout=4.0), + ) + ) - run(run_client("127.0.0.1", idle_timeout=4.0)) server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_version_negotiation(self): server, response = run( asyncio.gather( run_server(), run_client( "127.0.0.1", + configuration=QuicConfiguration( + is_client=True, + quic_logger=QuicLogger(), - quic_logger=QuicLogger(), + supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_22], - supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_22], + ), ), ) ) self.assertEqual(response, b"gnip") server.close()
tests.test_asyncio/HighLevelTest.test_key_update
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<0>:<add> async def run_client_key_update(host, port=4433): <del> async def run_client_key_update(host, **kwargs): <1>:<add> async with connect(host, port) as client: <del> async with connect(host, 4433, **kwargs) as client:
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_key_update(self): <0> async def run_client_key_update(host, **kwargs): <1> async with connect(host, 4433, **kwargs) as client: <2> await client.ping() <3> client.request_key_update() <4> await client.ping() <5> <6> server, _ = run( <7> asyncio.gather( <8> run_server(stateless_retry=False), run_client_key_update("127.0.0.1") <9> ) <10> ) <11> server.close() <12>
===========unchanged ref 0=========== at: aioquic.quic.logger QuicLogger() at: aioquic.quic.packet QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: tests.test_asyncio run_client(host, port=4433, request=b"ping", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_version_negotiation server, response = run( asyncio.gather( run_server(), run_client( "127.0.0.1", configuration=QuicConfiguration( is_client=True, quic_logger=QuicLogger(), supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_22], ), ), ) ) server, response = run( asyncio.gather( run_server(), run_client( "127.0.0.1", configuration=QuicConfiguration( is_client=True, quic_logger=QuicLogger(), supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_22], ), ), ) ) at: tests.utils run(coro) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========unchanged ref 1=========== assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None ===========changed ref 0=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_timeout(self): with self.assertRaises(ConnectionError): + run( + run_client( + "127.0.0.1", + port=4400, + configuration=QuicConfiguration(is_client=True, idle_timeout=5), + ) + ) - run(run_client("127.0.0.1", port=4400, idle_timeout=5)) ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_change_connection_id(self): + async def run_client_key_update(host, port=4433): - async def run_client_key_update(host, **kwargs): + async with connect(host, port) as client: - async with connect(host, 4433, **kwargs) as client: await client.ping() client.change_connection_id() await client.ping() server, _ = run( asyncio.gather( run_server(stateless_retry=False), run_client_key_update("127.0.0.1") ) ) server.close() ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("aioquic.quic.retry.QuicRetryTokenHandler.validate_token") def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate): mock_validate.side_effect = ValueError("Decryption failed.") server = run(run_server(stateless_retry=True)) with self.assertRaises(ConnectionError): + run( + run_client( + "127.0.0.1", + configuration=QuicConfiguration(is_client=True, idle_timeout=4.0), + ) + ) - run(run_client("127.0.0.1", idle_timeout=4.0)) server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_version_negotiation(self): server, response = run( asyncio.gather( run_server(), run_client( "127.0.0.1", + configuration=QuicConfiguration( + is_client=True, + quic_logger=QuicLogger(), - quic_logger=QuicLogger(), + supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_22], - supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_22], + ), ), ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 4=========== # module: tests.test_asyncio + def run_server(configuration=None, **kwargs): - def run_server(**kwargs): + if configuration is None: + configuration = QuicConfiguration( + certificate=SERVER_CERTIFICATE, + private_key=SERVER_PRIVATE_KEY, + is_client=False, + ) return await serve( host="::", port="4433", - certificate=SERVER_CERTIFICATE, - private_key=SERVER_PRIVATE_KEY, + configuration=configuration, stream_handler=handle_stream, **kwargs ) ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_writelines(self): + async def run_client_writelines(host, port=4433): - async def run_client_writelines(host, port=4433, **kwargs): + async with connect(host, port) as client: - async with connect(host, port, **kwargs) as client: reader, writer = await client.create_stream() assert writer.can_write_eof() is True writer.writelines([b"01234567", b"89012345"]) writer.write_eof() return await reader.read() server, response = run( asyncio.gather(run_server(), run_client_writelines("127.0.0.1")) ) self.assertEqual(response, b"5432109876543210") server.close() ===========changed ref 6=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_session_ticket(self): client_ticket = None store = SessionTicketStore() def save_ticket(t): nonlocal client_ticket client_ticket = t # first request server, response = run( asyncio.gather( run_server(session_ticket_handler=store.add), run_client("127.0.0.1", session_ticket_handler=save_ticket), ) ) self.assertEqual(response, b"gnip") server.close() self.assertIsNotNone(client_ticket) # second request server, response = run( asyncio.gather( run_server(session_ticket_fetcher=store.pop), + run_client( + "127.0.0.1", + configuration=QuicConfiguration( + is_client=True, session_ticket=client_ticket - run_client("127.0.0.1", session_ticket=client_ticket), + ), + ), ) ) self.assertEqual(response, b"gnip") server.close()
tests.test_asyncio/HighLevelTest.test_ping
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<0>:<add> async def run_client_ping(host, port=4433): <del> async def run_client_ping(host, **kwargs): <1>:<add> async with connect(host, port) as client: <del> async with connect(host, 4433, **kwargs) as client:
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_ping(self): <0> async def run_client_ping(host, **kwargs): <1> async with connect(host, 4433, **kwargs) as client: <2> await client.ping() <3> await client.ping() <4> <5> server, _ = run( <6> asyncio.gather( <7> run_server(stateless_retry=False), run_client_ping("127.0.0.1") <8> ) <9> ) <10> server.close() <11>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(host: str, port: int, *, configuration: Optional[QuicConfiguration]=None, create_protocol: Optional[Callable]=QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] connect(*args, **kwds) at: aioquic.asyncio.protocol.QuicConnectionProtocol change_connection_id() -> None ping() -> None at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) ===========changed ref 0=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. """ certificate: Any = None """ The server's TLS certificate. See :func:`cryptography.x509.load_pem_x509_certificate`. .. note:: This is only used by servers. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. """ private_key: Any = None """ The server's TLS private key. See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. .. note:: This is only used by servers. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ + supported_versions: List[int] = field( - supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) ===========changed ref 1=========== <s>, - secrets_log_file: Optional[TextIO] = None, - session_ticket: Optional[SessionTicket] = None, + configuration: Optional[QuicConfiguration] = None, + create_protocol: Optional[Callable] = QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, - supported_versions: Optional[List[int]] = None, ) -> AsyncGenerator[QuicConnectionProtocol, None]: """ Connect to a QUIC server at the given `host` and `port`. :meth:`connect()` returns an awaitable. Awaiting it yields a :class:`~aioquic.asyncio.QuicConnectionProtocol` which can be used to create streams. :func:`connect` also accepts the following optional arguments: + * ``configuration`` is a :class:`~aioquic.quic.configuration.QuicConfiguration` + configuration object. + * ``create_protocol`` allows customizing the :class:`~asyncio.Protocol` that + manages the connection. It should be a callable or class accepting the same + arguments as :class:`~aioquic.asyncio.QuicConnectionProtocol` and returning + an instance of :class:`~aioquic.asyncio.QuicConnectionProtocol` or a subclass. - * ``alpn_protocols`` is a list of ALPN protocols to offer in the - ClientHello. - * ``secrets_log_file`` is a file-like object in which to log traffic - secrets. This is useful to analyze traffic captures with Wireshark. - * ``session_ticket`` is a TLS session ticket which should be used for - resumption. * ``session_ticket_handler`` is a callback which is invoked by the TLS engine when a new session ticket is received. * ``stream_handler`` is a callback which is invoked whenever a stream is created. It must accept two arguments: a :class:`asyncio.StreamReader` and a :class:`asyncio.StreamWriter`. """</s> ===========changed ref 2=========== <s>_log_file: Optional[TextIO] = None, - session_ticket: Optional[SessionTicket] = None, + configuration: Optional[QuicConfiguration] = None, + create_protocol: Optional[Callable] = QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler] = None, stream_handler: Optional[QuicStreamHandler] = None, - supported_versions: Optional[List[int]] = None, ) -> AsyncGenerator[QuicConnectionProtocol, None]: # offset: 1 <s> It must accept two arguments: a :class:`asyncio.StreamReader` and a :class:`asyncio.StreamWriter`. """ loop = asyncio.get_event_loop() # if host is not an IP address, pass it to enable SNI try: ipaddress.ip_address(host) server_name = None except ValueError: server_name = host # lookup remote address infos = await loop.getaddrinfo(host, port, type=socket.SOCK_DGRAM) addr = infos[0][4] if len(addr) == 2: addr = ("::ffff:" + addr[0], addr[1], 0, 0) + # prepare QUIC connection + if configuration is None: + configuration = QuicConfiguration(is_client=True) - configuration = QuicConfiguration( - alpn_protocols=alpn_protocols, - is_client=True, - quic_logger=quic_logger, - secrets_log_file=secrets_log_file, - server_name=server_name, - session_ticket=session_ticket, - ) + if server_name is not None: - if idle_timeout is not None: - configuration.idle_timeout = idle_timeout - if supported_versions is not None: - configuration.supported_versions = supported_versions - + configuration.server_</s>
examples.http3-server/HttpServerProtocol.__init__
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<0>:<add> super().__init__(*args, **kwargs) <del> super().__init__(quic) <3>:<del> self._server = server
# module: examples.http3-server class HttpServerProtocol(QuicConnectionProtocol): + def __init__(self, *args, **kwargs): - def __init__(self, quic: QuicConnection, server: HttpServer): <0> super().__init__(quic) <1> self._handlers: Dict[int, HttpRequestHandler] = {} <2> self._http: Optional[HttpConnection] = None <3> self._server = server <4>
===========unchanged ref 0=========== at: argparse._ActionsContainer add_argument(*name_or_flags: Text, action: Union[Text, Type[Action]]=..., nargs: Union[int, Text]=..., const: Any=..., default: Any=..., type: Union[Callable[[Text], _T], Callable[[str], _T], FileType]=..., choices: Iterable[_T]=..., required: bool=..., help: Optional[Text]=..., metavar: Optional[Union[Text, Tuple[Text, ...]]]=..., dest: Optional[Text]=..., version: Text=..., **kwargs: Any) -> Action at: examples.http3-server parser = argparse.ArgumentParser(description="QUIC server") ===========changed ref 0=========== # module: examples.http3-server - class HttpServer(asyncio.DatagramProtocol): - def connection_made(self, transport: asyncio.BaseTransport) -> None: - self._transport = cast(asyncio.DatagramTransport, transport) - ===========changed ref 1=========== # module: examples.http3-server - class HttpServer(asyncio.DatagramProtocol): - def close(self): - for protocol in set(self._protocols.values()): - protocol.close() - self._protocols.clear() - self._transport.close() - ===========changed ref 2=========== # module: examples.http3-server - class HttpServer(asyncio.DatagramProtocol): - def __init__( - self, - *, - application: AsgiApplication, - configuration: QuicConfiguration, - session_ticket_fetcher: Optional[SessionTicketFetcher] = None, - session_ticket_handler: Optional[SessionTicketHandler] = None, - stateless_retry: bool = False, - ) -> None: - self._application = application - self._configuration = configuration - self._loop = asyncio.get_event_loop() - self._protocols: Dict[bytes, QuicConnectionProtocol] = {} - self._session_ticket_fetcher = session_ticket_fetcher - self._session_ticket_handler = session_ticket_handler - self._transport: Optional[asyncio.DatagramTransport] = None - - if stateless_retry: - self._retry = QuicRetryTokenHandler() - else: - self._retry = None - ===========changed ref 3=========== # module: examples.http3-server - class HttpServer(asyncio.DatagramProtocol): - def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: - data = cast(bytes, data) - buf = Buffer(data=data) - header = pull_quic_header(buf, host_cid_length=8) - - # version negotiation - if ( - header.version is not None - and header.version not in self._configuration.supported_versions - ): - self._transport.sendto( - encode_quic_version_negotiation( - source_cid=header.destination_cid, - destination_cid=header.source_cid, - supported_versions=self._configuration.supported_versions, - ), - addr, - ) - return - - protocol = self._protocols.get(header.destination_cid, None) - original_connection_id: Optional[bytes] = None - if protocol is None and header.packet_type == PACKET_TYPE_INITIAL: - # stateless retry - if self._retry is not None: - if not header.token: - # create a retry token - self._transport.sendto( - encode_quic_retry( - version=header.version, - source_cid=os.urandom(8), - destination_cid=header.source_cid, - original_destination_cid=header.destination_cid, - retry_token=self._retry.create_token( - addr, header.destination_cid - ), - ), - addr, - ) - return - else: - # validate retry token - try: - original_connection_id = self._retry.validate_token( - addr, header.token - ) - except ValueError: - return - - # create new connection - connection = QuicConnection( - configuration=self._</s> ===========changed ref 4=========== # module: examples.http3-server - class HttpServer(asyncio.DatagramProtocol): - def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 1 <s>: - return - - # create new connection - connection = QuicConnection( - configuration=self._configuration, - original_connection_id=original_connection_id, - session_ticket_fetcher=self._session_ticket_fetcher, - session_ticket_handler=self._session_ticket_handler, - ) - protocol = HttpServerProtocol(connection, self) - protocol.connection_made(self._transport) - - self._protocols[header.destination_cid] = protocol - self._protocols[connection.host_cid] = protocol - - if protocol is not None: - protocol.datagram_received(data, addr) - ===========changed ref 5=========== # module: aioquic.asyncio.server __all__ = ["serve"] - QuicConnectionHandler = Callable[[QuicConnectionProtocol], None] - ===========changed ref 6=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): + def _connection_terminated(self, protocol: QuicConnectionProtocol): + for cid, proto in list(self._protocols.items()): + if proto == protocol: + del self._protocols[cid] + ===========changed ref 7=========== # module: aioquic.quic.connection @dataclass class QuicReceiveContext: epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath + quic_logger_frames: Optional[List[Any]] time: float ===========changed ref 8=========== # module: tests.test_connection def client_receive_context(client, epoch=tls.Epoch.ONE_RTT): return QuicReceiveContext( epoch=epoch, host_cid=client.host_cid, network_path=client._network_paths[0], + quic_logger_frames=[], time=asyncio.get_event_loop().time(), ) ===========changed ref 9=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_timeout(self): with self.assertRaises(ConnectionError): + run( + run_client( + "127.0.0.1", + port=4400, + configuration=QuicConfiguration(is_client=True, idle_timeout=5), + ) + ) - run(run_client("127.0.0.1", port=4400, idle_timeout=5)) ===========changed ref 10=========== # module: examples.http3-client class HttpClient(QuicConnectionProtocol): + def http_event_received(self, event: HttpEvent): + if ( + isinstance(event, (ResponseReceived, DataReceived)) + and event.stream_id in self._request_events + ): + self._request_events[event.stream_id].append(event) + if event.stream_ended: + request_waiter = self._request_waiter.pop(event.stream_id) + request_waiter.set_result(self._request_events.pop(event.stream_id)) +
examples.http3-server/HttpServerProtocol.quic_event_received
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<0>:<del> if isinstance(event, aioquic.quic.events.ConnectionTerminated): <1>:<del> # remove the connection <2>:<del> for cid, protocol in list(self._server._protocols.items()): <3>:<del> if protocol == self: <4>:<del> del self._server._protocols[cid] <5>:<del> return <6>:<add> if isinstance(event, ProtocolNegotiated): <del> elif isinstance(event, aioquic.quic.events.ProtocolNegotiated): <11>:<del> elif isinstance(event, aioquic.quic.events.ConnectionIdIssued): <12>:<del> self._server._protocols[event.connection_id] = self <13>:<del> elif isinstance(event, aioquic.quic.events.ConnectionIdRetired): <14>:<del> assert self._server._protocols[event.connection_id] == self <15>:<del> del self._server._protocols[event.connection_id]
# module: examples.http3-server class HttpServerProtocol(QuicConnectionProtocol): def quic_event_received(self, event: QuicEvent): <0> if isinstance(event, aioquic.quic.events.ConnectionTerminated): <1> # remove the connection <2> for cid, protocol in list(self._server._protocols.items()): <3> if protocol == self: <4> del self._server._protocols[cid] <5> return <6> elif isinstance(event, aioquic.quic.events.ProtocolNegotiated): <7> if event.alpn_protocol == "h3-22": <8> self._http = H3Connection(self._quic) <9> elif event.alpn_protocol == "hq-22": <10> self._http = H0Connection(self._quic) <11> elif isinstance(event, aioquic.quic.events.ConnectionIdIssued): <12> self._server._protocols[event.connection_id] = self <13> elif isinstance(event, aioquic.quic.events.ConnectionIdRetired): <14> assert self._server._protocols[event.connection_id] == self <15> del self._server._protocols[event.connection_id] <16> <17> #  pass event to the HTTP layer <18> if self._http is not None: <19> for http_event in self._http.handle_event(event): <20> self.http_event_received(http_event) <21>
===========unchanged ref 0=========== at: argparse.ArgumentParser parse_args(args: Optional[Sequence[Text]], namespace: None) -> Namespace parse_args(args: Optional[Sequence[Text]]=...) -> Namespace parse_args(*, namespace: None) -> Namespace parse_args(args: Optional[Sequence[Text]], namespace: _N) -> _N parse_args(*, namespace: _N) -> _N at: argparse._ActionsContainer add_argument(*name_or_flags: Text, action: Union[Text, Type[Action]]=..., nargs: Union[int, Text]=..., const: Any=..., default: Any=..., type: Union[Callable[[Text], _T], Callable[[str], _T], FileType]=..., choices: Iterable[_T]=..., required: bool=..., help: Optional[Text]=..., metavar: Optional[Union[Text, Tuple[Text, ...]]]=..., dest: Optional[Text]=..., version: Text=..., **kwargs: Any) -> Action at: examples.http3-server parser = argparse.ArgumentParser(description="QUIC server") ===========changed ref 0=========== # module: examples.http3-server class HttpServerProtocol(QuicConnectionProtocol): + def __init__(self, *args, **kwargs): - def __init__(self, quic: QuicConnection, server: HttpServer): + super().__init__(*args, **kwargs) - super().__init__(quic) self._handlers: Dict[int, HttpRequestHandler] = {} self._http: Optional[HttpConnection] = None - self._server = server ===========changed ref 1=========== # module: examples.http3-server - class HttpServer(asyncio.DatagramProtocol): - def connection_made(self, transport: asyncio.BaseTransport) -> None: - self._transport = cast(asyncio.DatagramTransport, transport) - ===========changed ref 2=========== # module: examples.http3-server - class HttpServer(asyncio.DatagramProtocol): - def close(self): - for protocol in set(self._protocols.values()): - protocol.close() - self._protocols.clear() - self._transport.close() - ===========changed ref 3=========== # module: examples.http3-server - class HttpServer(asyncio.DatagramProtocol): - def __init__( - self, - *, - application: AsgiApplication, - configuration: QuicConfiguration, - session_ticket_fetcher: Optional[SessionTicketFetcher] = None, - session_ticket_handler: Optional[SessionTicketHandler] = None, - stateless_retry: bool = False, - ) -> None: - self._application = application - self._configuration = configuration - self._loop = asyncio.get_event_loop() - self._protocols: Dict[bytes, QuicConnectionProtocol] = {} - self._session_ticket_fetcher = session_ticket_fetcher - self._session_ticket_handler = session_ticket_handler - self._transport: Optional[asyncio.DatagramTransport] = None - - if stateless_retry: - self._retry = QuicRetryTokenHandler() - else: - self._retry = None - ===========changed ref 4=========== # module: examples.http3-server - class HttpServer(asyncio.DatagramProtocol): - def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: - data = cast(bytes, data) - buf = Buffer(data=data) - header = pull_quic_header(buf, host_cid_length=8) - - # version negotiation - if ( - header.version is not None - and header.version not in self._configuration.supported_versions - ): - self._transport.sendto( - encode_quic_version_negotiation( - source_cid=header.destination_cid, - destination_cid=header.source_cid, - supported_versions=self._configuration.supported_versions, - ), - addr, - ) - return - - protocol = self._protocols.get(header.destination_cid, None) - original_connection_id: Optional[bytes] = None - if protocol is None and header.packet_type == PACKET_TYPE_INITIAL: - # stateless retry - if self._retry is not None: - if not header.token: - # create a retry token - self._transport.sendto( - encode_quic_retry( - version=header.version, - source_cid=os.urandom(8), - destination_cid=header.source_cid, - original_destination_cid=header.destination_cid, - retry_token=self._retry.create_token( - addr, header.destination_cid - ), - ), - addr, - ) - return - else: - # validate retry token - try: - original_connection_id = self._retry.validate_token( - addr, header.token - ) - except ValueError: - return - - # create new connection - connection = QuicConnection( - configuration=self._</s> ===========changed ref 5=========== # module: examples.http3-server - class HttpServer(asyncio.DatagramProtocol): - def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 1 <s>: - return - - # create new connection - connection = QuicConnection( - configuration=self._configuration, - original_connection_id=original_connection_id, - session_ticket_fetcher=self._session_ticket_fetcher, - session_ticket_handler=self._session_ticket_handler, - ) - protocol = HttpServerProtocol(connection, self) - protocol.connection_made(self._transport) - - self._protocols[header.destination_cid] = protocol - self._protocols[connection.host_cid] = protocol - - if protocol is not None: - protocol.datagram_received(data, addr) - ===========changed ref 6=========== # module: aioquic.asyncio.server __all__ = ["serve"] - QuicConnectionHandler = Callable[[QuicConnectionProtocol], None] - ===========changed ref 7=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): + def _connection_terminated(self, protocol: QuicConnectionProtocol): + for cid, proto in list(self._protocols.items()): + if proto == protocol: + del self._protocols[cid] + ===========changed ref 8=========== # module: aioquic.quic.connection @dataclass class QuicReceiveContext: epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath + quic_logger_frames: Optional[List[Any]] time: float ===========changed ref 9=========== # module: tests.test_connection def client_receive_context(client, epoch=tls.Epoch.ONE_RTT): return QuicReceiveContext( epoch=epoch, host_cid=client.host_cid, network_path=client._network_paths[0], + quic_logger_frames=[], time=asyncio.get_event_loop().time(), ) ===========changed ref 10=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_timeout(self): with self.assertRaises(ConnectionError): + run( + run_client( + "127.0.0.1", + port=4400, + configuration=QuicConfiguration(is_client=True, idle_timeout=5), + ) + ) - run(run_client("127.0.0.1", port=4400, idle_timeout=5))
examples.http3-server/HttpServerProtocol.http_event_received
Modified
aiortc~aioquic
60258445de4728a971e4124be18997fa61ee87a2
Merge pull request #19 from pgjones/master
<38>:<add> asyncio.ensure_future(handler.run_asgi(application)) <del> asyncio.ensure_future(handler.run_asgi(self._server._application))
# module: examples.http3-server class HttpServerProtocol(QuicConnectionProtocol): def http_event_received(self, event: HttpEvent) -> None: <0> if isinstance(event, RequestReceived): <1> headers = [] <2> raw_path = b"" <3> method = "" <4> for header, value in event.headers: <5> if header == b":authority": <6> headers.append((b"host", value)) <7> elif header == b":method": <8> method = value.decode("utf8") <9> elif header == b":path": <10> raw_path = value <11> elif header and not header.startswith(b":"): <12> headers.append((header, value)) <13> <14> if b"?" in raw_path: <15> path_bytes, query_string = raw_path.split(b"?", maxsplit=1) <16> else: <17> path_bytes, query_string = raw_path, b"" <18> <19> scope = { <20> "headers": headers, <21> "http_version": "0.9" if isinstance(self._http, H0Connection) else "3", <22> "method": method, <23> "path": path_bytes.decode("utf8"), <24> "query_string": query_string, <25> "raw_path": raw_path, <26> "root_path": "", <27> "scheme": "https", <28> "type": "http", <29> } <30> <31> handler = HttpRequestHandler( <32> connection=self._http, <33> scope=scope, <34> send_pending=self._send_pending, <35> stream_id=event.stream_id, <36> ) <37> self._handlers[event.stream_id] = handler <38> asyncio.ensure_future(handler.run_asgi(self._server._application)) <39> elif isinstance(event, DataReceived): <40> handler = self._handlers[event.stream_id] <41> handler.queue.put_nowait( <42> { <43> "type": "http.request", <44> "body": event.data</s>
===========below chunk 0=========== # module: examples.http3-server class HttpServerProtocol(QuicConnectionProtocol): def http_event_received(self, event: HttpEvent) -> None: # offset: 1 "more_body": not event.stream_ended, } ) ===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.asyncio.server serve(host: str, port: int, *, certificate: Any, private_key: Any, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, quic_logger: Optional[QuicLogger]=None, stream_handler: QuicStreamHandler=None, secrets_log_file: Optional[TextIO]=None, session_ticket_fetcher: Optional[SessionTicketFetcher]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stateless_retry: bool=False) -> QuicServer at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.quic.logger QuicLogger() at: asyncio.events get_event_loop() -> AbstractEventLoop ===========unchanged ref 1=========== at: asyncio.events.AbstractEventLoop run_until_complete(future: Generator[Any, None, _T]) -> _T run_until_complete(future: Awaitable[_T]) -> _T at: examples.http3-server uvloop = None SessionTicketStore() args = parser.parse_args() at: importlib import_module(name: str, package: Optional[str]=...) -> types.ModuleType at: io.BufferedReader read(self, size: Optional[int]=..., /) -> bytes at: io.FileIO read(self, size: int=..., /) -> bytes at: logging INFO = 20 DEBUG = 10 basicConfig(*, filename: Optional[StrPath]=..., filemode: str=..., format: str=..., datefmt: Optional[str]=..., style: str=..., level: Optional[_Level]=..., stream: Optional[IO[str]]=..., handlers: Optional[Iterable[Handler]]=...) -> None at: typing.IO __slots__ = () read(n: int=...) -> AnyStr ===========changed ref 0=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. """ certificate: Any = None """ The server's TLS certificate. See :func:`cryptography.x509.load_pem_x509_certificate`. .. note:: This is only used by servers. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. """ private_key: Any = None """ The server's TLS private key. See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. .. note:: This is only used by servers. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ + supported_versions: List[int] = field( - supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) ===========changed ref 1=========== <s>Logger] = None, - stream_handler: QuicStreamHandler = None, - secrets_log_file: Optional[TextIO] = None, + configuration: QuicConfiguration, + create_protocol: Callable = QuicConnectionProtocol, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, + stream_handler: QuicStreamHandler = None, ) -> QuicServer: """ Start a QUIC server at the given `host` and `port`. - :func:`serve` requires a TLS certificate and private key, which can be - specified using the following arguments: - - * ``certificate`` is the server's TLS certificate. - See :func:`cryptography.x509.load_pem_x509_certificate`. - * ``private_key`` is the server's private key. - See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. + :func:`serve` requires a :class:`~aioquic.quic.configuration.QuicConfiguration` + containing TLS certificate and private key as the ``configuration`` argument. :func:`serve` also accepts the following optional arguments: + * ``create_protocol`` allows customizing the :class:`~asyncio.Protocol` that + manages the connection. It should be a callable or class accepting the same + arguments as :class:`~aioquic.asyncio.QuicConnectionProtocol` and returning + an instance of :class:`~aioquic.asyncio.QuicConnectionProtocol` or a subclass. - * ``secrets_log_file`` is a file-like object in which to log traffic - secrets. This is useful to analyze traffic captures with Wireshark. * ``session_ticket_fetcher`` is a callback which is invoked by the TLS engine when a session ticket is presented by the peer. It should return the session ticket with the specified ID or `None` if it is not found. * ``</s>