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
|
---|---|---|---|---|---|---|---|
examples.interop/test_version_negotiation
|
Modified
|
aiortc~aioquic
|
60258445de4728a971e4124be18997fa61ee87a2
|
Merge pull request #19 from pgjones/master
|
<0>:<add> configuration.supported_versions = [0x1A2A3A4A, QuicProtocolVersion.DRAFT_22]
<add>
<del> quic_logger = QuicLogger()
<2>:<del> config.host,
<3>:<del> config.port,
<4>:<del> quic_logger=quic_logger,
<5>:<del> supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_22],
<6>:<del> **kwargs
<7>:<add> server.host, server.port, configuration=configuration
<11>:<add> for stamp, category, event, data in configuration.quic_logger.to_dict()[
<del> for stamp, category, event, data in quic_logger.to_dict()["traces"][0][
<12>:<add> "traces"
<del> "events"
<13>:<add> ][0]["events"]:
<del> ]:
<19>:<add> server.result |= Result.V
<del> config.result |= Result.V
|
# module: examples.interop
+ def test_version_negotiation(server: Server, configuration: QuicConfiguration):
- def test_version_negotiation(config, **kwargs):
<0> quic_logger = QuicLogger()
<1> async with connect(
<2> config.host,
<3> config.port,
<4> quic_logger=quic_logger,
<5> supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_22],
<6> **kwargs
<7> ) as connection:
<8> await connection.ping()
<9>
<10> # check log
<11> for stamp, category, event, data in quic_logger.to_dict()["traces"][0][
<12> "events"
<13> ]:
<14> if (
<15> category == "TRANSPORT"
<16> and event == "PACKET_RECEIVED"
<17> and data["type"] == "VERSION_NEGOTIATION"
<18> ):
<19> config.result |= Result.V
<20>
|
===========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.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.logger.QuicLogger
to_dict() -> Dict[str, Any]
at: aioquic.quic.packet
QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int)
QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
at: examples.interop
Result()
Server(name: str, host: str, port: int=4433, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)))
at: examples.interop.Server
name: str
host: str
port: int = 4433
retry_port: Optional[int] = 4434
path: str = "/"
result: Result = field(default_factory=lambda: Result(0))
===========changed ref 0===========
# module: examples.interop
+ @dataclass
+ class Server:
+ name: str
+ host: str
+ port: int = 4433
+ retry_port: Optional[int] = 4434
+ path: str = "/"
+ result: Result = field(default_factory=lambda: Result(0))
+
===========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===========
<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>
|
examples.interop/test_handshake_and_close
|
Modified
|
aiortc~aioquic
|
60258445de4728a971e4124be18997fa61ee87a2
|
Merge pull request #19 from pgjones/master
|
<0>:<add> async with connect(
<add> server.host, server.port, configuration=configuration
<add> ) as connection:
<del> async with connect(config.host, config.port, **kwargs) as connection:
<2>:<add> server.result |= Result.H
<del> config.result |= Result.H
<3>:<add> server.result |= Result.C
<del> config.result |= Result.C
|
# module: examples.interop
+ def test_handshake_and_close(server: Server, configuration: QuicConfiguration):
- def test_handshake_and_close(config, **kwargs):
<0> async with connect(config.host, config.port, **kwargs) as connection:
<1> await connection.ping()
<2> config.result |= Result.H
<3> config.result |= Result.C
<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, 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: examples.interop
Result()
at: examples.interop.Server
host: str
port: int = 4433
result: Result = field(default_factory=lambda: Result(0))
===========changed ref 0===========
<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 1===========
<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>
===========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: 2
<s> server_name
connection = QuicConnection(
configuration=configuration, session_ticket_handler=session_ticket_handler
)
# connect
_, protocol = await loop.create_datagram_endpoint(
+ lambda: create_protocol(connection, stream_handler=stream_handler),
- 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()
===========changed ref 3===========
# module: examples.interop
+ @dataclass
+ class Server:
+ name: str
+ host: str
+ port: int = 4433
+ retry_port: Optional[int] = 4434
+ path: str = "/"
+ result: Result = field(default_factory=lambda: Result(0))
+
===========changed ref 4===========
# module: examples.interop
- @dataclass
- class Config:
- name: str
- host: str
- port: int = 4433
- retry_port: Optional[int] = 4434
- path: str = "/"
- result: Result = field(default_factory=lambda: Result(0))
-
|
examples.interop/test_stateless_retry
|
Modified
|
aiortc~aioquic
|
60258445de4728a971e4124be18997fa61ee87a2
|
Merge pull request #19 from pgjones/master
|
<0>:<del> quic_logger = QuicLogger()
<2>:<add> server.host, server.retry_port, configuration=configuration
<del> config.host, config.retry_port, quic_logger=quic_logger, **kwargs
<7>:<add> for stamp, category, event, data in configuration.quic_logger.to_dict()[
<del> for stamp, category, event, data in quic_logger.to_dict()["traces"][0][
<8>:<add> "traces"
<del> "events"
<9>:<add> ][0]["events"]:
<del> ]:
<15>:<add> server.result |= Result.S
<del> config.result |= Result.S
|
# module: examples.interop
+ def test_stateless_retry(server: Server, configuration: QuicConfiguration):
- def test_stateless_retry(config, **kwargs):
<0> quic_logger = QuicLogger()
<1> async with connect(
<2> config.host, config.retry_port, quic_logger=quic_logger, **kwargs
<3> ) as connection:
<4> await connection.ping()
<5>
<6> # check log
<7> for stamp, category, event, data in quic_logger.to_dict()["traces"][0][
<8> "events"
<9> ]:
<10> if (
<11> category == "TRANSPORT"
<12> and event == "PACKET_RECEIVED"
<13> and data["type"] == "RETRY"
<14> ):
<15> config.result |= Result.S
<16>
|
===========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.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
to_dict() -> Dict[str, Any]
at: examples.interop
Result()
Server(name: str, host: str, port: int=4433, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)))
at: examples.interop.Server
host: str
retry_port: Optional[int] = 4434
result: Result = field(default_factory=lambda: Result(0))
===========changed ref 0===========
# module: examples.interop
+ @dataclass
+ class Server:
+ name: str
+ host: str
+ port: int = 4433
+ retry_port: Optional[int] = 4434
+ path: str = "/"
+ result: Result = field(default_factory=lambda: Result(0))
+
===========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===========
<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>
|
examples.interop/test_http_0
|
Modified
|
aiortc~aioquic
|
60258445de4728a971e4124be18997fa61ee87a2
|
Merge pull request #19 from pgjones/master
|
<0>:<add> if server.path is None:
<del> if config.path is None:
<3>:<add> configuration.alpn_protocols = ["hq-22"]
<add> async with connect(
<add> server.host, server.port, configuration=configuration
<add> ) as connection:
<del> kwargs["alpn_protocols"] = ["hq-22"]
<4>:<del> async with connect(config.host, config.port, **kwargs) as connection:
<5>:<add> response = await http_request(connection, server.path)
<del> response = await http_request(connection, config.path)
<7>:<add> server.result |= Result.D
<del> config.result |= Result.D
|
# module: examples.interop
+ def test_http_0(server: Server, configuration: QuicConfiguration):
- def test_http_0(config, **kwargs):
<0> if config.path is None:
<1> return
<2>
<3> kwargs["alpn_protocols"] = ["hq-22"]
<4> async with connect(config.host, config.port, **kwargs) as connection:
<5> response = await http_request(connection, config.path)
<6> if response:
<7> config.result |= Result.D
<8>
|
===========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.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
at: examples.interop
Server(name: str, host: str, port: int=4433, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)))
http_request(connection: QuicConnectionProtocol, path: str)
at: examples.interop.Server
host: str
port: int = 4433
path: str = "/"
===========changed ref 0===========
# module: examples.interop
+ @dataclass
+ class Server:
+ name: str
+ host: str
+ port: int = 4433
+ retry_port: Optional[int] = 4434
+ path: str = "/"
+ result: Result = field(default_factory=lambda: Result(0))
+
===========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===========
<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>
|
examples.interop/test_http_3
|
Modified
|
aiortc~aioquic
|
60258445de4728a971e4124be18997fa61ee87a2
|
Merge pull request #19 from pgjones/master
|
<0>:<add> if server.path is None:
<del> if config.path is None:
<3>:<add> configuration.alpn_protocols = ["h3-22"]
<add> async with connect(
<add> server.host, server.port, configuration=configuration
<add> ) as connection:
<del> kwargs["alpn_protocols"] = ["h3-22"]
<4>:<del> async with connect(config.host, config.port, **kwargs) as connection:
<5>:<add> response = await http3_request(connection, server.host, server.path)
<del> response = await http3_request(connection, config.host, config.path)
<7>:<add> server.result |= Result.D
<del> config.result |= Result.D
<8>:<add> server.result |= Result.three
<del> config.result |= Result.three
|
# module: examples.interop
+ def test_http_3(server: Server, configuration: QuicConfiguration):
- def test_http_3(config, **kwargs):
<0> if config.path is None:
<1> return
<2>
<3> kwargs["alpn_protocols"] = ["h3-22"]
<4> async with connect(config.host, config.port, **kwargs) as connection:
<5> response = await http3_request(connection, config.host, config.path)
<6> if response:
<7> config.result |= Result.D
<8> config.result |= Result.three
<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.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
at: examples.interop
Server(name: str, host: str, port: int=4433, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)))
at: examples.interop.Server
host: str
port: int = 4433
path: str = "/"
===========changed ref 0===========
# module: examples.interop
+ @dataclass
+ class Server:
+ name: str
+ host: str
+ port: int = 4433
+ retry_port: Optional[int] = 4434
+ path: str = "/"
+ result: Result = field(default_factory=lambda: Result(0))
+
===========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===========
<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 3===========
<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.interop/test_session_resumption
|
Modified
|
aiortc~aioquic
|
60258445de4728a971e4124be18997fa61ee87a2
|
Merge pull request #19 from pgjones/master
|
<8>:<add> server.host,
<add> server.port,
<add> configuration=configuration,
<del> config.host,
<9>:<del> config.port,
<11>:<del> **kwargs
<17>:<add> configuration.session_ticket = saved_ticket
<18>:<add> server.host, server.port, configuration=configuration
<del> config.host, config.port, session_ticket=saved_ticket, **kwargs
<24>:<add> server.result |= Result.R
<del> config.result |= Result.R
<28>:<add> server.result |= Result.Z
<del> config.result |= Result.Z
|
# module: examples.interop
+ def test_session_resumption(server: Server, configuration: QuicConfiguration):
- 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._quic.tls.session_resumed:
<24> config.result |= Result.R
<25>
<26> # check early data was accepted
<27> if connection._quic.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, 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.asyncio.protocol.QuicConnectionProtocol.__init__
self._quic = quic
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
session_ticket: Optional[SessionTicket] = None
at: aioquic.quic.connection.QuicConnection._initialize
self.tls = tls.Context(is_client=self._is_client, logger=self._logger)
at: examples.interop
Result()
Server(name: str, host: str, port: int=4433, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)))
at: examples.interop.Server
host: str
port: int = 4433
===========unchanged ref 1===========
result: Result = field(default_factory=lambda: Result(0))
===========changed ref 0===========
# module: examples.interop
+ @dataclass
+ class Server:
+ name: str
+ host: str
+ port: int = 4433
+ retry_port: Optional[int] = 4434
+ path: str = "/"
+ result: Result = field(default_factory=lambda: Result(0))
+
===========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===========
<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>
|
examples.interop/test_key_update
|
Modified
|
aiortc~aioquic
|
60258445de4728a971e4124be18997fa61ee87a2
|
Merge pull request #19 from pgjones/master
|
<0>:<add> async with connect(
<add> server.host, server.port, configuration=configuration
<add> ) as connection:
<del> async with connect(config.host, config.port, **kwargs) as connection:
<10>:<add> server.result |= Result.U
<del> config.result |= Result.U
|
# module: examples.interop
+ def test_key_update(server: Server, configuration: QuicConfiguration):
- def test_key_update(config, **kwargs):
<0> async with connect(config.host, config.port, **kwargs) as connection:
<1> # cause some traffic
<2> await connection.ping()
<3>
<4> # request key update
<5> connection.request_key_update()
<6>
<7> # cause more traffic
<8> await connection.ping()
<9>
<10> config.result |= Result.U
<11>
|
===========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.asyncio.protocol.QuicConnectionProtocol.__init__
self._quic = quic
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._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()
===========unchanged ref 1===========
Server(name: str, host: str, port: int=4433, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)))
at: examples.interop.Server
host: str
port: int = 4433
result: Result = field(default_factory=lambda: Result(0))
===========changed ref 0===========
# module: examples.interop
+ @dataclass
+ class Server:
+ name: str
+ host: str
+ port: int = 4433
+ retry_port: Optional[int] = 4434
+ path: str = "/"
+ result: Result = field(default_factory=lambda: Result(0))
+
===========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===========
<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>
|
examples.interop/test_spin_bit
|
Modified
|
aiortc~aioquic
|
60258445de4728a971e4124be18997fa61ee87a2
|
Merge pull request #19 from pgjones/master
|
<0>:<del> quic_logger = QuicLogger()
<2>:<add> server.host, server.port, configuration=configuration
<del> config.host, config.port, quic_logger=quic_logger, **kwargs
<9>:<add> for stamp, category, event, data in configuration.quic_logger.to_dict()[
<del> for stamp, category, event, data in quic_logger.to_dict()["traces"][0][
<10>:<add> "traces"
<del> "events"
<11>:<add> ][0]["events"]:
<del> ]:
<15>:<add> server.result |= Result.P
<del> config.result |= Result.P
|
# module: examples.interop
+ def test_spin_bit(server: Server, configuration: QuicConfiguration):
- def test_spin_bit(config, **kwargs):
<0> quic_logger = QuicLogger()
<1> async with connect(
<2> config.host, config.port, quic_logger=quic_logger, **kwargs
<3> ) as connection:
<4> for i in range(5):
<5> await connection.ping()
<6>
<7> # check log
<8> spin_bits = set()
<9> for stamp, category, event, data in quic_logger.to_dict()["traces"][0][
<10> "events"
<11> ]:
<12> if category == "CONNECTIVITY" and event == "SPIN_BIT_UPDATE":
<13> spin_bits.add(data["state"])
<14> if len(spin_bits) == 2:
<15> config.result |= Result.P
<16>
|
===========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.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
to_dict() -> Dict[str, Any]
at: examples.interop
Result()
Server(name: str, host: str, port: int=4433, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)))
at: examples.interop.Server
host: str
port: int = 4433
result: Result = field(default_factory=lambda: Result(0))
===========changed ref 0===========
# module: examples.interop
+ @dataclass
+ class Server:
+ name: str
+ host: str
+ port: int = 4433
+ retry_port: Optional[int] = 4434
+ path: str = "/"
+ result: Result = field(default_factory=lambda: Result(0))
+
===========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===========
<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>
|
examples.interop/print_result
|
Modified
|
aiortc~aioquic
|
60258445de4728a971e4124be18997fa61ee87a2
|
Merge pull request #19 from pgjones/master
|
<0>:<add> result = str(server.result).replace("three", "3")
<del> result = str(config.result).replace("three", "3")
<2>:<add> print("%s%s%s" % (server.name, " " * (20 - len(server.name)), result))
<del> print("%s%s%s" % (config.name, " " * (20 - len(config.name)), result))
|
# module: examples.interop
+ def print_result(server: Server) -> None:
- def print_result(config: Config) -> None:
<0> result = str(config.result).replace("three", "3")
<1> result = result[0:7] + " " + result[7:13] + " " + result[13:]
<2> print("%s%s%s" % (config.name, " " * (20 - len(config.name)), result))
<3>
|
===========unchanged ref 0===========
at: examples.interop
Result()
at: examples.interop.Server
result: Result = field(default_factory=lambda: Result(0))
at: examples.interop.test_spin_bit
spin_bits = set()
===========changed ref 0===========
# module: examples.interop
+ def test_key_update(server: Server, configuration: QuicConfiguration):
- def test_key_update(config, **kwargs):
+ async with connect(
+ server.host, server.port, configuration=configuration
+ ) as connection:
- async with connect(config.host, config.port, **kwargs) as connection:
# cause some traffic
await connection.ping()
# request key update
connection.request_key_update()
# cause more traffic
await connection.ping()
+ server.result |= Result.U
- config.result |= Result.U
===========changed ref 1===========
# module: examples.interop
+ def test_handshake_and_close(server: Server, configuration: QuicConfiguration):
- def test_handshake_and_close(config, **kwargs):
+ async with connect(
+ server.host, server.port, configuration=configuration
+ ) as connection:
- async with connect(config.host, config.port, **kwargs) as connection:
await connection.ping()
+ server.result |= Result.H
- config.result |= Result.H
+ server.result |= Result.C
- config.result |= Result.C
===========changed ref 2===========
# module: examples.interop
+ def test_spin_bit(server: Server, configuration: QuicConfiguration):
- def test_spin_bit(config, **kwargs):
- quic_logger = QuicLogger()
async with connect(
+ server.host, server.port, configuration=configuration
- config.host, config.port, quic_logger=quic_logger, **kwargs
) as connection:
for i in range(5):
await connection.ping()
# check log
spin_bits = set()
+ for stamp, category, event, data in configuration.quic_logger.to_dict()[
- for stamp, category, event, data in quic_logger.to_dict()["traces"][0][
+ "traces"
- "events"
+ ][0]["events"]:
- ]:
if category == "CONNECTIVITY" and event == "SPIN_BIT_UPDATE":
spin_bits.add(data["state"])
if len(spin_bits) == 2:
+ server.result |= Result.P
- config.result |= Result.P
===========changed ref 3===========
# module: examples.interop
+ def test_http_0(server: Server, configuration: QuicConfiguration):
- def test_http_0(config, **kwargs):
+ if server.path is None:
- if config.path is None:
return
+ configuration.alpn_protocols = ["hq-22"]
+ async with connect(
+ server.host, server.port, configuration=configuration
+ ) as connection:
- kwargs["alpn_protocols"] = ["hq-22"]
- async with connect(config.host, config.port, **kwargs) as connection:
+ response = await http_request(connection, server.path)
- response = await http_request(connection, config.path)
if response:
+ server.result |= Result.D
- config.result |= Result.D
===========changed ref 4===========
# module: examples.interop
+ @dataclass
+ class Server:
+ name: str
+ host: str
+ port: int = 4433
+ retry_port: Optional[int] = 4434
+ path: str = "/"
+ result: Result = field(default_factory=lambda: Result(0))
+
===========changed ref 5===========
# module: examples.interop
- @dataclass
- class Config:
- name: str
- host: str
- port: int = 4433
- retry_port: Optional[int] = 4434
- path: str = "/"
- result: Result = field(default_factory=lambda: Result(0))
-
===========changed ref 6===========
# module: examples.interop
+ def test_http_3(server: Server, configuration: QuicConfiguration):
- def test_http_3(config, **kwargs):
+ if server.path is None:
- if config.path is None:
return
+ configuration.alpn_protocols = ["h3-22"]
+ async with connect(
+ server.host, server.port, configuration=configuration
+ ) as connection:
- kwargs["alpn_protocols"] = ["h3-22"]
- async with connect(config.host, config.port, **kwargs) as connection:
+ response = await http3_request(connection, server.host, server.path)
- response = await http3_request(connection, config.host, config.path)
if response:
+ server.result |= Result.D
- config.result |= Result.D
+ server.result |= Result.three
- config.result |= Result.three
===========changed ref 7===========
# module: examples.interop
+ def test_stateless_retry(server: Server, configuration: QuicConfiguration):
- def test_stateless_retry(config, **kwargs):
- quic_logger = QuicLogger()
async with connect(
+ server.host, server.retry_port, configuration=configuration
- config.host, config.retry_port, quic_logger=quic_logger, **kwargs
) as connection:
await connection.ping()
# check log
+ for stamp, category, event, data in configuration.quic_logger.to_dict()[
- for stamp, category, event, data in quic_logger.to_dict()["traces"][0][
+ "traces"
- "events"
+ ][0]["events"]:
- ]:
if (
category == "TRANSPORT"
and event == "PACKET_RECEIVED"
and data["type"] == "RETRY"
):
+ server.result |= Result.S
- config.result |= Result.S
===========changed ref 8===========
# module: examples.interop
+ def test_session_resumption(server: Server, configuration: QuicConfiguration):
- 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(
+ server.host,
+ server.port,
+ configuration=configuration,
- 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:
+ configuration.session_ticket = saved_ticket
async with connect(
+ server.host, server.port, configuration=configuration
- config.host, config.port, session_ticket=saved_ticket, **kwargs
) as connection:
await connection.ping()
# check session was resumed
if connection._quic.tls.session_resumed:
+ server.result |= Result.R
- config.result |= Result.R
# check early data was accepted
if connection._quic.tls.early_data_accepted:
+ server.result |= Result.Z
- config.result |= Result.Z
|
examples.interop/run
|
Modified
|
aiortc~aioquic
|
60258445de4728a971e4124be18997fa61ee87a2
|
Merge pull request #19 from pgjones/master
|
<0>:<add> for server in servers:
<del> for config in configs:
<2>:<add> print("\n=== %s %s ===\n" % (server.name, test_name))
<del> print("\n=== %s %s ===\n" % (config.name, test_name))
<3>:<add> configuration = QuicConfiguration(
<add> alpn_protocols=["hq-22", "h3-22"],
<add> is_client=True,
<add> quic_logger=QuicLogger(),
<add> )
<4>:<add> await asyncio.wait_for(test_func(server, configuration), timeout=5)
<del> await asyncio.wait_for(test_func(config, **kwargs), timeout=5)
<8>:<add> print_result(server)
<del> print_result(config)
<11>:<add> if len(servers) > 1:
<del> if len(configs) > 1:
<13>:<add> for server in servers:
<del> for config in configs:
<14>:<add> print_result(server)
<del> print_result(config)
|
# module: examples.interop
+ def run(servers, tests) -> None:
- def run(configs, tests, **kwargs) -> None:
<0> for config in configs:
<1> for test_name, test_func in tests:
<2> print("\n=== %s %s ===\n" % (config.name, test_name))
<3> try:
<4> await asyncio.wait_for(test_func(config, **kwargs), timeout=5)
<5> except Exception as exc:
<6> print(exc)
<7> print("")
<8> print_result(config)
<9>
<10> # print summary
<11> if len(configs) > 1:
<12> print("SUMMARY")
<13> for config in configs:
<14> print_result(config)
<15>
|
===========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()
at: examples.interop
Server(name: str, host: str, port: int=4433, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)))
at: examples.interop.Server
name: str
result: Result = field(default_factory=lambda: Result(0))
===========changed ref 0===========
# module: examples.interop
+ @dataclass
+ class Server:
+ name: str
+ host: str
+ port: int = 4433
+ retry_port: Optional[int] = 4434
+ path: str = "/"
+ result: Result = field(default_factory=lambda: Result(0))
+
===========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: examples.interop
+ def print_result(server: Server) -> None:
- def print_result(config: Config) -> None:
+ result = str(server.result).replace("three", "3")
- result = str(config.result).replace("three", "3")
result = result[0:7] + " " + result[7:13] + " " + result[13:]
+ print("%s%s%s" % (server.name, " " * (20 - len(server.name)), result))
- print("%s%s%s" % (config.name, " " * (20 - len(config.name)), result))
===========changed ref 3===========
# module: examples.interop
+ def test_key_update(server: Server, configuration: QuicConfiguration):
- def test_key_update(config, **kwargs):
+ async with connect(
+ server.host, server.port, configuration=configuration
+ ) as connection:
- async with connect(config.host, config.port, **kwargs) as connection:
# cause some traffic
await connection.ping()
# request key update
connection.request_key_update()
# cause more traffic
await connection.ping()
+ server.result |= Result.U
- config.result |= Result.U
===========changed ref 4===========
# module: examples.interop
+ def test_handshake_and_close(server: Server, configuration: QuicConfiguration):
- def test_handshake_and_close(config, **kwargs):
+ async with connect(
+ server.host, server.port, configuration=configuration
+ ) as connection:
- async with connect(config.host, config.port, **kwargs) as connection:
await connection.ping()
+ server.result |= Result.H
- config.result |= Result.H
+ server.result |= Result.C
- config.result |= Result.C
===========changed ref 5===========
# module: examples.interop
+ def test_spin_bit(server: Server, configuration: QuicConfiguration):
- def test_spin_bit(config, **kwargs):
- quic_logger = QuicLogger()
async with connect(
+ server.host, server.port, configuration=configuration
- config.host, config.port, quic_logger=quic_logger, **kwargs
) as connection:
for i in range(5):
await connection.ping()
# check log
spin_bits = set()
+ for stamp, category, event, data in configuration.quic_logger.to_dict()[
- for stamp, category, event, data in quic_logger.to_dict()["traces"][0][
+ "traces"
- "events"
+ ][0]["events"]:
- ]:
if category == "CONNECTIVITY" and event == "SPIN_BIT_UPDATE":
spin_bits.add(data["state"])
if len(spin_bits) == 2:
+ server.result |= Result.P
- config.result |= Result.P
===========changed ref 6===========
# module: examples.interop
+ def test_http_0(server: Server, configuration: QuicConfiguration):
- def test_http_0(config, **kwargs):
+ if server.path is None:
- if config.path is None:
return
+ configuration.alpn_protocols = ["hq-22"]
+ async with connect(
+ server.host, server.port, configuration=configuration
+ ) as connection:
- kwargs["alpn_protocols"] = ["hq-22"]
- async with connect(config.host, config.port, **kwargs) as connection:
+ response = await http_request(connection, server.path)
- response = await http_request(connection, config.path)
if response:
+ server.result |= Result.D
- config.result |= Result.D
===========changed ref 7===========
# module: examples.interop
- @dataclass
- class Config:
- name: str
- host: str
- port: int = 4433
- retry_port: Optional[int] = 4434
- path: str = "/"
- result: Result = field(default_factory=lambda: Result(0))
-
|
aioquic.asyncio.protocol/QuicConnectionProtocol.__init__
|
Modified
|
aiortc~aioquic
|
ca1da35cc9a2a5906e16da0986014887523a6182
|
[asyncio] add QuicConnectionProtocol.transmit() to public API
|
<7>:<del> self._send_task: Optional[asyncio.Handle] = None
<11>:<add> self._transmit_task: Optional[asyncio.Handle] = 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> self._connection_terminated_handler: Callable[[], None] = lambda: None
<17> if stream_handler is not None:
<18> self._stream_handler = stream_handler
<19> else:
<20> self._stream_handler = lambda r, w: None
<21>
|
===========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._process_events
self._ping_waiter = None
at: aioquic.asyncio.protocol.QuicConnectionProtocol._transmit_soon
self._transmit_task = self._loop.call_soon(self.transmit)
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.asyncio.protocol.QuicConnectionProtocol.transmit
self._transmit_task = None
self._timer = self._loop.call_at(timer_at, self._handle_timer)
self._timer = None
self._timer_at = timer_at
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')
|
aioquic.asyncio.protocol/QuicConnectionProtocol.change_connection_id
|
Modified
|
aiortc~aioquic
|
ca1da35cc9a2a5906e16da0986014887523a6182
|
[asyncio] add QuicConnectionProtocol.transmit() to public API
|
<6>:<add> self.transmit()
<del> self._send_pending()
|
# 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._quic.change_connection_id()
<6> self._send_pending()
<7>
|
===========unchanged ref 0===========
at: aioquic.asyncio.protocol.QuicConnectionProtocol
transmit() -> 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, 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._transmit_task: Optional[asyncio.Handle] = 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
|
aioquic.asyncio.protocol/QuicConnectionProtocol.close
|
Modified
|
aiortc~aioquic
|
ca1da35cc9a2a5906e16da0986014887523a6182
|
[asyncio] add QuicConnectionProtocol.transmit() to public API
|
<4>:<add> self.transmit()
<del> self._send_pending()
|
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def close(self) -> None:
<0> """
<1> Close the connection.
<2> """
<3> self._quic.close()
<4> self._send_pending()
<5>
|
===========unchanged ref 0===========
at: aioquic.asyncio.protocol.QuicConnectionProtocol
transmit() -> None
at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__
self._quic = quic
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.transmit()
- self._send_pending()
===========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._transmit_task: Optional[asyncio.Handle] = 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
|
aioquic.asyncio.protocol/QuicConnectionProtocol.connect
|
Modified
|
aiortc~aioquic
|
ca1da35cc9a2a5906e16da0986014887523a6182
|
[asyncio] add QuicConnectionProtocol.transmit() to public API
|
<6>:<add> self.transmit()
<del> self._send_pending()
|
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def connect(self, addr: NetworkAddress) -> 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(addr, now=self._loop.time())
<6> self._send_pending()
<7>
|
===========unchanged ref 0===========
at: aioquic.asyncio.protocol.QuicConnectionProtocol
transmit() -> 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.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def close(self) -> None:
"""
Close the connection.
"""
self._quic.close()
+ self.transmit()
- 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.transmit()
- self._send_pending()
===========changed ref 2===========
# 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._transmit_task: Optional[asyncio.Handle] = 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
|
aioquic.asyncio.protocol/QuicConnectionProtocol.request_key_update
|
Modified
|
aiortc~aioquic
|
ca1da35cc9a2a5906e16da0986014887523a6182
|
[asyncio] add QuicConnectionProtocol.transmit() to public API
|
<4>:<add> self.transmit()
<del> self._send_pending()
|
# 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._quic.request_key_update()
<4> self._send_pending()
<5>
|
===========unchanged ref 0===========
at: aioquic.asyncio.protocol.QuicConnectionProtocol
transmit() -> 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.transmit()
- self._send_pending()
===========changed ref 1===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def connect(self, addr: NetworkAddress) -> 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())
+ self.transmit()
- 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.transmit()
- self._send_pending()
===========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._transmit_task: Optional[asyncio.Handle] = 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
|
aioquic.asyncio.protocol/QuicConnectionProtocol.ping
|
Modified
|
aiortc~aioquic
|
ca1da35cc9a2a5906e16da0986014887523a6182
|
[asyncio] add QuicConnectionProtocol.transmit() to public API
|
<1>:<add> Ping the peer and wait for the response.
<del> Pings the remote host and waits for the response.
<6>:<add> self.transmit()
<del> self._send_pending()
|
# 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._quic.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
transmit() -> 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._process_events
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.transmit()
- 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.transmit()
- self._send_pending()
===========changed ref 2===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def connect(self, addr: NetworkAddress) -> 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())
+ self.transmit()
- 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.transmit()
- self._send_pending()
===========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._transmit_task: Optional[asyncio.Handle] = 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
|
aioquic.asyncio.protocol/QuicConnectionProtocol.datagram_received
|
Modified
|
aiortc~aioquic
|
ca1da35cc9a2a5906e16da0986014887523a6182
|
[asyncio] add QuicConnectionProtocol.transmit() to public API
|
<1>:<add> self._process_events()
<add> self.transmit()
<del> self._send_pending()
|
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None:
<0> self._quic.receive_datagram(cast(bytes, data), addr, now=self._loop.time())
<1> self._send_pending()
<2>
|
===========unchanged ref 0===========
at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__
self._timer_at: Optional[float] = None
at: aioquic.asyncio.protocol.QuicConnectionProtocol._handle_timer
self._timer_at = None
at: aioquic.asyncio.protocol.QuicConnectionProtocol.transmit
timer_at = self._quic.get_timer()
===========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.transmit()
- 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.transmit()
- self._send_pending()
===========changed ref 2===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def connect(self, addr: NetworkAddress) -> 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())
+ self.transmit()
- 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.transmit()
- self._send_pending()
===========changed ref 4===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def ping(self) -> None:
"""
+ Ping the peer and wait for the response.
- 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.transmit()
- self._send_pending()
await asyncio.shield(self._ping_waiter)
===========changed ref 5===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
+ def transmit(self) -> None:
+ """
+ Send pending datagrams to the peer.
+ """
+ self._transmit_task = None
+
+ # 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 6===========
# 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._transmit_task: Optional[asyncio.Handle] = 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
|
aioquic.asyncio.protocol/QuicConnectionProtocol._handle_timer
|
Modified
|
aiortc~aioquic
|
ca1da35cc9a2a5906e16da0986014887523a6182
|
[asyncio] add QuicConnectionProtocol.transmit() to public API
|
<4>:<add> self._process_events()
<add> self.transmit()
<del> self._send_pending()
|
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def _handle_timer(self) -> None:
<0> now = max(self._timer_at, self._loop.time())
<1> self._timer = None
<2> self._timer_at = None
<3> self._quic.handle_timer(now=now)
<4> self._send_pending()
<5>
|
===========unchanged ref 0===========
at: aioquic.asyncio.protocol.QuicConnectionProtocol
_create_stream(stream_id: int) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]
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
StreamDataReceived(data: bytes, end_stream: bool, stream_id: int)
at: asyncio.streams.StreamReader
_source_traceback = None
feed_data(data: bytes) -> 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 datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None:
self._quic.receive_datagram(cast(bytes, data), addr, now=self._loop.time())
+ self._process_events()
+ self.transmit()
- 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.transmit()
- 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.transmit()
- self._send_pending()
===========changed ref 3===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def connect(self, addr: NetworkAddress) -> 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())
+ self.transmit()
- 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.transmit()
- self._send_pending()
===========changed ref 5===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def ping(self) -> None:
"""
+ Ping the peer and wait for the response.
- 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.transmit()
- self._send_pending()
await asyncio.shield(self._ping_waiter)
===========changed ref 6===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
+ def transmit(self) -> None:
+ """
+ Send pending datagrams to the peer.
+ """
+ self._transmit_task = None
+
+ # 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 7===========
# 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._transmit_task: Optional[asyncio.Handle] = 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
|
aioquic.asyncio.protocol/QuicStreamAdapter.write
|
Modified
|
aiortc~aioquic
|
ca1da35cc9a2a5906e16da0986014887523a6182
|
[asyncio] add QuicConnectionProtocol.transmit() to public API
|
<1>:<add> self.protocol._transmit_soon()
<del> self.protocol._send_soon()
|
# module: aioquic.asyncio.protocol
class QuicStreamAdapter(asyncio.Transport):
def write(self, data):
<0> self.protocol._quic.send_stream_data(self.stream_id, data)
<1> self.protocol._send_soon()
<2>
|
===========changed ref 0===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
+ def _transmit_soon(self) -> None:
+ if self._transmit_task is None:
+ self._transmit_task = self._loop.call_soon(self.transmit)
+
===========changed ref 1===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
- def _send_soon(self) -> None:
- if self._send_task is None:
- self._send_task = self._loop.call_soon(self._send_pending)
-
===========changed ref 2===========
# 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._process_events()
+ self.transmit()
- self._send_pending()
===========changed ref 3===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None:
self._quic.receive_datagram(cast(bytes, data), addr, now=self._loop.time())
+ self._process_events()
+ self.transmit()
- 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.transmit()
- self._send_pending()
===========changed ref 5===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def close(self) -> None:
"""
Close the connection.
"""
self._quic.close()
+ self.transmit()
- self._send_pending()
===========changed ref 6===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def connect(self, addr: NetworkAddress) -> 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())
+ self.transmit()
- self._send_pending()
===========changed ref 7===========
# 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.transmit()
- self._send_pending()
===========changed ref 8===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def ping(self) -> None:
"""
+ Ping the peer and wait for the response.
- 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.transmit()
- self._send_pending()
await asyncio.shield(self._ping_waiter)
===========changed ref 9===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
+ def _process_events(self) -> None:
+ 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()
+
===========changed ref 10===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
+ def transmit(self) -> None:
+ """
+ Send pending datagrams to the peer.
+ """
+ self._transmit_task = None
+
+ # 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 11===========
# 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._transmit_task: Optional[asyncio.Handle] = 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
|
aioquic.asyncio.protocol/QuicStreamAdapter.write_eof
|
Modified
|
aiortc~aioquic
|
ca1da35cc9a2a5906e16da0986014887523a6182
|
[asyncio] add QuicConnectionProtocol.transmit() to public API
|
<1>:<add> self.protocol._transmit_soon()
<del> self.protocol._send_soon()
|
# module: aioquic.asyncio.protocol
class QuicStreamAdapter(asyncio.Transport):
def write_eof(self):
<0> self.protocol._quic.send_stream_data(self.stream_id, b"", end_stream=True)
<1> self.protocol._send_soon()
<2>
|
===========unchanged ref 0===========
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
at: asyncio.transports.WriteTransport
__slots__ = ()
write(self, data: Any) -> None
===========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._transmit_soon()
- self.protocol._send_soon()
===========changed ref 1===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
+ def _transmit_soon(self) -> None:
+ if self._transmit_task is None:
+ self._transmit_task = self._loop.call_soon(self.transmit)
+
===========changed ref 2===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
- def _send_soon(self) -> None:
- if self._send_task is None:
- self._send_task = self._loop.call_soon(self._send_pending)
-
===========changed ref 3===========
# 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._process_events()
+ self.transmit()
- self._send_pending()
===========changed ref 4===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None:
self._quic.receive_datagram(cast(bytes, data), addr, now=self._loop.time())
+ self._process_events()
+ self.transmit()
- self._send_pending()
===========changed ref 5===========
# 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.transmit()
- self._send_pending()
===========changed ref 6===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def close(self) -> None:
"""
Close the connection.
"""
self._quic.close()
+ self.transmit()
- self._send_pending()
===========changed ref 7===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def connect(self, addr: NetworkAddress) -> 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())
+ self.transmit()
- self._send_pending()
===========changed ref 8===========
# 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.transmit()
- self._send_pending()
===========changed ref 9===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def ping(self) -> None:
"""
+ Ping the peer and wait for the response.
- 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.transmit()
- self._send_pending()
await asyncio.shield(self._ping_waiter)
===========changed ref 10===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
+ def _process_events(self) -> None:
+ 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()
+
===========changed ref 11===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
+ def transmit(self) -> None:
+ """
+ Send pending datagrams to the peer.
+ """
+ self._transmit_task = None
+
+ # 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
+
|
examples.http3-client/HttpClient.get
|
Modified
|
aiortc~aioquic
|
ca1da35cc9a2a5906e16da0986014887523a6182
|
[asyncio] add QuicConnectionProtocol.transmit() to public API
|
<18>:<add> self.transmit()
<del> self._send_pending()
|
# module: examples.http3-client
class HttpClient(QuicConnectionProtocol):
def get(self, authority: str, path: str) -> Deque[HttpEvent]:
<0> """
<1> Perform a GET request.
<2> """
<3> stream_id = self._quic.get_next_available_stream_id()
<4> self._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> self._http.send_data(stream_id=stream_id, data=b"", end_stream=True)
<14>
<15> waiter = self._loop.create_future()
<16> self._request_events[stream_id] = deque()
<17> self._request_waiter[stream_id] = waiter
<18> self._send_pending()
<19>
<20> return await asyncio.shield(waiter)
<21>
|
===========unchanged ref 0===========
at: aioquic.asyncio.protocol.QuicConnectionProtocol
transmit() -> 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
HttpEvent()
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: 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: typing
Deque = _alias(collections.deque, 1, name='Deque')
===========changed ref 0===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
+ def transmit(self) -> None:
+ """
+ Send pending datagrams to the peer.
+ """
+ self._transmit_task = None
+
+ # 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 1===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
+ def _transmit_soon(self) -> None:
+ if self._transmit_task is None:
+ self._transmit_task = self._loop.call_soon(self.transmit)
+
===========changed ref 2===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
- def _send_soon(self) -> None:
- if self._send_task is None:
- self._send_task = self._loop.call_soon(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.transmit()
- 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.transmit()
- 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._transmit_soon()
- self.protocol._send_soon()
===========changed ref 6===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None:
self._quic.receive_datagram(cast(bytes, data), addr, now=self._loop.time())
+ self._process_events()
+ self.transmit()
- 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._transmit_soon()
- self.protocol._send_soon()
===========changed ref 8===========
# 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.transmit()
- self._send_pending()
===========changed ref 9===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def connect(self, addr: NetworkAddress) -> 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())
+ self.transmit()
- 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._process_events()
+ self.transmit()
- self._send_pending()
===========changed ref 11===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def ping(self) -> None:
"""
+ Ping the peer and wait for the response.
- 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.transmit()
- self._send_pending()
await asyncio.shield(self._ping_waiter)
|
examples.http3-server/HttpRequestHandler.__init__
|
Modified
|
aiortc~aioquic
|
ca1da35cc9a2a5906e16da0986014887523a6182
|
[asyncio] add QuicConnectionProtocol.transmit() to public API
|
<3>:<del> self.send_pending = send_pending
<5>:<add> self.transmit = transmit
|
# module: examples.http3-server
class HttpRequestHandler:
def __init__(
self,
*,
connection: HttpConnection,
scope: Dict,
- send_pending: Callable[[], None],
stream_id: int,
+ transmit: Callable[[], None],
):
<0> self.connection = connection
<1> self.queue: asyncio.Queue[Dict] = asyncio.Queue()
<2> self.scope = scope
<3> self.send_pending = send_pending
<4> self.stream_id = stream_id
<5>
|
===========unchanged ref 0===========
at: asyncio.queues
Queue(maxsize: int=..., *, loop: Optional[AbstractEventLoop]=...)
at: examples.http3-server
HttpConnection = Union[H0Connection, H3Connection]
at: typing
Callable = _CallableType(collections.abc.Callable, 2)
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
+ def _transmit_soon(self) -> None:
+ if self._transmit_task is None:
+ self._transmit_task = self._loop.call_soon(self.transmit)
+
===========changed ref 1===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
- def _send_soon(self) -> None:
- if self._send_task is None:
- self._send_task = self._loop.call_soon(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.transmit()
- 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.transmit()
- 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._transmit_soon()
- self.protocol._send_soon()
===========changed ref 5===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None:
self._quic.receive_datagram(cast(bytes, data), addr, now=self._loop.time())
+ self._process_events()
+ self.transmit()
- 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._transmit_soon()
- self.protocol._send_soon()
===========changed ref 7===========
# 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.transmit()
- self._send_pending()
===========changed ref 8===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def connect(self, addr: NetworkAddress) -> 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())
+ self.transmit()
- 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._process_events()
+ self.transmit()
- self._send_pending()
===========changed ref 10===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def ping(self) -> None:
"""
+ Ping the peer and wait for the response.
- 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.transmit()
- self._send_pending()
await asyncio.shield(self._ping_waiter)
===========changed ref 11===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
+ def transmit(self) -> None:
+ """
+ Send pending datagrams to the peer.
+ """
+ self._transmit_task = None
+
+ # 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 12===========
# module: examples.http3-client
class HttpClient(QuicConnectionProtocol):
def get(self, authority: str, path: str) -> Deque[HttpEvent]:
"""
Perform a GET request.
"""
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":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.transmit()
- self._send_pending()
return await asyncio.shield(waiter)
===========changed ref 13===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
+ def _process_events(self) -> None:
+ 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()
+
|
examples.http3-server/HttpRequestHandler.run_asgi
|
Modified
|
aiortc~aioquic
|
ca1da35cc9a2a5906e16da0986014887523a6182
|
[asyncio] add QuicConnectionProtocol.transmit() to public API
|
<3>:<add> self.transmit()
<del> self.send_pending()
|
# module: examples.http3-server
class HttpRequestHandler:
def run_asgi(self, app: AsgiApplication) -> None:
<0> await application(self.scope, self.receive, self.send)
<1>
<2> self.connection.send_data(stream_id=self.stream_id, data=b"", end_stream=True)
<3> self.send_pending()
<4>
|
===========unchanged ref 0===========
at: aioquic.h0.connection.H0Connection
send_data(stream_id: int, data: bytes, end_stream: bool) -> None
at: aioquic.h3.connection.H3Connection
send_data(stream_id: int, data: bytes, end_stream: bool) -> None
at: examples.http3-server
AsgiApplication = Callable
application = getattr(module, attr_str)
at: examples.http3-server.HttpRequestHandler
receive() -> Dict
send(message: Dict)
send(self, message: Dict)
at: examples.http3-server.HttpRequestHandler.__init__
self.connection = connection
self.scope = scope
self.stream_id = stream_id
self.transmit = transmit
===========changed ref 0===========
# module: examples.http3-server
class HttpRequestHandler:
def __init__(
self,
*,
connection: HttpConnection,
scope: Dict,
- send_pending: Callable[[], None],
stream_id: int,
+ transmit: Callable[[], None],
):
self.connection = connection
self.queue: asyncio.Queue[Dict] = asyncio.Queue()
self.scope = scope
- self.send_pending = send_pending
self.stream_id = stream_id
+ self.transmit = transmit
===========changed ref 1===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
+ def _transmit_soon(self) -> None:
+ if self._transmit_task is None:
+ self._transmit_task = self._loop.call_soon(self.transmit)
+
===========changed ref 2===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
- def _send_soon(self) -> None:
- if self._send_task is None:
- self._send_task = self._loop.call_soon(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.transmit()
- 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.transmit()
- 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._transmit_soon()
- self.protocol._send_soon()
===========changed ref 6===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None:
self._quic.receive_datagram(cast(bytes, data), addr, now=self._loop.time())
+ self._process_events()
+ self.transmit()
- 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._transmit_soon()
- self.protocol._send_soon()
===========changed ref 8===========
# 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.transmit()
- self._send_pending()
===========changed ref 9===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def connect(self, addr: NetworkAddress) -> 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())
+ self.transmit()
- 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._process_events()
+ self.transmit()
- self._send_pending()
===========changed ref 11===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def ping(self) -> None:
"""
+ Ping the peer and wait for the response.
- 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.transmit()
- self._send_pending()
await asyncio.shield(self._ping_waiter)
===========changed ref 12===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
+ def transmit(self) -> None:
+ """
+ Send pending datagrams to the peer.
+ """
+ self._transmit_task = None
+
+ # 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 13===========
# module: examples.http3-client
class HttpClient(QuicConnectionProtocol):
def get(self, authority: str, path: str) -> Deque[HttpEvent]:
"""
Perform a GET request.
"""
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":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.transmit()
- self._send_pending()
return await asyncio.shield(waiter)
|
examples.http3-server/HttpRequestHandler.send
|
Modified
|
aiortc~aioquic
|
ca1da35cc9a2a5906e16da0986014887523a6182
|
[asyncio] add QuicConnectionProtocol.transmit() to public API
|
<14>:<add> self.transmit()
<del> self.send_pending()
|
# module: examples.http3-server
class HttpRequestHandler:
def send(self, message: Dict):
<0> if message["type"] == "http.response.start":
<1> self.connection.send_headers(
<2> stream_id=self.stream_id,
<3> headers=[
<4> (b":status", str(message["status"]).encode("ascii")),
<5> (b"server", b"aioquic"),
<6> (b"date", formatdate(time.time(), usegmt=True).encode()),
<7> ]
<8> + [(k, v) for k, v in message["headers"]],
<9> )
<10> elif message["type"] == "http.response.body":
<11> self.connection.send_data(
<12> stream_id=self.stream_id, data=message["body"], end_stream=False
<13> )
<14> self.send_pending()
<15>
|
===========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: email.utils
formatdate(timeval: Optional[float]=..., localtime: bool=..., usegmt: bool=...) -> str
at: examples.http3-server.HttpRequestHandler.__init__
self.connection = connection
self.stream_id = stream_id
self.transmit = transmit
at: time
time() -> float
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# 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.transmit()
- self.send_pending()
===========changed ref 1===========
# module: examples.http3-server
class HttpRequestHandler:
def __init__(
self,
*,
connection: HttpConnection,
scope: Dict,
- send_pending: Callable[[], None],
stream_id: int,
+ transmit: Callable[[], None],
):
self.connection = connection
self.queue: asyncio.Queue[Dict] = asyncio.Queue()
self.scope = scope
- self.send_pending = send_pending
self.stream_id = stream_id
+ self.transmit = transmit
===========changed ref 2===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
+ def _transmit_soon(self) -> None:
+ if self._transmit_task is None:
+ self._transmit_task = self._loop.call_soon(self.transmit)
+
===========changed ref 3===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
- def _send_soon(self) -> None:
- if self._send_task is None:
- self._send_task = self._loop.call_soon(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.transmit()
- self._send_pending()
===========changed ref 5===========
# 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.transmit()
- self._send_pending()
===========changed ref 6===========
# module: aioquic.asyncio.protocol
class QuicStreamAdapter(asyncio.Transport):
def write(self, data):
self.protocol._quic.send_stream_data(self.stream_id, data)
+ self.protocol._transmit_soon()
- 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._quic.receive_datagram(cast(bytes, data), addr, now=self._loop.time())
+ self._process_events()
+ self.transmit()
- self._send_pending()
===========changed ref 8===========
# 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._transmit_soon()
- self.protocol._send_soon()
===========changed ref 9===========
# 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.transmit()
- self._send_pending()
===========changed ref 10===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def connect(self, addr: NetworkAddress) -> 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())
+ self.transmit()
- self._send_pending()
===========changed ref 11===========
# 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._process_events()
+ self.transmit()
- self._send_pending()
===========changed ref 12===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def ping(self) -> None:
"""
+ Ping the peer and wait for the response.
- 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.transmit()
- self._send_pending()
await asyncio.shield(self._ping_waiter)
===========changed ref 13===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
+ def transmit(self) -> None:
+ """
+ Send pending datagrams to the peer.
+ """
+ self._transmit_task = None
+
+ # 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
+
|
examples.http3-server/HttpServerProtocol.http_event_received
|
Modified
|
aiortc~aioquic
|
ca1da35cc9a2a5906e16da0986014887523a6182
|
[asyncio] add QuicConnectionProtocol.transmit() to public API
|
<34>:<del> send_pending=self._send_pending,
<36>:<add> transmit=self.transmit,
|
# 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(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,
<45> </s>
|
===========below chunk 0===========
# module: examples.http3-server
class HttpServerProtocol(QuicConnectionProtocol):
def http_event_received(self, event: HttpEvent) -> None:
# offset: 1
}
)
===========unchanged ref 0===========
at: aioquic.h0.connection
H0Connection(quic: QuicConnection)
at: aioquic.h3.events
HttpEvent()
DataReceived(data: bytes, stream_id: int, stream_ended: bool)
RequestReceived(headers: Headers, stream_id: int, stream_ended: bool)
at: asyncio.queues.Queue
__class_getitem__ = classmethod(GenericAlias)
put_nowait(item: _T) -> None
at: asyncio.tasks
ensure_future(coro_or_future: _FutureT[_T], *, loop: Optional[AbstractEventLoop]=...) -> Future[_T]
at: examples.http3-server
HttpRequestHandler(*, connection: HttpConnection, scope: Dict, stream_id: int, transmit: Callable[[], None])
application = getattr(module, attr_str)
at: examples.http3-server.HttpRequestHandler
run_asgi(self, app: AsgiApplication) -> None
run_asgi(app: AsgiApplication) -> None
at: examples.http3-server.HttpRequestHandler.__init__
self.queue: asyncio.Queue[Dict] = asyncio.Queue()
at: examples.http3-server.HttpServerProtocol.__init__
self._handlers: Dict[int, HttpRequestHandler] = {}
self._http: Optional[HttpConnection] = None
at: examples.http3-server.HttpServerProtocol.quic_event_received
self._http = H3Connection(self._quic)
self._http = H0Connection(self._quic)
===========changed ref 0===========
# 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.transmit()
- self.send_pending()
===========changed ref 1===========
# module: examples.http3-server
class HttpRequestHandler:
def __init__(
self,
*,
connection: HttpConnection,
scope: Dict,
- send_pending: Callable[[], None],
stream_id: int,
+ transmit: Callable[[], None],
):
self.connection = connection
self.queue: asyncio.Queue[Dict] = asyncio.Queue()
self.scope = scope
- self.send_pending = send_pending
self.stream_id = stream_id
+ self.transmit = transmit
===========changed ref 2===========
# 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.transmit()
- self.send_pending()
===========changed ref 3===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
+ def _transmit_soon(self) -> None:
+ if self._transmit_task is None:
+ self._transmit_task = self._loop.call_soon(self.transmit)
+
===========changed ref 4===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
- def _send_soon(self) -> None:
- if self._send_task is None:
- self._send_task = self._loop.call_soon(self._send_pending)
-
===========changed ref 5===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def close(self) -> None:
"""
Close the connection.
"""
self._quic.close()
+ self.transmit()
- self._send_pending()
===========changed ref 6===========
# 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.transmit()
- self._send_pending()
===========changed ref 7===========
# module: aioquic.asyncio.protocol
class QuicStreamAdapter(asyncio.Transport):
def write(self, data):
self.protocol._quic.send_stream_data(self.stream_id, data)
+ self.protocol._transmit_soon()
- 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._quic.receive_datagram(cast(bytes, data), addr, now=self._loop.time())
+ self._process_events()
+ self.transmit()
- self._send_pending()
===========changed ref 9===========
# 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._transmit_soon()
- self.protocol._send_soon()
===========changed ref 10===========
# 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.transmit()
- self._send_pending()
===========changed ref 11===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def connect(self, addr: NetworkAddress) -> 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())
+ self.transmit()
- self._send_pending()
===========changed ref 12===========
# 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._process_events()
+ self.transmit()
- self._send_pending()
===========changed ref 13===========
# module: aioquic.asyncio.protocol
class QuicConnectionProtocol(asyncio.DatagramProtocol):
def ping(self) -> None:
"""
+ Ping the peer and wait for the response.
- 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.transmit()
- self._send_pending()
await asyncio.shield(self._ping_waiter)
|
examples.interop/test_version_negotiation
|
Modified
|
aiortc~aioquic
|
d4d5508146da453a8e8e0c2b5b7592652efc9401
|
[examples] use http3 client code for interop testing
|
<4>:<add> ) as protocol:
<del> ) as connection:
<5>:<add> await protocol.ping()
<del> await connection.ping()
|
# module: examples.interop
def test_version_negotiation(server: Server, configuration: QuicConfiguration):
<0> configuration.supported_versions = [0x1A2A3A4A, QuicProtocolVersion.DRAFT_22]
<1>
<2> async with connect(
<3> server.host, server.port, configuration=configuration
<4> ) as connection:
<5> await connection.ping()
<6>
<7> # check log
<8> for stamp, category, event, data in configuration.quic_logger.to_dict()[
<9> "traces"
<10> ][0]["events"]:
<11> if (
<12> category == "TRANSPORT"
<13> and event == "PACKET_RECEIVED"
<14> and data["type"] == "VERSION_NEGOTIATION"
<15> ):
<16> server.result |= Result.V
<17>
|
===========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
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[int]=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[int] = field(
default_factory=lambda: [QuicProtocolVersion.DRAFT_22]
)
at: aioquic.quic.logger.QuicLogger
to_dict() -> Dict[str, Any]
at: examples.interop
Result()
===========unchanged ref 1===========
Server(name: str, host: str, port: int=4433, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)))
at: examples.interop.Server
name: str
host: str
port: int = 4433
retry_port: Optional[int] = 4434
path: str = "/"
result: Result = field(default_factory=lambda: Result(0))
===========changed ref 0===========
# module: examples.interop
- def http_request(connection: QuicConnectionProtocol, path: str):
- # perform HTTP/0.9 request
- reader, writer = await connection.create_stream()
- writer.write(("GET %s\r\n" % path).encode("utf8"))
- writer.write_eof()
-
- return await reader.read()
-
===========changed ref 1===========
# module: examples.interop
- def http3_request(connection: QuicConnectionProtocol, authority: str, path: str):
- reader, writer = await connection.create_stream()
- stream_id = writer.get_extra_info("stream_id")
-
- http = H3Connection(connection._quic)
- 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()
-
|
examples.interop/test_handshake_and_close
|
Modified
|
aiortc~aioquic
|
d4d5508146da453a8e8e0c2b5b7592652efc9401
|
[examples] use http3 client code for interop testing
|
<2>:<add> ) as protocol:
<del> ) as connection:
<3>:<add> await protocol.ping()
<del> await connection.ping()
|
# module: examples.interop
def test_handshake_and_close(server: Server, configuration: QuicConfiguration):
<0> async with connect(
<1> server.host, server.port, configuration=configuration
<2> ) as connection:
<3> await connection.ping()
<4> server.result |= Result.H
<5> server.result |= Result.C
<6>
|
===========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.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[int]=field(
default_factory=lambda: [QuicProtocolVersion.DRAFT_22]
))
at: aioquic.quic.configuration.QuicConfiguration
alpn_protocols: Optional[List[str]] = None
at: examples.interop
Server(name: str, host: str, port: int=4433, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)))
at: examples.interop.Server
host: str
path: str = "/"
===========changed ref 0===========
# module: examples.interop
- def http_request(connection: QuicConnectionProtocol, path: str):
- # perform HTTP/0.9 request
- reader, writer = await connection.create_stream()
- writer.write(("GET %s\r\n" % path).encode("utf8"))
- writer.write_eof()
-
- return await reader.read()
-
===========changed ref 1===========
# module: examples.interop
def test_version_negotiation(server: Server, configuration: QuicConfiguration):
configuration.supported_versions = [0x1A2A3A4A, QuicProtocolVersion.DRAFT_22]
async with connect(
server.host, server.port, configuration=configuration
+ ) as protocol:
- ) as connection:
+ await protocol.ping()
- await connection.ping()
# check log
for stamp, category, event, data in configuration.quic_logger.to_dict()[
"traces"
][0]["events"]:
if (
category == "TRANSPORT"
and event == "PACKET_RECEIVED"
and data["type"] == "VERSION_NEGOTIATION"
):
server.result |= Result.V
===========changed ref 2===========
# module: examples.interop
- def http3_request(connection: QuicConnectionProtocol, authority: str, path: str):
- reader, writer = await connection.create_stream()
- stream_id = writer.get_extra_info("stream_id")
-
- http = H3Connection(connection._quic)
- 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()
-
|
examples.interop/test_stateless_retry
|
Modified
|
aiortc~aioquic
|
d4d5508146da453a8e8e0c2b5b7592652efc9401
|
[examples] use http3 client code for interop testing
|
<2>:<add> ) as protocol:
<del> ) as connection:
<3>:<add> await protocol.ping()
<del> await connection.ping()
|
# module: examples.interop
def test_stateless_retry(server: Server, configuration: QuicConfiguration):
<0> async with connect(
<1> server.host, server.retry_port, configuration=configuration
<2> ) as connection:
<3> await connection.ping()
<4>
<5> # check log
<6> for stamp, category, event, data in configuration.quic_logger.to_dict()[
<7> "traces"
<8> ][0]["events"]:
<9> if (
<10> category == "TRANSPORT"
<11> and event == "PACKET_RECEIVED"
<12> and data["type"] == "RETRY"
<13> ):
<14> server.result |= Result.S
<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.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[int]=field(
default_factory=lambda: [QuicProtocolVersion.DRAFT_22]
))
at: aioquic.quic.configuration.QuicConfiguration
alpn_protocols: Optional[List[str]] = None
at: examples.interop
Result()
Server(name: str, host: str, port: int=4433, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)))
at: examples.interop.Server
host: str
path: str = "/"
result: Result = field(default_factory=lambda: Result(0))
at: http3_client
HttpClient(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None, /, *, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None)
at: http3_client.HttpClient
get(authority: str, path: str) -> Deque[HttpEvent]
===========unchanged ref 1===========
at: typing
cast(typ: Type[_T], val: Any) -> _T
cast(typ: str, val: Any) -> Any
cast(typ: object, val: Any) -> Any
===========changed ref 0===========
# module: examples.interop
def test_handshake_and_close(server: Server, configuration: QuicConfiguration):
async with connect(
server.host, server.port, configuration=configuration
+ ) as protocol:
- ) as connection:
+ await protocol.ping()
- await connection.ping()
server.result |= Result.H
server.result |= Result.C
===========changed ref 1===========
# module: examples.interop
- def http_request(connection: QuicConnectionProtocol, path: str):
- # perform HTTP/0.9 request
- reader, writer = await connection.create_stream()
- writer.write(("GET %s\r\n" % path).encode("utf8"))
- writer.write_eof()
-
- return await reader.read()
-
===========changed ref 2===========
# module: examples.interop
def test_version_negotiation(server: Server, configuration: QuicConfiguration):
configuration.supported_versions = [0x1A2A3A4A, QuicProtocolVersion.DRAFT_22]
async with connect(
server.host, server.port, configuration=configuration
+ ) as protocol:
- ) as connection:
+ await protocol.ping()
- await connection.ping()
# check log
for stamp, category, event, data in configuration.quic_logger.to_dict()[
"traces"
][0]["events"]:
if (
category == "TRANSPORT"
and event == "PACKET_RECEIVED"
and data["type"] == "VERSION_NEGOTIATION"
):
server.result |= Result.V
===========changed ref 3===========
# module: examples.interop
- def http3_request(connection: QuicConnectionProtocol, authority: str, path: str):
- reader, writer = await connection.create_stream()
- stream_id = writer.get_extra_info("stream_id")
-
- http = H3Connection(connection._quic)
- 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()
-
|
examples.interop/test_http_0
|
Modified
|
aiortc~aioquic
|
d4d5508146da453a8e8e0c2b5b7592652efc9401
|
[examples] use http3 client code for interop testing
|
<5>:<add> server.host,
<add> server.port,
<add> configuration=configuration,
<add> create_protocol=HttpClient,
<add> ) as protocol:
<add> protocol = cast(HttpClient, protocol)
<add>
<add> # perform HTTP request
<add> events = await protocol.get(server.host, server.path)
<add> if events and isinstance(events[0], ResponseReceived):
<del> server.host, server.port, configuration=configuration
<6>:<del> ) as connection:
<7>:<del> response = await http_request(connection, server.path)
<8>:<del> if response:
|
# module: examples.interop
def test_http_0(server: Server, configuration: QuicConfiguration):
<0> if server.path is None:
<1> return
<2>
<3> configuration.alpn_protocols = ["hq-22"]
<4> async with connect(
<5> server.host, server.port, configuration=configuration
<6> ) as connection:
<7> response = await http_request(connection, server.path)
<8> if response:
<9> server.result |= Result.D
<10>
|
===========unchanged ref 0===========
at: aioquic.h3.events
ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)
at: examples.interop
Result()
at: examples.interop.Server
host: str
path: str = "/"
result: Result = field(default_factory=lambda: Result(0))
at: http3_client
HttpClient(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None, /, *, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None)
at: http3_client.HttpClient
get(authority: str, path: str) -> Deque[HttpEvent]
at: typing
cast(typ: Type[_T], val: Any) -> _T
cast(typ: str, val: Any) -> Any
cast(typ: object, val: Any) -> Any
===========changed ref 0===========
# module: examples.interop
def test_handshake_and_close(server: Server, configuration: QuicConfiguration):
async with connect(
server.host, server.port, configuration=configuration
+ ) as protocol:
- ) as connection:
+ await protocol.ping()
- await connection.ping()
server.result |= Result.H
server.result |= Result.C
===========changed ref 1===========
# module: examples.interop
- def http_request(connection: QuicConnectionProtocol, path: str):
- # perform HTTP/0.9 request
- reader, writer = await connection.create_stream()
- writer.write(("GET %s\r\n" % path).encode("utf8"))
- writer.write_eof()
-
- return await reader.read()
-
===========changed ref 2===========
# module: examples.interop
def test_stateless_retry(server: Server, configuration: QuicConfiguration):
async with connect(
server.host, server.retry_port, configuration=configuration
+ ) as protocol:
- ) as connection:
+ await protocol.ping()
- await connection.ping()
# check log
for stamp, category, event, data in configuration.quic_logger.to_dict()[
"traces"
][0]["events"]:
if (
category == "TRANSPORT"
and event == "PACKET_RECEIVED"
and data["type"] == "RETRY"
):
server.result |= Result.S
===========changed ref 3===========
# module: examples.interop
def test_version_negotiation(server: Server, configuration: QuicConfiguration):
configuration.supported_versions = [0x1A2A3A4A, QuicProtocolVersion.DRAFT_22]
async with connect(
server.host, server.port, configuration=configuration
+ ) as protocol:
- ) as connection:
+ await protocol.ping()
- await connection.ping()
# check log
for stamp, category, event, data in configuration.quic_logger.to_dict()[
"traces"
][0]["events"]:
if (
category == "TRANSPORT"
and event == "PACKET_RECEIVED"
and data["type"] == "VERSION_NEGOTIATION"
):
server.result |= Result.V
===========changed ref 4===========
# module: examples.interop
- def http3_request(connection: QuicConnectionProtocol, authority: str, path: str):
- reader, writer = await connection.create_stream()
- stream_id = writer.get_extra_info("stream_id")
-
- http = H3Connection(connection._quic)
- 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()
-
|
examples.interop/test_http_3
|
Modified
|
aiortc~aioquic
|
d4d5508146da453a8e8e0c2b5b7592652efc9401
|
[examples] use http3 client code for interop testing
|
<5>:<add> server.host,
<add> server.port,
<add> configuration=configuration,
<add> create_protocol=HttpClient,
<add> ) as protocol:
<add> protocol = cast(HttpClient, protocol)
<add>
<add> # perform HTTP request
<add> events = await protocol.get(server.host, server.path)
<add> if events and isinstance(events[0], ResponseReceived):
<del> server.host, server.port, configuration=configuration
<6>:<del> ) as connection:
<7>:<del> response = await http3_request(connection, server.host, server.path)
<8>:<del> if response:
|
# module: examples.interop
def test_http_3(server: Server, configuration: QuicConfiguration):
<0> if server.path is None:
<1> return
<2>
<3> configuration.alpn_protocols = ["h3-22"]
<4> async with connect(
<5> server.host, server.port, configuration=configuration
<6> ) as connection:
<7> response = await http3_request(connection, server.host, server.path)
<8> if response:
<9> server.result |= Result.D
<10> server.result |= Result.three
<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: examples.interop.Server
host: str
port: int = 4433
===========changed ref 0===========
# module: examples.interop
def test_handshake_and_close(server: Server, configuration: QuicConfiguration):
async with connect(
server.host, server.port, configuration=configuration
+ ) as protocol:
- ) as connection:
+ await protocol.ping()
- await connection.ping()
server.result |= Result.H
server.result |= Result.C
===========changed ref 1===========
# module: examples.interop
- def http_request(connection: QuicConnectionProtocol, path: str):
- # perform HTTP/0.9 request
- reader, writer = await connection.create_stream()
- writer.write(("GET %s\r\n" % path).encode("utf8"))
- writer.write_eof()
-
- return await reader.read()
-
===========changed ref 2===========
# module: examples.interop
def test_stateless_retry(server: Server, configuration: QuicConfiguration):
async with connect(
server.host, server.retry_port, configuration=configuration
+ ) as protocol:
- ) as connection:
+ await protocol.ping()
- await connection.ping()
# check log
for stamp, category, event, data in configuration.quic_logger.to_dict()[
"traces"
][0]["events"]:
if (
category == "TRANSPORT"
and event == "PACKET_RECEIVED"
and data["type"] == "RETRY"
):
server.result |= Result.S
===========changed ref 3===========
# module: examples.interop
def test_http_0(server: Server, configuration: QuicConfiguration):
if server.path is None:
return
configuration.alpn_protocols = ["hq-22"]
async with connect(
+ server.host,
+ server.port,
+ configuration=configuration,
+ create_protocol=HttpClient,
+ ) as protocol:
+ protocol = cast(HttpClient, protocol)
+
+ # perform HTTP request
+ events = await protocol.get(server.host, server.path)
+ if events and isinstance(events[0], ResponseReceived):
- server.host, server.port, configuration=configuration
- ) as connection:
- response = await http_request(connection, server.path)
- if response:
server.result |= Result.D
===========changed ref 4===========
# module: examples.interop
def test_version_negotiation(server: Server, configuration: QuicConfiguration):
configuration.supported_versions = [0x1A2A3A4A, QuicProtocolVersion.DRAFT_22]
async with connect(
server.host, server.port, configuration=configuration
+ ) as protocol:
- ) as connection:
+ await protocol.ping()
- await connection.ping()
# check log
for stamp, category, event, data in configuration.quic_logger.to_dict()[
"traces"
][0]["events"]:
if (
category == "TRANSPORT"
and event == "PACKET_RECEIVED"
and data["type"] == "VERSION_NEGOTIATION"
):
server.result |= Result.V
===========changed ref 5===========
# module: examples.interop
- def http3_request(connection: QuicConnectionProtocol, authority: str, path: str):
- reader, writer = await connection.create_stream()
- stream_id = writer.get_extra_info("stream_id")
-
- http = H3Connection(connection._quic)
- 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()
-
|
examples.interop/test_session_resumption
|
Modified
|
aiortc~aioquic
|
d4d5508146da453a8e8e0c2b5b7592652efc9401
|
[examples] use http3 client code for interop testing
|
<12>:<add> ) as protocol:
<del> ) as connection:
<13>:<add> await protocol.ping()
<del> await connection.ping()
<20>:<add> ) as protocol:
<del> ) as connection:
<21>:<add> await protocol.ping()
<del> await connection.ping()
<24>:<add> if protocol._quic.tls.session_resumed:
<del> if connection._quic.tls.session_resumed:
<28>:<add> if protocol._quic.tls.early_data_accepted:
<del> if connection._quic.tls.early_data_accepted:
|
# module: examples.interop
def test_session_resumption(server: Server, configuration: QuicConfiguration):
<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> server.host,
<9> server.port,
<10> configuration=configuration,
<11> session_ticket_handler=session_ticket_handler,
<12> ) as connection:
<13> await connection.ping()
<14>
<15> # connect a second time, with the ticket
<16> if saved_ticket is not None:
<17> configuration.session_ticket = saved_ticket
<18> async with connect(
<19> server.host, server.port, configuration=configuration
<20> ) as connection:
<21> await connection.ping()
<22>
<23> # check session was resumed
<24> if connection._quic.tls.session_resumed:
<25> server.result |= Result.R
<26>
<27> # check early data was accepted
<28> if connection._quic.tls.early_data_accepted:
<29> server.result |= Result.Z
<30>
|
===========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
request_key_update() -> None
ping() -> None
at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__
self._quic = quic
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[int]=field(
default_factory=lambda: [QuicProtocolVersion.DRAFT_22]
))
at: aioquic.quic.configuration.QuicConfiguration
session_ticket: Optional[SessionTicket] = None
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()
===========unchanged ref 1===========
Server(name: str, host: str, port: int=4433, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)))
at: examples.interop.Server
host: str
port: int = 4433
result: Result = field(default_factory=lambda: Result(0))
at: examples.interop.test_session_resumption
saved_ticket = None
===========changed ref 0===========
# module: examples.interop
def test_handshake_and_close(server: Server, configuration: QuicConfiguration):
async with connect(
server.host, server.port, configuration=configuration
+ ) as protocol:
- ) as connection:
+ await protocol.ping()
- await connection.ping()
server.result |= Result.H
server.result |= Result.C
===========changed ref 1===========
# module: examples.interop
- def http_request(connection: QuicConnectionProtocol, path: str):
- # perform HTTP/0.9 request
- reader, writer = await connection.create_stream()
- writer.write(("GET %s\r\n" % path).encode("utf8"))
- writer.write_eof()
-
- return await reader.read()
-
===========changed ref 2===========
# module: examples.interop
def test_stateless_retry(server: Server, configuration: QuicConfiguration):
async with connect(
server.host, server.retry_port, configuration=configuration
+ ) as protocol:
- ) as connection:
+ await protocol.ping()
- await connection.ping()
# check log
for stamp, category, event, data in configuration.quic_logger.to_dict()[
"traces"
][0]["events"]:
if (
category == "TRANSPORT"
and event == "PACKET_RECEIVED"
and data["type"] == "RETRY"
):
server.result |= Result.S
===========changed ref 3===========
# module: examples.interop
def test_http_0(server: Server, configuration: QuicConfiguration):
if server.path is None:
return
configuration.alpn_protocols = ["hq-22"]
async with connect(
+ server.host,
+ server.port,
+ configuration=configuration,
+ create_protocol=HttpClient,
+ ) as protocol:
+ protocol = cast(HttpClient, protocol)
+
+ # perform HTTP request
+ events = await protocol.get(server.host, server.path)
+ if events and isinstance(events[0], ResponseReceived):
- server.host, server.port, configuration=configuration
- ) as connection:
- response = await http_request(connection, server.path)
- if response:
server.result |= Result.D
===========changed ref 4===========
# module: examples.interop
def test_http_3(server: Server, configuration: QuicConfiguration):
if server.path is None:
return
configuration.alpn_protocols = ["h3-22"]
async with connect(
+ server.host,
+ server.port,
+ configuration=configuration,
+ create_protocol=HttpClient,
+ ) as protocol:
+ protocol = cast(HttpClient, protocol)
+
+ # perform HTTP request
+ events = await protocol.get(server.host, server.path)
+ if events and isinstance(events[0], ResponseReceived):
- server.host, server.port, configuration=configuration
- ) as connection:
- response = await http3_request(connection, server.host, server.path)
- if response:
server.result |= Result.D
server.result |= Result.three
===========changed ref 5===========
# module: examples.interop
def test_version_negotiation(server: Server, configuration: QuicConfiguration):
configuration.supported_versions = [0x1A2A3A4A, QuicProtocolVersion.DRAFT_22]
async with connect(
server.host, server.port, configuration=configuration
+ ) as protocol:
- ) as connection:
+ await protocol.ping()
- await connection.ping()
# check log
for stamp, category, event, data in configuration.quic_logger.to_dict()[
"traces"
][0]["events"]:
if (
category == "TRANSPORT"
and event == "PACKET_RECEIVED"
and data["type"] == "VERSION_NEGOTIATION"
):
server.result |= Result.V
===========changed ref 6===========
# module: examples.interop
- def http3_request(connection: QuicConnectionProtocol, authority: str, path: str):
- reader, writer = await connection.create_stream()
- stream_id = writer.get_extra_info("stream_id")
-
- http = H3Connection(connection._quic)
- 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()
-
|
examples.interop/test_key_update
|
Modified
|
aiortc~aioquic
|
d4d5508146da453a8e8e0c2b5b7592652efc9401
|
[examples] use http3 client code for interop testing
|
<2>:<add> ) as protocol:
<del> ) as connection:
<4>:<add> await protocol.ping()
<del> await connection.ping()
<7>:<add> protocol.request_key_update()
<del> connection.request_key_update()
<10>:<add> await protocol.ping()
<del> await connection.ping()
|
# module: examples.interop
def test_key_update(server: Server, configuration: QuicConfiguration):
<0> async with connect(
<1> server.host, server.port, configuration=configuration
<2> ) as connection:
<3> # cause some traffic
<4> await connection.ping()
<5>
<6> # request key update
<7> connection.request_key_update()
<8>
<9> # cause more traffic
<10> await connection.ping()
<11>
<12> server.result |= Result.U
<13>
|
===========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
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[int]=field(
default_factory=lambda: [QuicProtocolVersion.DRAFT_22]
))
at: aioquic.quic.configuration.QuicConfiguration
quic_logger: Optional[QuicLogger] = None
at: aioquic.quic.logger.QuicLogger
to_dict() -> Dict[str, Any]
at: examples.interop
Server(name: str, host: str, port: int=4433, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)))
at: examples.interop.Server
host: str
port: int = 4433
===========changed ref 0===========
# module: examples.interop
def test_handshake_and_close(server: Server, configuration: QuicConfiguration):
async with connect(
server.host, server.port, configuration=configuration
+ ) as protocol:
- ) as connection:
+ await protocol.ping()
- await connection.ping()
server.result |= Result.H
server.result |= Result.C
===========changed ref 1===========
# module: examples.interop
- def http_request(connection: QuicConnectionProtocol, path: str):
- # perform HTTP/0.9 request
- reader, writer = await connection.create_stream()
- writer.write(("GET %s\r\n" % path).encode("utf8"))
- writer.write_eof()
-
- return await reader.read()
-
===========changed ref 2===========
# module: examples.interop
def test_stateless_retry(server: Server, configuration: QuicConfiguration):
async with connect(
server.host, server.retry_port, configuration=configuration
+ ) as protocol:
- ) as connection:
+ await protocol.ping()
- await connection.ping()
# check log
for stamp, category, event, data in configuration.quic_logger.to_dict()[
"traces"
][0]["events"]:
if (
category == "TRANSPORT"
and event == "PACKET_RECEIVED"
and data["type"] == "RETRY"
):
server.result |= Result.S
===========changed ref 3===========
# module: examples.interop
def test_http_0(server: Server, configuration: QuicConfiguration):
if server.path is None:
return
configuration.alpn_protocols = ["hq-22"]
async with connect(
+ server.host,
+ server.port,
+ configuration=configuration,
+ create_protocol=HttpClient,
+ ) as protocol:
+ protocol = cast(HttpClient, protocol)
+
+ # perform HTTP request
+ events = await protocol.get(server.host, server.path)
+ if events and isinstance(events[0], ResponseReceived):
- server.host, server.port, configuration=configuration
- ) as connection:
- response = await http_request(connection, server.path)
- if response:
server.result |= Result.D
===========changed ref 4===========
# module: examples.interop
def test_http_3(server: Server, configuration: QuicConfiguration):
if server.path is None:
return
configuration.alpn_protocols = ["h3-22"]
async with connect(
+ server.host,
+ server.port,
+ configuration=configuration,
+ create_protocol=HttpClient,
+ ) as protocol:
+ protocol = cast(HttpClient, protocol)
+
+ # perform HTTP request
+ events = await protocol.get(server.host, server.path)
+ if events and isinstance(events[0], ResponseReceived):
- server.host, server.port, configuration=configuration
- ) as connection:
- response = await http3_request(connection, server.host, server.path)
- if response:
server.result |= Result.D
server.result |= Result.three
===========changed ref 5===========
# module: examples.interop
def test_version_negotiation(server: Server, configuration: QuicConfiguration):
configuration.supported_versions = [0x1A2A3A4A, QuicProtocolVersion.DRAFT_22]
async with connect(
server.host, server.port, configuration=configuration
+ ) as protocol:
- ) as connection:
+ await protocol.ping()
- await connection.ping()
# check log
for stamp, category, event, data in configuration.quic_logger.to_dict()[
"traces"
][0]["events"]:
if (
category == "TRANSPORT"
and event == "PACKET_RECEIVED"
and data["type"] == "VERSION_NEGOTIATION"
):
server.result |= Result.V
===========changed ref 6===========
# module: examples.interop
- def http3_request(connection: QuicConnectionProtocol, authority: str, path: str):
- reader, writer = await connection.create_stream()
- stream_id = writer.get_extra_info("stream_id")
-
- http = H3Connection(connection._quic)
- 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 7===========
# module: examples.interop
def test_session_resumption(server: Server, configuration: QuicConfiguration):
saved_ticket = None
def session_ticket_handler(ticket):
nonlocal saved_ticket
saved_ticket = ticket
# connect a first time, receive a ticket
async with connect(
server.host,
server.port,
configuration=configuration,
session_ticket_handler=session_ticket_handler,
+ ) as protocol:
- ) as connection:
+ await protocol.ping()
- await connection.ping()
# connect a second time, with the ticket
if saved_ticket is not None:
configuration.session_ticket = saved_ticket
async with connect(
server.host, server.port, configuration=configuration
+ ) as protocol:
- ) as connection:
+ await protocol.ping()
- await connection.ping()
# check session was resumed
+ if protocol._quic.tls.session_resumed:
- if connection._quic.tls.session_resumed:
server.result |= Result.R
# check early data was accepted
+ if protocol._quic.tls.early_data_accepted:
- if connection._quic.tls.early_data_accepted:
server.result |= Result.Z
|
examples.interop/test_spin_bit
|
Modified
|
aiortc~aioquic
|
d4d5508146da453a8e8e0c2b5b7592652efc9401
|
[examples] use http3 client code for interop testing
|
<2>:<add> ) as protocol:
<del> ) as connection:
<4>:<add> await protocol.ping()
<del> await connection.ping()
|
# module: examples.interop
def test_spin_bit(server: Server, configuration: QuicConfiguration):
<0> async with connect(
<1> server.host, server.port, configuration=configuration
<2> ) as connection:
<3> for i in range(5):
<4> await connection.ping()
<5>
<6> # check log
<7> spin_bits = set()
<8> for stamp, category, event, data in configuration.quic_logger.to_dict()[
<9> "traces"
<10> ][0]["events"]:
<11> if category == "CONNECTIVITY" and event == "SPIN_BIT_UPDATE":
<12> spin_bits.add(data["state"])
<13> if len(spin_bits) == 2:
<14> server.result |= Result.P
<15>
|
===========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[int]=field(
default_factory=lambda: [QuicProtocolVersion.DRAFT_22]
))
at: examples.interop
Result()
Server(name: str, host: str, port: int=4433, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)))
at: examples.interop.Server
name: str
result: Result = field(default_factory=lambda: Result(0))
===========changed ref 0===========
# module: examples.interop
def test_key_update(server: Server, configuration: QuicConfiguration):
async with connect(
server.host, server.port, configuration=configuration
+ ) as protocol:
- ) as connection:
# cause some traffic
+ await protocol.ping()
- await connection.ping()
# request key update
+ protocol.request_key_update()
- connection.request_key_update()
# cause more traffic
+ await protocol.ping()
- await connection.ping()
server.result |= Result.U
===========changed ref 1===========
# module: examples.interop
def test_handshake_and_close(server: Server, configuration: QuicConfiguration):
async with connect(
server.host, server.port, configuration=configuration
+ ) as protocol:
- ) as connection:
+ await protocol.ping()
- await connection.ping()
server.result |= Result.H
server.result |= Result.C
===========changed ref 2===========
# module: examples.interop
- def http_request(connection: QuicConnectionProtocol, path: str):
- # perform HTTP/0.9 request
- reader, writer = await connection.create_stream()
- writer.write(("GET %s\r\n" % path).encode("utf8"))
- writer.write_eof()
-
- return await reader.read()
-
===========changed ref 3===========
# module: examples.interop
def test_stateless_retry(server: Server, configuration: QuicConfiguration):
async with connect(
server.host, server.retry_port, configuration=configuration
+ ) as protocol:
- ) as connection:
+ await protocol.ping()
- await connection.ping()
# check log
for stamp, category, event, data in configuration.quic_logger.to_dict()[
"traces"
][0]["events"]:
if (
category == "TRANSPORT"
and event == "PACKET_RECEIVED"
and data["type"] == "RETRY"
):
server.result |= Result.S
===========changed ref 4===========
# module: examples.interop
def test_http_0(server: Server, configuration: QuicConfiguration):
if server.path is None:
return
configuration.alpn_protocols = ["hq-22"]
async with connect(
+ server.host,
+ server.port,
+ configuration=configuration,
+ create_protocol=HttpClient,
+ ) as protocol:
+ protocol = cast(HttpClient, protocol)
+
+ # perform HTTP request
+ events = await protocol.get(server.host, server.path)
+ if events and isinstance(events[0], ResponseReceived):
- server.host, server.port, configuration=configuration
- ) as connection:
- response = await http_request(connection, server.path)
- if response:
server.result |= Result.D
===========changed ref 5===========
# module: examples.interop
def test_http_3(server: Server, configuration: QuicConfiguration):
if server.path is None:
return
configuration.alpn_protocols = ["h3-22"]
async with connect(
+ server.host,
+ server.port,
+ configuration=configuration,
+ create_protocol=HttpClient,
+ ) as protocol:
+ protocol = cast(HttpClient, protocol)
+
+ # perform HTTP request
+ events = await protocol.get(server.host, server.path)
+ if events and isinstance(events[0], ResponseReceived):
- server.host, server.port, configuration=configuration
- ) as connection:
- response = await http3_request(connection, server.host, server.path)
- if response:
server.result |= Result.D
server.result |= Result.three
===========changed ref 6===========
# module: examples.interop
def test_version_negotiation(server: Server, configuration: QuicConfiguration):
configuration.supported_versions = [0x1A2A3A4A, QuicProtocolVersion.DRAFT_22]
async with connect(
server.host, server.port, configuration=configuration
+ ) as protocol:
- ) as connection:
+ await protocol.ping()
- await connection.ping()
# check log
for stamp, category, event, data in configuration.quic_logger.to_dict()[
"traces"
][0]["events"]:
if (
category == "TRANSPORT"
and event == "PACKET_RECEIVED"
and data["type"] == "VERSION_NEGOTIATION"
):
server.result |= Result.V
===========changed ref 7===========
# module: examples.interop
- def http3_request(connection: QuicConnectionProtocol, authority: str, path: str):
- reader, writer = await connection.create_stream()
- stream_id = writer.get_extra_info("stream_id")
-
- http = H3Connection(connection._quic)
- 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 8===========
# module: examples.interop
def test_session_resumption(server: Server, configuration: QuicConfiguration):
saved_ticket = None
def session_ticket_handler(ticket):
nonlocal saved_ticket
saved_ticket = ticket
# connect a first time, receive a ticket
async with connect(
server.host,
server.port,
configuration=configuration,
session_ticket_handler=session_ticket_handler,
+ ) as protocol:
- ) as connection:
+ await protocol.ping()
- await connection.ping()
# connect a second time, with the ticket
if saved_ticket is not None:
configuration.session_ticket = saved_ticket
async with connect(
server.host, server.port, configuration=configuration
+ ) as protocol:
- ) as connection:
+ await protocol.ping()
- await connection.ping()
# check session was resumed
+ if protocol._quic.tls.session_resumed:
- if connection._quic.tls.session_resumed:
server.result |= Result.R
# check early data was accepted
+ if protocol._quic.tls.early_data_accepted:
- if connection._quic.tls.early_data_accepted:
server.result |= Result.Z
|
examples.interop/run
|
Modified
|
aiortc~aioquic
|
540e98bebef10ed262c02c97e4979876a674f25b
|
[interop] add test for rebinding
|
<7>:<add> secrets_log_file=secrets_log_file,
|
# module: examples.interop
+ def run(servers, tests, secrets_log_file=None) -> None:
- def run(servers, tests) -> None:
<0> for server in servers:
<1> for test_name, test_func in tests:
<2> print("\n=== %s %s ===\n" % (server.name, test_name))
<3> configuration = QuicConfiguration(
<4> alpn_protocols=["hq-22", "h3-22"],
<5> is_client=True,
<6> quic_logger=QuicLogger(),
<7> )
<8> try:
<9> await asyncio.wait_for(test_func(server, configuration), timeout=5)
<10> except Exception as exc:
<11> print(exc)
<12> print("")
<13> print_result(server)
<14>
<15> # print summary
<16> if len(servers) > 1:
<17> print("SUMMARY")
<18> for server in servers:
<19> print_result(server)
<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[int] = field(
default_factory=lambda: [QuicProtocolVersion.DRAFT_22]
)
at: aioquic.quic.logger.QuicLogger
to_dict() -> Dict[str, Any]
at: examples.interop
Result()
Server(name: str, host: str, port: int=4433, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)))
at: examples.interop.Server
name: str
host: str
port: int = 4433
retry_port: Optional[int] = 4434
path: str = "/"
result: Result = field(default_factory=lambda: Result(0))
===========changed ref 0===========
# module: examples.interop
+ def test_rebinding(server: Server, configuration: QuicConfiguration):
+ async with connect(
+ server.host, server.port, configuration=configuration
+ ) as protocol:
+ # cause some traffic
+ await protocol.ping()
+
+ # replace transport
+ protocol._transport.close()
+ await loop.create_datagram_endpoint(lambda: protocol, local_addr=("::", 0))
+
+ # cause more traffic
+ await protocol.ping()
+
+ server.result |= Result.B
+
|
aioquic.quic.logger/QuicLogger.to_dict
|
Modified
|
aiortc~aioquic
|
9d0f8d65fae17342dfbb653725a4810aab7976eb
|
[qlog] improve logging
|
<13>:<add> event[1],
<del> event[1].upper(), # draft-00
<14>:<add> event[2],
<del> event[2].upper(), # draft-00
|
# module: aioquic.quic.logger
class QuicLogger:
def to_dict(self) -> Dict[str, Any]:
<0> """
<1> Return the trace as a dictionary which can be written as JSON.
<2> """
<3> traces = []
<4> if self._events:
<5> reference_time = self._events[0][0]
<6> trace = {
<7> "common_fields": {"reference_time": "%d" % (reference_time * 1000)},
<8> "event_fields": ["relative_time", "CATEGORY", "EVENT_TYPE", "DATA"],
<9> "events": list(
<10> map(
<11> lambda event: (
<12> "%d" % ((event[0] - reference_time) * 1000),
<13> event[1].upper(), # draft-00
<14> event[2].upper(), # draft-00
<15> event[3],
<16> ),
<17> self._events,
<18> )
<19> ),
<20> }
<21> traces.append(trace)
<22>
<23> return {"qlog_version": "draft-00", "traces": traces}
<24>
|
===========unchanged ref 0===========
at: aioquic.quic.logger.QuicLogger.__init__
self._events: Deque[Tuple[float, str, str, Dict[str, Any]]] = deque()
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
|
aioquic.quic.recovery/QuicPacketRecovery.on_ack_received
|
Modified
|
aiortc~aioquic
|
9d0f8d65fae17342dfbb653725a4810aab7976eb
|
[qlog] improve logging
|
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def on_ack_received(
self,
space: QuicPacketSpace,
ack_rangeset: RangeSet,
ack_delay_encoded: int,
now: float,
) -> None:
<0> """
<1> Update metrics as the result of an ACK being received.
<2> """
<3> is_ack_eliciting = False
<4> largest_acked = ack_rangeset.bounds().stop - 1
<5> largest_newly_acked = None
<6> largest_sent_time = None
<7>
<8> if largest_acked > space.largest_acked_packet:
<9> space.largest_acked_packet = largest_acked
<10>
<11> for packet_number in sorted(space.sent_packets.keys()):
<12> if packet_number > largest_acked:
<13> break
<14> if packet_number in ack_rangeset:
<15> # remove packet and update counters
<16> packet = space.sent_packets.pop(packet_number)
<17> if packet.is_ack_eliciting:
<18> is_ack_eliciting = True
<19> space.ack_eliciting_in_flight -= 1
<20> if packet.in_flight:
<21> self.on_packet_acked(packet)
<22> largest_newly_acked = packet_number
<23> largest_sent_time = packet.sent_time
<24>
<25> # trigger callbacks
<26> for handler, args in packet.delivery_handlers:
<27> handler(QuicDeliveryState.ACKED, *args)
<28>
<29> # nothing to do if there are no newly acked packets
<30> if largest_newly_acked is None:
<31> return
<32>
<33> if largest_acked == largest_newly_acked and is_ack_eliciting:
<34> latest_rtt = now - largest_sent_time
<35>
<36> # decode ACK delay into seconds
<37> ack_delay = max(
<38> (ack_delay_encoded << self.ack_delay_</s>
|
===========below chunk 0===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def on_ack_received(
self,
space: QuicPacketSpace,
ack_rangeset: RangeSet,
ack_delay_encoded: int,
now: float,
) -> None:
# offset: 1
self.max_ack_delay / 1000,
)
# update RTT estimate, which cannot be < 1 ms
self._rtt_latest = max(latest_rtt, 0.001)
if self._rtt_latest < self._rtt_min:
self._rtt_min = self._rtt_latest
if self._rtt_latest > self._rtt_min + ack_delay:
self._rtt_latest -= ack_delay
if not self._rtt_initialized:
self._rtt_initialized = True
self._rtt_variance = latest_rtt / 2
self._rtt_smoothed = latest_rtt
else:
self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs(
self._rtt_min - self._rtt_latest
)
self._rtt_smoothed = (
7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest
)
if self._quic_logger is not None:
self._quic_logger.log_event(
category="recovery",
event="metric_update",
data={
"latest_rtt": int(self._rtt_latest * 1000),
"min_rtt": int(self._rtt_min * 1000),
"smoothed_rtt": int(self._rtt_smoothed * 1000),
"rtt_variance": int(self._rtt_variance * 1000),
},
)
self.detect_loss(space, now=now)
self._pto_count = 0
===========unchanged ref 0===========
at: aioquic.quic.logger.QuicLogger
log_event(*, category: str, event: str, data: Dict) -> None
at: aioquic.quic.packet_builder
QuicDeliveryState()
at: aioquic.quic.packet_builder.QuicSentPacket
epoch: Epoch
in_flight: bool
is_ack_eliciting: bool
is_crypto_packet: bool
packet_number: int
packet_type: int
sent_time: Optional[float] = None
sent_bytes: int = 0
delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(
default_factory=list
)
at: aioquic.quic.rangeset
RangeSet(ranges: Iterable[range]=[])
at: aioquic.quic.rangeset.RangeSet
bounds() -> range
at: aioquic.quic.recovery
QuicPacketSpace()
at: aioquic.quic.recovery.QuicPacketRecovery
detect_loss(space: QuicPacketSpace, now: float) -> None
on_packet_acked(packet: QuicSentPacket) -> None
at: aioquic.quic.recovery.QuicPacketRecovery.__init__
self.ack_delay_exponent = 3
self.max_ack_delay = 25 # ms
self._quic_logger = quic_logger
self._pto_count = 0
self._rtt_initialized = False
self._rtt_latest = 0.0
self._rtt_min = math.inf
self._rtt_smoothed = 0.0
self._rtt_variance = 0.0
at: aioquic.quic.recovery.QuicPacketRecovery.on_loss_detection_timeout
self._pto_count += 1
at: aioquic.quic.recovery.QuicPacketSpace.__init__
self.ack_eliciting_in_flight = 0
===========unchanged ref 1===========
self.largest_acked_packet = 0
self.sent_packets: Dict[int, QuicSentPacket] = {}
at: typing.MutableMapping
pop(key: _KT) -> _VT
pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T]
===========changed ref 0===========
# module: aioquic.quic.logger
class QuicLogger:
def to_dict(self) -> Dict[str, Any]:
"""
Return the trace as a dictionary which can be written as JSON.
"""
traces = []
if self._events:
reference_time = self._events[0][0]
trace = {
"common_fields": {"reference_time": "%d" % (reference_time * 1000)},
"event_fields": ["relative_time", "CATEGORY", "EVENT_TYPE", "DATA"],
"events": list(
map(
lambda event: (
"%d" % ((event[0] - reference_time) * 1000),
+ event[1],
- event[1].upper(), # draft-00
+ event[2],
- event[2].upper(), # draft-00
event[3],
),
self._events,
)
),
}
traces.append(trace)
return {"qlog_version": "draft-00", "traces": traces}
|
|
aioquic.quic.recovery/QuicPacketRecovery.on_packet_lost
|
Modified
|
aiortc~aioquic
|
9d0f8d65fae17342dfbb653725a4810aab7976eb
|
[qlog] improve logging
|
<9>:<add> category="RECOVERY",
<del> category="recovery",
<10>:<add> event="PACKET_LOST",
<del> event="packet_lost",
<13>:<add> "packet_number": str(packet.packet_number),
<del> "packet_number": packet.packet_number,
|
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def on_packet_lost(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None:
<0> del space.sent_packets[packet.packet_number]
<1>
<2> if packet.is_ack_eliciting:
<3> space.ack_eliciting_in_flight -= 1
<4> if packet.in_flight:
<5> self.bytes_in_flight -= packet.sent_bytes
<6>
<7> if self._quic_logger is not None:
<8> self._quic_logger.log_event(
<9> category="recovery",
<10> event="packet_lost",
<11> data={
<12> "type": self._quic_logger.packet_type(packet.packet_type),
<13> "packet_number": packet.packet_number,
<14> },
<15> )
<16> self._log_metric_update()
<17>
<18> # trigger callbacks
<19> for handler, args in packet.delivery_handlers:
<20> handler(QuicDeliveryState.LOST, *args)
<21>
|
===========unchanged ref 0===========
at: aioquic.quic.logger.QuicLogger
log_event(*, category: str, event: str, data: Dict) -> None
packet_type(packet_type: int) -> str
at: aioquic.quic.packet_builder
QuicDeliveryState()
QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, packet_type: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field(
default_factory=list
))
at: aioquic.quic.packet_builder.QuicSentPacket
in_flight: bool
is_ack_eliciting: bool
packet_number: int
packet_type: int
sent_bytes: int = 0
delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(
default_factory=list
)
at: aioquic.quic.recovery
QuicPacketSpace()
at: aioquic.quic.recovery.QuicPacketRecovery
_log_metric_update(self) -> None
_log_metric_update() -> None
at: aioquic.quic.recovery.QuicPacketRecovery.__init__
self._quic_logger = quic_logger
self.bytes_in_flight = 0
at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_acked
self.bytes_in_flight -= packet.sent_bytes
at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_expired
self.bytes_in_flight -= packet.sent_bytes
at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_sent
self.bytes_in_flight += packet.sent_bytes
===========unchanged ref 1===========
at: aioquic.quic.recovery.QuicPacketSpace.__init__
self.ack_eliciting_in_flight = 0
self.sent_packets: Dict[int, QuicSentPacket] = {}
===========changed ref 0===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def on_ack_received(
self,
space: QuicPacketSpace,
ack_rangeset: RangeSet,
ack_delay_encoded: int,
now: float,
) -> None:
"""
Update metrics as the result of an ACK being received.
"""
is_ack_eliciting = False
largest_acked = ack_rangeset.bounds().stop - 1
largest_newly_acked = None
largest_sent_time = None
if largest_acked > space.largest_acked_packet:
space.largest_acked_packet = largest_acked
for packet_number in sorted(space.sent_packets.keys()):
if packet_number > largest_acked:
break
if packet_number in ack_rangeset:
# remove packet and update counters
packet = space.sent_packets.pop(packet_number)
if packet.is_ack_eliciting:
is_ack_eliciting = True
space.ack_eliciting_in_flight -= 1
if packet.in_flight:
self.on_packet_acked(packet)
largest_newly_acked = packet_number
largest_sent_time = packet.sent_time
# trigger callbacks
for handler, args in packet.delivery_handlers:
handler(QuicDeliveryState.ACKED, *args)
# nothing to do if there are no newly acked packets
if largest_newly_acked is None:
return
if largest_acked == largest_newly_acked and is_ack_eliciting:
latest_rtt = now - largest_sent_time
# decode ACK delay into seconds
ack_delay = max(
(ack_delay_encoded << self.ack_delay_exponent) / 1000000,
self.max_ack_delay / 1000,
)
# update RTT estimate, which cannot be < 1 ms
self._</s>
===========changed ref 1===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def on_ack_received(
self,
space: QuicPacketSpace,
ack_rangeset: RangeSet,
ack_delay_encoded: int,
now: float,
) -> None:
# offset: 1
<s>max_ack_delay / 1000,
)
# update RTT estimate, which cannot be < 1 ms
self._rtt_latest = max(latest_rtt, 0.001)
if self._rtt_latest < self._rtt_min:
self._rtt_min = self._rtt_latest
if self._rtt_latest > self._rtt_min + ack_delay:
self._rtt_latest -= ack_delay
if not self._rtt_initialized:
self._rtt_initialized = True
self._rtt_variance = latest_rtt / 2
self._rtt_smoothed = latest_rtt
else:
self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs(
self._rtt_min - self._rtt_latest
)
self._rtt_smoothed = (
7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest
)
if self._quic_logger is not None:
self._quic_logger.log_event(
+ category="RECOVERY",
- category="recovery",
+ event="METRIC_UPDATE",
- event="metric_update",
data={
"latest_rtt": int(self._rtt_latest * 1000),
"min_rtt": int(self._rtt_min * 1000),
"smoothed_rtt": int(self._rtt_smoothed * 1000),
"rtt_variance": int(self._rtt_variance * 1000),
},
)
self
===========changed ref 2===========
# module: aioquic.quic.logger
class QuicLogger:
def to_dict(self) -> Dict[str, Any]:
"""
Return the trace as a dictionary which can be written as JSON.
"""
traces = []
if self._events:
reference_time = self._events[0][0]
trace = {
"common_fields": {"reference_time": "%d" % (reference_time * 1000)},
"event_fields": ["relative_time", "CATEGORY", "EVENT_TYPE", "DATA"],
"events": list(
map(
lambda event: (
"%d" % ((event[0] - reference_time) * 1000),
+ event[1],
- event[1].upper(), # draft-00
+ event[2],
- event[2].upper(), # draft-00
event[3],
),
self._events,
)
),
}
traces.append(trace)
return {"qlog_version": "draft-00", "traces": traces}
|
aioquic.quic.recovery/QuicPacketRecovery._log_metric_update
|
Modified
|
aiortc~aioquic
|
9d0f8d65fae17342dfbb653725a4810aab7976eb
|
[qlog] improve logging
|
<5>:<add> category="RECOVERY", event="METRIC_UPDATE", data=data
<del> category="recovery", event="metric_update", data=data
|
# module: aioquic.quic.recovery
class QuicPacketRecovery:
# TODO : collapse congestion window if persistent congestion
def _log_metric_update(self) -> None:
<0> data = {"bytes_in_flight": self.bytes_in_flight, "cwnd": self.congestion_window}
<1> if self._ssthresh is not None:
<2> data["ssthresh"] = self._ssthresh
<3>
<4> self._quic_logger.log_event(
<5> category="recovery", event="metric_update", data=data
<6> )
<7>
|
===========unchanged ref 0===========
at: aioquic.quic.logger.QuicLogger
log_event(*, category: str, event: str, data: Dict) -> None
at: aioquic.quic.recovery.QuicPacketRecovery.__init__
self._quic_logger = quic_logger
self.bytes_in_flight = 0
self.congestion_window = K_INITIAL_WINDOW
self._ssthresh: Optional[int] = None
at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_acked
self.bytes_in_flight -= packet.sent_bytes
self.congestion_window += (
K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window
)
self.congestion_window += packet.sent_bytes
at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_expired
self.bytes_in_flight -= packet.sent_bytes
at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_lost
self.bytes_in_flight -= packet.sent_bytes
at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_sent
self.bytes_in_flight += packet.sent_bytes
at: aioquic.quic.recovery.QuicPacketRecovery.on_packets_lost
self.congestion_window = max(
int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW
)
self._ssthresh = self.congestion_window
===========changed ref 0===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def on_packet_lost(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None:
del space.sent_packets[packet.packet_number]
if packet.is_ack_eliciting:
space.ack_eliciting_in_flight -= 1
if packet.in_flight:
self.bytes_in_flight -= packet.sent_bytes
if self._quic_logger is not None:
self._quic_logger.log_event(
+ category="RECOVERY",
- category="recovery",
+ event="PACKET_LOST",
- event="packet_lost",
data={
"type": self._quic_logger.packet_type(packet.packet_type),
+ "packet_number": str(packet.packet_number),
- "packet_number": packet.packet_number,
},
)
self._log_metric_update()
# trigger callbacks
for handler, args in packet.delivery_handlers:
handler(QuicDeliveryState.LOST, *args)
===========changed ref 1===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def on_ack_received(
self,
space: QuicPacketSpace,
ack_rangeset: RangeSet,
ack_delay_encoded: int,
now: float,
) -> None:
"""
Update metrics as the result of an ACK being received.
"""
is_ack_eliciting = False
largest_acked = ack_rangeset.bounds().stop - 1
largest_newly_acked = None
largest_sent_time = None
if largest_acked > space.largest_acked_packet:
space.largest_acked_packet = largest_acked
for packet_number in sorted(space.sent_packets.keys()):
if packet_number > largest_acked:
break
if packet_number in ack_rangeset:
# remove packet and update counters
packet = space.sent_packets.pop(packet_number)
if packet.is_ack_eliciting:
is_ack_eliciting = True
space.ack_eliciting_in_flight -= 1
if packet.in_flight:
self.on_packet_acked(packet)
largest_newly_acked = packet_number
largest_sent_time = packet.sent_time
# trigger callbacks
for handler, args in packet.delivery_handlers:
handler(QuicDeliveryState.ACKED, *args)
# nothing to do if there are no newly acked packets
if largest_newly_acked is None:
return
if largest_acked == largest_newly_acked and is_ack_eliciting:
latest_rtt = now - largest_sent_time
# decode ACK delay into seconds
ack_delay = max(
(ack_delay_encoded << self.ack_delay_exponent) / 1000000,
self.max_ack_delay / 1000,
)
# update RTT estimate, which cannot be < 1 ms
self._</s>
===========changed ref 2===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def on_ack_received(
self,
space: QuicPacketSpace,
ack_rangeset: RangeSet,
ack_delay_encoded: int,
now: float,
) -> None:
# offset: 1
<s>max_ack_delay / 1000,
)
# update RTT estimate, which cannot be < 1 ms
self._rtt_latest = max(latest_rtt, 0.001)
if self._rtt_latest < self._rtt_min:
self._rtt_min = self._rtt_latest
if self._rtt_latest > self._rtt_min + ack_delay:
self._rtt_latest -= ack_delay
if not self._rtt_initialized:
self._rtt_initialized = True
self._rtt_variance = latest_rtt / 2
self._rtt_smoothed = latest_rtt
else:
self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs(
self._rtt_min - self._rtt_latest
)
self._rtt_smoothed = (
7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest
)
if self._quic_logger is not None:
self._quic_logger.log_event(
+ category="RECOVERY",
- category="recovery",
+ event="METRIC_UPDATE",
- event="metric_update",
data={
"latest_rtt": int(self._rtt_latest * 1000),
"min_rtt": int(self._rtt_min * 1000),
"smoothed_rtt": int(self._rtt_smoothed * 1000),
"rtt_variance": int(self._rtt_variance * 1000),
},
)
self
===========changed ref 3===========
# module: aioquic.quic.logger
class QuicLogger:
def to_dict(self) -> Dict[str, Any]:
"""
Return the trace as a dictionary which can be written as JSON.
"""
traces = []
if self._events:
reference_time = self._events[0][0]
trace = {
"common_fields": {"reference_time": "%d" % (reference_time * 1000)},
"event_fields": ["relative_time", "CATEGORY", "EVENT_TYPE", "DATA"],
"events": list(
map(
lambda event: (
"%d" % ((event[0] - reference_time) * 1000),
+ event[1],
- event[1].upper(), # draft-00
+ event[2],
- event[2].upper(), # draft-00
event[3],
),
self._events,
)
),
}
traces.append(trace)
return {"qlog_version": "draft-00", "traces": traces}
|
aioquic.quic.connection/QuicConnection.datagrams_to_send
|
Modified
|
aiortc~aioquic
|
9d0f8d65fae17342dfbb653725a4810aab7976eb
|
[qlog] improve logging
|
# module: aioquic.quic.connection
class QuicConnection:
def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]:
<0> """
<1> Return a list of `(data, addr)` tuples of datagrams which need to be
<2> sent, and the network address to which they need to be sent.
<3>
<4> :param now: The current time.
<5> """
<6> network_path = self._network_paths[0]
<7>
<8> if self._state in END_STATES:
<9> return []
<10>
<11> # build datagrams
<12> builder = QuicPacketBuilder(
<13> host_cid=self.host_cid,
<14> packet_number=self._packet_number,
<15> pad_first_datagram=(
<16> self._is_client and self._state == QuicConnectionState.FIRSTFLIGHT
<17> ),
<18> peer_cid=self._peer_cid,
<19> peer_token=self._peer_token,
<20> spin_bit=self._spin_bit,
<21> version=self._version,
<22> )
<23> if self._close_pending:
<24> for epoch, packet_type in (
<25> (tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT),
<26> (tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE),
<27> (tls.Epoch.INITIAL, PACKET_TYPE_INITIAL),
<28> ):
<29> crypto = self._cryptos[epoch]
<30> if crypto.send.is_valid():
<31> builder.start_packet(packet_type, crypto)
<32> write_close_frame(
<33> builder=builder,
<34> error_code=self._close_event.error_code,
<35> frame_type=self._close_event.frame_type,
<36> reason_phrase=self._close_event.reason_phrase,
<37> )
<38> builder.end_packet()
<39> self._close_pending = False
<40> break
<41> self._close_begin(is_initiator=True, now</s>
|
===========below chunk 0===========
# module: aioquic.quic.connection
class QuicConnection:
def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]:
# offset: 1
else:
# congestion control
builder.max_flight_bytes = (
self._loss.congestion_window - self._loss.bytes_in_flight
)
if self._probe_pending and builder.max_flight_bytes < PACKET_MAX_SIZE:
builder.max_flight_bytes = PACKET_MAX_SIZE
# limit data on un-validated network paths
if not network_path.is_validated:
builder.max_total_bytes = (
network_path.bytes_received * 3 - network_path.bytes_sent
)
try:
if not self._handshake_confirmed:
for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]:
self._write_handshake(builder, epoch)
self._write_application(builder, network_path, now)
except QuicPacketBuilderStop:
pass
datagrams, packets = builder.flush()
if datagrams:
self._packet_number = builder.packet_number
# register packets
sent_handshake = False
for packet in packets:
packet.sent_time = now
self._loss.on_packet_sent(
packet=packet, space=self._spaces[packet.epoch]
)
if packet.epoch == tls.Epoch.HANDSHAKE:
sent_handshake = True
# log packet
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="packet_sent",
data={
"type": self._quic_logger.packet_type(packet.packet_type),
"header": {
"packet_number": packet.packet_number,
"packet_size": packet.sent_bytes,
},
"frames": [],
},
)
</s>
===========below chunk 1===========
# module: aioquic.quic.connection
class QuicConnection:
def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]:
# offset: 2
<s>
"packet_size": packet.sent_bytes,
},
"frames": [],
},
)
# check if we can discard initial keys
if sent_handshake and self._is_client:
self._discard_epoch(tls.Epoch.INITIAL)
# return datagrams to send and the destination network address
ret = []
for datagram in datagrams:
byte_length = len(datagram)
network_path.bytes_sent += byte_length
ret.append((datagram, network_path.addr))
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="datagram_sent",
data={"byte_length": byte_length, "count": 1},
)
return ret
===========unchanged ref 0===========
at: aioquic.quic.connection
NetworkAddress = Any
dump_cid(cid: bytes) -> str
write_close_frame(builder: QuicPacketBuilder, error_code: int, frame_type: Optional[int], reason_phrase: str) -> None
QuicConnectionState()
END_STATES = frozenset(
[
QuicConnectionState.CLOSING,
QuicConnectionState.DRAINING,
QuicConnectionState.TERMINATED,
]
)
at: aioquic.quic.connection.QuicConnection
_close_begin(is_initiator: bool, now: float) -> None
at: aioquic.quic.connection.QuicConnection.__init__
self._is_client = configuration.is_client
self._close_event: Optional[events.ConnectionTerminated] = None
self._cryptos: Dict[tls.Epoch, CryptoPair] = {}
self.host_cid = self._host_cids[0].cid
self._loss = QuicPacketRecovery(
is_client_without_1rtt=self._is_client,
quic_logger=self._quic_logger,
send_probe=self._send_probe,
)
self._network_paths: List[QuicNetworkPath] = []
self._packet_number = 0
self._peer_cid = os.urandom(8)
self._peer_token = b""
self._spin_bit = False
self._state = QuicConnectionState.FIRSTFLIGHT
self._version: Optional[int] = None
self._close_pending = False
self._probe_pending = False
at: aioquic.quic.connection.QuicConnection._handle_connection_close_frame
self._close_event = events.ConnectionTerminated(
error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase
)
===========unchanged ref 1===========
at: aioquic.quic.connection.QuicConnection._initialize
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
self._packet_number = 0
at: aioquic.quic.connection.QuicConnection._send_probe
self._probe_pending = True
at: aioquic.quic.connection.QuicConnection._set_state
self._state = state
at: aioquic.quic.connection.QuicConnection._write_application
self._probe_pending = False
at: aioquic.quic.connection.QuicConnection._write_handshake
self._probe_pending = False
at: aioquic.quic.connection.QuicConnection.change_connection_id
self._peer_cid = connection_id.cid
at: aioquic.quic.connection.QuicConnection.close
self._close_event = events.ConnectionTerminated(
error_code=error_code,
frame_type=frame_type,
reason_phrase=reason_phrase,
)
self._close_pending = True
at: aioquic.quic.connection.QuicConnection.connect
self._network_paths = [QuicNetworkPath(addr, is_validated=True)]
self._version = self._configuration.supported_versions[0]
at: aioquic.quic.connection.QuicConnection.handle_timer
self._close_event = events.ConnectionTerminated(
error_code=QuicErrorCode.INTERNAL_ERROR,
frame_type=None,
reason_phrase="Idle timeout",
)
|
|
aioquic.quic.connection/QuicConnection._handle_ack_frame
|
Modified
|
aiortc~aioquic
|
9d0f8d65fae17342dfbb653725a4810aab7976eb
|
[qlog] improve logging
|
<16>:<add> "acked_ranges": [
<add> [str(x.start), str(x.stop - 1)] for x in ack_rangeset
<del> "acked_ranges": [[x.start, x.stop - 1] for x in ack_rangeset],
<17>:<add> ],
<add> "frame_type": "ACK",
<del> "type": "ack",
|
# 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> # log frame
<10> if context.quic_logger_frames is not None:
<11> context.quic_logger_frames.append(
<12> {
<13> "ack_delay": str(
<14> (ack_delay_encoded << self._loss.ack_delay_exponent) // 1000
<15> ),
<16> "acked_ranges": [[x.start, x.stop - 1] for x in ack_rangeset],
<17> "type": "ack",
<18> }
<19> )
<20>
<21> self._loss.on_ack_received(
<22> space=self._spaces[context.epoch],
<23> ack_rangeset=ack_rangeset,
<24> ack_delay_encoded=ack_delay_encoded,
<25> now=context.time,
<26> )
<27>
<28> # check if we can discard handshake keys
<29> if (
<30> not self._handshake_confirmed
<31> and self._handshake_complete
<32> and context.epoch == tls.Epoch.ONE_RTT
<33> ):
<34> self._discard_epoch(tls.Epoch.HANDSHAKE)
<35> self._handshake_confirmed = True
<36>
|
===========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, quic_logger_frames: Optional[List[Any]], time: float)
at: aioquic.quic.connection.QuicConnection.__init__
self._is_client = configuration.is_client
self._cryptos: Dict[tls.Epoch, CryptoPair] = {}
self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}
self._loss = QuicPacketRecovery(
is_client_without_1rtt=self._is_client,
quic_logger=self._quic_logger,
send_probe=self._send_probe,
)
self._packet_number = 0
self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}
at: aioquic.quic.connection.QuicConnection._initialize
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
at: aioquic.quic.connection.QuicConnection.datagrams_to_send
self._packet_number = builder.packet_number
at: aioquic.quic.connection.QuicReceiveContext
epoch: tls.Epoch
host_cid: bytes
network_path: QuicNetworkPath
quic_logger_frames: Optional[List[Any]]
time: float
at: aioquic.quic.crypto.CryptoPair
setup_initial(cid: bytes, is_client: bool) -> None
===========unchanged ref 1===========
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]
at: aioquic.quic.recovery
QuicPacketSpace()
at: aioquic.quic.recovery.QuicPacketRecovery.__init__
self.ack_delay_exponent = 3
self.spaces: List[QuicPacketSpace] = []
at: aioquic.quic.stream
QuicStream(stream_id: Optional[int]=None, connection: Optional[Any]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0)
at: aioquic.tls
Epoch()
===========changed ref 0===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
# TODO : collapse congestion window if persistent congestion
def _log_metric_update(self) -> None:
data = {"bytes_in_flight": self.bytes_in_flight, "cwnd": self.congestion_window}
if self._ssthresh is not None:
data["ssthresh"] = self._ssthresh
self._quic_logger.log_event(
+ category="RECOVERY", event="METRIC_UPDATE", data=data
- category="recovery", event="metric_update", data=data
)
===========changed ref 1===========
# module: aioquic.quic.logger
class QuicLogger:
def to_dict(self) -> Dict[str, Any]:
"""
Return the trace as a dictionary which can be written as JSON.
"""
traces = []
if self._events:
reference_time = self._events[0][0]
trace = {
"common_fields": {"reference_time": "%d" % (reference_time * 1000)},
"event_fields": ["relative_time", "CATEGORY", "EVENT_TYPE", "DATA"],
"events": list(
map(
lambda event: (
"%d" % ((event[0] - reference_time) * 1000),
+ event[1],
- event[1].upper(), # draft-00
+ event[2],
- event[2].upper(), # draft-00
event[3],
),
self._events,
)
),
}
traces.append(trace)
return {"qlog_version": "draft-00", "traces": traces}
===========changed ref 2===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def on_packet_lost(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None:
del space.sent_packets[packet.packet_number]
if packet.is_ack_eliciting:
space.ack_eliciting_in_flight -= 1
if packet.in_flight:
self.bytes_in_flight -= packet.sent_bytes
if self._quic_logger is not None:
self._quic_logger.log_event(
+ category="RECOVERY",
- category="recovery",
+ event="PACKET_LOST",
- event="packet_lost",
data={
"type": self._quic_logger.packet_type(packet.packet_type),
+ "packet_number": str(packet.packet_number),
- "packet_number": packet.packet_number,
},
)
self._log_metric_update()
# trigger callbacks
for handler, args in packet.delivery_handlers:
handler(QuicDeliveryState.LOST, *args)
===========changed ref 3===========
# module: aioquic.quic.connection
class QuicConnection:
def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]:
"""
Return a list of `(data, addr)` tuples of datagrams which need to be
sent, and the network address to which they need to be sent.
:param now: The current time.
"""
network_path = self._network_paths[0]
if self._state in END_STATES:
return []
# build datagrams
builder = QuicPacketBuilder(
host_cid=self.host_cid,
packet_number=self._packet_number,
pad_first_datagram=(
self._is_client and self._state == QuicConnectionState.FIRSTFLIGHT
),
peer_cid=self._peer_cid,
peer_token=self._peer_token,
spin_bit=self._spin_bit,
version=self._version,
)
if self._close_pending:
for epoch, packet_type in (
(tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT),
(tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE),
(tls.Epoch.INITIAL, PACKET_TYPE_INITIAL),
):
crypto = self._cryptos[epoch]
if crypto.send.is_valid():
builder.start_packet(packet_type, crypto)
write_close_frame(
builder=builder,
error_code=self._close_event.error_code,
frame_type=self._close_event.frame_type,
reason_phrase=self._close_event.reason_phrase,
)
builder.end_packet()
self._close_pending = False
break
self._close_begin(is_initiator=True, now=now)
else:
# congestion control
builder.max_flight_bytes = (
self._loss.congestion_window - self._loss.bytes</s>
|
examples.interop/test_version_negotiation
|
Modified
|
aiortc~aioquic
|
9d0f8d65fae17342dfbb653725a4810aab7976eb
|
[qlog] improve logging
|
<14>:<add> and data["packet_type"] == "VERSION_NEGOTIATION"
<del> and data["type"] == "VERSION_NEGOTIATION"
|
# module: examples.interop
def test_version_negotiation(server: Server, configuration: QuicConfiguration):
<0> configuration.supported_versions = [0x1A2A3A4A, QuicProtocolVersion.DRAFT_22]
<1>
<2> async with connect(
<3> server.host, server.port, configuration=configuration
<4> ) as protocol:
<5> await protocol.ping()
<6>
<7> # check log
<8> for stamp, category, event, data in configuration.quic_logger.to_dict()[
<9> "traces"
<10> ][0]["events"]:
<11> if (
<12> category == "TRANSPORT"
<13> and event == "PACKET_RECEIVED"
<14> and data["type"] == "VERSION_NEGOTIATION"
<15> ):
<16> server.result |= Result.V
<17>
|
===========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
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[int]=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[int] = field(
default_factory=lambda: [QuicProtocolVersion.DRAFT_22]
)
at: aioquic.quic.logger.QuicLogger
to_dict() -> Dict[str, Any]
===========unchanged ref 1===========
at: aioquic.quic.packet
QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int)
QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
at: examples.interop
Result()
Server(name: str, host: str, port: int=4433, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)))
at: examples.interop.Server
name: str
host: str
port: int = 4433
retry_port: Optional[int] = 4434
path: str = "/"
result: Result = field(default_factory=lambda: Result(0))
===========changed ref 0===========
# module: aioquic.quic.logger
class QuicLogger:
def to_dict(self) -> Dict[str, Any]:
"""
Return the trace as a dictionary which can be written as JSON.
"""
traces = []
if self._events:
reference_time = self._events[0][0]
trace = {
"common_fields": {"reference_time": "%d" % (reference_time * 1000)},
"event_fields": ["relative_time", "CATEGORY", "EVENT_TYPE", "DATA"],
"events": list(
map(
lambda event: (
"%d" % ((event[0] - reference_time) * 1000),
+ event[1],
- event[1].upper(), # draft-00
+ event[2],
- event[2].upper(), # draft-00
event[3],
),
self._events,
)
),
}
traces.append(trace)
return {"qlog_version": "draft-00", "traces": traces}
===========changed ref 1===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
# TODO : collapse congestion window if persistent congestion
def _log_metric_update(self) -> None:
data = {"bytes_in_flight": self.bytes_in_flight, "cwnd": self.congestion_window}
if self._ssthresh is not None:
data["ssthresh"] = self._ssthresh
self._quic_logger.log_event(
+ category="RECOVERY", event="METRIC_UPDATE", data=data
- category="recovery", event="metric_update", data=data
)
===========changed ref 2===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def on_packet_lost(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None:
del space.sent_packets[packet.packet_number]
if packet.is_ack_eliciting:
space.ack_eliciting_in_flight -= 1
if packet.in_flight:
self.bytes_in_flight -= packet.sent_bytes
if self._quic_logger is not None:
self._quic_logger.log_event(
+ category="RECOVERY",
- category="recovery",
+ event="PACKET_LOST",
- event="packet_lost",
data={
"type": self._quic_logger.packet_type(packet.packet_type),
+ "packet_number": str(packet.packet_number),
- "packet_number": packet.packet_number,
},
)
self._log_metric_update()
# trigger callbacks
for handler, args in packet.delivery_handlers:
handler(QuicDeliveryState.LOST, *args)
===========changed ref 3===========
# 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": [
+ [str(x.start), str(x.stop - 1)] for x in ack_rangeset
- "acked_ranges": [[x.start, x.stop - 1] for x in ack_rangeset],
+ ],
+ "frame_type": "ACK",
- "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.interop/test_stateless_retry
|
Modified
|
aiortc~aioquic
|
9d0f8d65fae17342dfbb653725a4810aab7976eb
|
[qlog] improve logging
|
<12>:<add> and data["packet_type"] == "RETRY"
<del> and data["type"] == "RETRY"
|
# module: examples.interop
def test_stateless_retry(server: Server, configuration: QuicConfiguration):
<0> async with connect(
<1> server.host, server.retry_port, configuration=configuration
<2> ) as protocol:
<3> await protocol.ping()
<4>
<5> # check log
<6> for stamp, category, event, data in configuration.quic_logger.to_dict()[
<7> "traces"
<8> ][0]["events"]:
<9> if (
<10> category == "TRANSPORT"
<11> and event == "PACKET_RECEIVED"
<12> and data["type"] == "RETRY"
<13> ):
<14> server.result |= Result.S
<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
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[int]=field(
default_factory=lambda: [QuicProtocolVersion.DRAFT_22]
))
at: aioquic.quic.configuration.QuicConfiguration
quic_logger: Optional[QuicLogger] = None
at: aioquic.quic.logger.QuicLogger
to_dict() -> Dict[str, Any]
at: examples.interop
Result()
Server(name: str, host: str, port: int=4433, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)))
at: examples.interop.Server
host: str
retry_port: Optional[int] = 4434
result: Result = field(default_factory=lambda: Result(0))
===========changed ref 0===========
# module: aioquic.quic.logger
class QuicLogger:
def to_dict(self) -> Dict[str, Any]:
"""
Return the trace as a dictionary which can be written as JSON.
"""
traces = []
if self._events:
reference_time = self._events[0][0]
trace = {
"common_fields": {"reference_time": "%d" % (reference_time * 1000)},
"event_fields": ["relative_time", "CATEGORY", "EVENT_TYPE", "DATA"],
"events": list(
map(
lambda event: (
"%d" % ((event[0] - reference_time) * 1000),
+ event[1],
- event[1].upper(), # draft-00
+ event[2],
- event[2].upper(), # draft-00
event[3],
),
self._events,
)
),
}
traces.append(trace)
return {"qlog_version": "draft-00", "traces": traces}
===========changed ref 1===========
# module: examples.interop
def test_version_negotiation(server: Server, configuration: QuicConfiguration):
configuration.supported_versions = [0x1A2A3A4A, QuicProtocolVersion.DRAFT_22]
async with connect(
server.host, server.port, configuration=configuration
) as protocol:
await protocol.ping()
# check log
for stamp, category, event, data in configuration.quic_logger.to_dict()[
"traces"
][0]["events"]:
if (
category == "TRANSPORT"
and event == "PACKET_RECEIVED"
+ and data["packet_type"] == "VERSION_NEGOTIATION"
- and data["type"] == "VERSION_NEGOTIATION"
):
server.result |= Result.V
===========changed ref 2===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
# TODO : collapse congestion window if persistent congestion
def _log_metric_update(self) -> None:
data = {"bytes_in_flight": self.bytes_in_flight, "cwnd": self.congestion_window}
if self._ssthresh is not None:
data["ssthresh"] = self._ssthresh
self._quic_logger.log_event(
+ category="RECOVERY", event="METRIC_UPDATE", data=data
- category="recovery", event="metric_update", data=data
)
===========changed ref 3===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def on_packet_lost(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None:
del space.sent_packets[packet.packet_number]
if packet.is_ack_eliciting:
space.ack_eliciting_in_flight -= 1
if packet.in_flight:
self.bytes_in_flight -= packet.sent_bytes
if self._quic_logger is not None:
self._quic_logger.log_event(
+ category="RECOVERY",
- category="recovery",
+ event="PACKET_LOST",
- event="packet_lost",
data={
"type": self._quic_logger.packet_type(packet.packet_type),
+ "packet_number": str(packet.packet_number),
- "packet_number": packet.packet_number,
},
)
self._log_metric_update()
# trigger callbacks
for handler, args in packet.delivery_handlers:
handler(QuicDeliveryState.LOST, *args)
===========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": [
+ [str(x.start), str(x.stop - 1)] for x in ack_rangeset
- "acked_ranges": [[x.start, x.stop - 1] for x in ack_rangeset],
+ ],
+ "frame_type": "ACK",
- "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.quic.recovery/QuicPacketRecovery.__init__
|
Modified
|
aiortc~aioquic
|
97694d608d0bb1c99dc322b53c673367352ce051
|
[recovery] fix max_ack_delay handling, log ACK packets to QLOG
|
<0>:<del> self.ack_delay_exponent = 3
<2>:<add> self.max_ack_delay = 0.025
<del> self.max_ack_delay = 25 # ms
|
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def __init__(
self,
is_client_without_1rtt: bool,
send_probe: Callable[[], None],
quic_logger: Optional[QuicLogger] = None,
) -> None:
<0> self.ack_delay_exponent = 3
<1> self.is_client_without_1rtt = is_client_without_1rtt
<2> self.max_ack_delay = 25 # ms
<3> self.spaces: List[QuicPacketSpace] = []
<4>
<5> # callbacks
<6> self._quic_logger = quic_logger
<7> self._send_probe = send_probe
<8>
<9> # loss detection
<10> self._pto_count = 0
<11> self._rtt_initialized = False
<12> self._rtt_latest = 0.0
<13> self._rtt_min = math.inf
<14> self._rtt_smoothed = 0.0
<15> self._rtt_variance = 0.0
<16> self._time_of_last_sent_ack_eliciting_packet = 0.0
<17>
<18> # congestion control
<19> self.bytes_in_flight = 0
<20> self.congestion_window = K_INITIAL_WINDOW
<21> self._congestion_recovery_start_time = 0.0
<22> self._ssthresh: Optional[int] = None
<23>
|
===========unchanged ref 0===========
at: aioquic.quic.logger
QuicLogger()
at: aioquic.quic.recovery
K_INITIAL_WINDOW = 10 * K_MAX_DATAGRAM_SIZE
QuicPacketSpace()
at: aioquic.quic.recovery.QuicPacketRecovery.on_ack_received
self._rtt_latest = max(latest_rtt, 0.001)
self._rtt_latest -= ack_delay
self._rtt_min = self._rtt_latest
self._rtt_initialized = True
self._rtt_variance = latest_rtt / 2
self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs(
self._rtt_min - self._rtt_latest
)
self._rtt_smoothed = latest_rtt
self._rtt_smoothed = (
7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest
)
self._pto_count = 0
at: aioquic.quic.recovery.QuicPacketRecovery.on_loss_detection_timeout
self._pto_count += 1
at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_acked
self.bytes_in_flight -= packet.sent_bytes
self.congestion_window += (
K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window
)
self.congestion_window += packet.sent_bytes
at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_expired
self.bytes_in_flight -= packet.sent_bytes
at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_lost
self.bytes_in_flight -= packet.sent_bytes
===========unchanged ref 1===========
at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_sent
self._time_of_last_sent_ack_eliciting_packet = packet.sent_time
self.bytes_in_flight += packet.sent_bytes
at: aioquic.quic.recovery.QuicPacketRecovery.on_packets_lost
self._congestion_recovery_start_time = now
self.congestion_window = max(
int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW
)
self._ssthresh = self.congestion_window
at: math
inf: float
at: typing
Callable = _CallableType(collections.abc.Callable, 2)
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_ack_frame(self, rangeset: RangeSet, delay: float):
+ return {
+ "ack_delay": str(int(delay * 1000)), # convert to ms
+ "acked_ranges": [[str(x.start), str(x.stop - 1)] for x in rangeset],
+ "frame_type": "ACK",
+ }
+
===========changed ref 1===========
# module: aioquic.quic.packet_builder
@dataclass
class QuicSentPacket:
epoch: Epoch
in_flight: bool
is_ack_eliciting: bool
is_crypto_packet: bool
packet_number: int
packet_type: int
sent_time: Optional[float] = None
sent_bytes: int = 0
delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(
default_factory=list
)
+ quic_logger_frames: List[Dict] = field(default_factory=list)
|
aioquic.quic.recovery/QuicPacketRecovery.get_loss_detection_time
|
Modified
|
aiortc~aioquic
|
97694d608d0bb1c99dc322b53c673367352ce051
|
[recovery] fix max_ack_delay handling, log ACK packets to QLOG
|
<16>:<add> + self.max_ack_delay
<del> + self.max_ack_delay / 1000
|
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def get_loss_detection_time(self) -> float:
<0> # loss timer
<1> loss_space = self.get_earliest_loss_time()
<2> if loss_space is not None:
<3> return loss_space.loss_time
<4>
<5> # packet timer
<6> if (
<7> self.is_client_without_1rtt
<8> or sum(space.ack_eliciting_in_flight for space in self.spaces) > 0
<9> ):
<10> if not self._rtt_initialized:
<11> timeout = 2 * K_INITIAL_RTT * (2 ** self._pto_count)
<12> else:
<13> timeout = (
<14> self._rtt_smoothed
<15> + max(4 * self._rtt_variance, K_GRANULARITY)
<16> + self.max_ack_delay / 1000
<17> ) * (2 ** self._pto_count)
<18> return self._time_of_last_sent_ack_eliciting_packet + timeout
<19>
<20> return None
<21>
|
===========unchanged ref 0===========
at: aioquic.quic.recovery
K_INITIAL_RTT = 0.5 # seconds
K_GRANULARITY = 0.001 # seconds
at: aioquic.quic.recovery.QuicPacketRecovery
get_earliest_loss_time() -> Optional[QuicPacketSpace]
at: aioquic.quic.recovery.QuicPacketRecovery.__init__
self.is_client_without_1rtt = is_client_without_1rtt
self.max_ack_delay = 25 # ms
self.spaces: List[QuicPacketSpace] = []
self._pto_count = 0
self._rtt_initialized = False
self._rtt_smoothed = 0.0
self._rtt_variance = 0.0
self._time_of_last_sent_ack_eliciting_packet = 0.0
at: aioquic.quic.recovery.QuicPacketRecovery.on_ack_received
self._rtt_initialized = True
self._rtt_variance = latest_rtt / 2
self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs(
self._rtt_min - self._rtt_latest
)
self._rtt_smoothed = latest_rtt
self._rtt_smoothed = (
7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest
)
self._pto_count = 0
at: aioquic.quic.recovery.QuicPacketRecovery.on_loss_detection_timeout
self._pto_count += 1
at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_sent
self._time_of_last_sent_ack_eliciting_packet = packet.sent_time
at: aioquic.quic.recovery.QuicPacketSpace.__init__
self.ack_eliciting_in_flight = 0
===========unchanged ref 1===========
self.loss_time: Optional[float] = None
===========changed ref 0===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def __init__(
self,
is_client_without_1rtt: bool,
send_probe: Callable[[], None],
quic_logger: Optional[QuicLogger] = None,
) -> None:
- self.ack_delay_exponent = 3
self.is_client_without_1rtt = is_client_without_1rtt
+ self.max_ack_delay = 0.025
- self.max_ack_delay = 25 # ms
self.spaces: List[QuicPacketSpace] = []
# callbacks
self._quic_logger = quic_logger
self._send_probe = send_probe
# loss detection
self._pto_count = 0
self._rtt_initialized = False
self._rtt_latest = 0.0
self._rtt_min = math.inf
self._rtt_smoothed = 0.0
self._rtt_variance = 0.0
self._time_of_last_sent_ack_eliciting_packet = 0.0
# congestion control
self.bytes_in_flight = 0
self.congestion_window = K_INITIAL_WINDOW
self._congestion_recovery_start_time = 0.0
self._ssthresh: Optional[int] = None
===========changed ref 1===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_ack_frame(self, rangeset: RangeSet, delay: float):
+ return {
+ "ack_delay": str(int(delay * 1000)), # convert to ms
+ "acked_ranges": [[str(x.start), str(x.stop - 1)] for x in rangeset],
+ "frame_type": "ACK",
+ }
+
===========changed ref 2===========
# module: aioquic.quic.packet_builder
@dataclass
class QuicSentPacket:
epoch: Epoch
in_flight: bool
is_ack_eliciting: bool
is_crypto_packet: bool
packet_number: int
packet_type: int
sent_time: Optional[float] = None
sent_bytes: int = 0
delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(
default_factory=list
)
+ quic_logger_frames: List[Dict] = field(default_factory=list)
|
aioquic.quic.recovery/QuicPacketRecovery.get_probe_timeout
|
Modified
|
aiortc~aioquic
|
97694d608d0bb1c99dc322b53c673367352ce051
|
[recovery] fix max_ack_delay handling, log ACK packets to QLOG
|
<3>:<add> + self.max_ack_delay
<del> + self.max_ack_delay / 1000
|
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def get_probe_timeout(self) -> float:
<0> return (
<1> self._rtt_smoothed
<2> + max(4 * self._rtt_variance, K_GRANULARITY)
<3> + self.max_ack_delay / 1000
<4> )
<5>
|
===========unchanged ref 0===========
at: aioquic.quic.recovery
K_GRANULARITY = 0.001 # seconds
at: aioquic.quic.recovery.QuicPacketRecovery.__init__
self.max_ack_delay = 25 # ms
self._rtt_smoothed = 0.0
self._rtt_variance = 0.0
at: aioquic.quic.recovery.QuicPacketRecovery.on_ack_received
self._rtt_variance = latest_rtt / 2
self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs(
self._rtt_min - self._rtt_latest
)
self._rtt_smoothed = latest_rtt
self._rtt_smoothed = (
7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest
)
===========changed ref 0===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def get_loss_detection_time(self) -> float:
# loss timer
loss_space = self.get_earliest_loss_time()
if loss_space is not None:
return loss_space.loss_time
# packet timer
if (
self.is_client_without_1rtt
or sum(space.ack_eliciting_in_flight for space in self.spaces) > 0
):
if not self._rtt_initialized:
timeout = 2 * K_INITIAL_RTT * (2 ** self._pto_count)
else:
timeout = (
self._rtt_smoothed
+ max(4 * self._rtt_variance, K_GRANULARITY)
+ + self.max_ack_delay
- + self.max_ack_delay / 1000
) * (2 ** self._pto_count)
return self._time_of_last_sent_ack_eliciting_packet + timeout
return None
===========changed ref 1===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def __init__(
self,
is_client_without_1rtt: bool,
send_probe: Callable[[], None],
quic_logger: Optional[QuicLogger] = None,
) -> None:
- self.ack_delay_exponent = 3
self.is_client_without_1rtt = is_client_without_1rtt
+ self.max_ack_delay = 0.025
- self.max_ack_delay = 25 # ms
self.spaces: List[QuicPacketSpace] = []
# callbacks
self._quic_logger = quic_logger
self._send_probe = send_probe
# loss detection
self._pto_count = 0
self._rtt_initialized = False
self._rtt_latest = 0.0
self._rtt_min = math.inf
self._rtt_smoothed = 0.0
self._rtt_variance = 0.0
self._time_of_last_sent_ack_eliciting_packet = 0.0
# congestion control
self.bytes_in_flight = 0
self.congestion_window = K_INITIAL_WINDOW
self._congestion_recovery_start_time = 0.0
self._ssthresh: Optional[int] = None
===========changed ref 2===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_ack_frame(self, rangeset: RangeSet, delay: float):
+ return {
+ "ack_delay": str(int(delay * 1000)), # convert to ms
+ "acked_ranges": [[str(x.start), str(x.stop - 1)] for x in rangeset],
+ "frame_type": "ACK",
+ }
+
===========changed ref 3===========
# module: aioquic.quic.packet_builder
@dataclass
class QuicSentPacket:
epoch: Epoch
in_flight: bool
is_ack_eliciting: bool
is_crypto_packet: bool
packet_number: int
packet_type: int
sent_time: Optional[float] = None
sent_bytes: int = 0
delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(
default_factory=list
)
+ quic_logger_frames: List[Dict] = field(default_factory=list)
|
aioquic.quic.recovery/QuicPacketRecovery.on_ack_received
|
Modified
|
aiortc~aioquic
|
97694d608d0bb1c99dc322b53c673367352ce051
|
[recovery] fix max_ack_delay handling, log ACK packets to QLOG
|
<36>:<del> # decode ACK delay into seconds
<37>:<del> ack_delay = max(
<38>:<del> (ack_
|
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def on_ack_received(
self,
space: QuicPacketSpace,
ack_rangeset: RangeSet,
+ ack_delay: float,
- ack_delay_encoded: int,
now: float,
) -> None:
<0> """
<1> Update metrics as the result of an ACK being received.
<2> """
<3> is_ack_eliciting = False
<4> largest_acked = ack_rangeset.bounds().stop - 1
<5> largest_newly_acked = None
<6> largest_sent_time = None
<7>
<8> if largest_acked > space.largest_acked_packet:
<9> space.largest_acked_packet = largest_acked
<10>
<11> for packet_number in sorted(space.sent_packets.keys()):
<12> if packet_number > largest_acked:
<13> break
<14> if packet_number in ack_rangeset:
<15> # remove packet and update counters
<16> packet = space.sent_packets.pop(packet_number)
<17> if packet.is_ack_eliciting:
<18> is_ack_eliciting = True
<19> space.ack_eliciting_in_flight -= 1
<20> if packet.in_flight:
<21> self.on_packet_acked(packet)
<22> largest_newly_acked = packet_number
<23> largest_sent_time = packet.sent_time
<24>
<25> # trigger callbacks
<26> for handler, args in packet.delivery_handlers:
<27> handler(QuicDeliveryState.ACKED, *args)
<28>
<29> # nothing to do if there are no newly acked packets
<30> if largest_newly_acked is None:
<31> return
<32>
<33> if largest_acked == largest_newly_acked and is_ack_eliciting:
<34> latest_rtt = now - largest_sent_time
<35>
<36> # decode ACK delay into seconds
<37> ack_delay = max(
<38> (ack_</s>
|
===========below chunk 0===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def on_ack_received(
self,
space: QuicPacketSpace,
ack_rangeset: RangeSet,
+ ack_delay: float,
- ack_delay_encoded: int,
now: float,
) -> None:
# offset: 1
self.max_ack_delay / 1000,
)
# update RTT estimate, which cannot be < 1 ms
self._rtt_latest = max(latest_rtt, 0.001)
if self._rtt_latest < self._rtt_min:
self._rtt_min = self._rtt_latest
if self._rtt_latest > self._rtt_min + ack_delay:
self._rtt_latest -= ack_delay
if not self._rtt_initialized:
self._rtt_initialized = True
self._rtt_variance = latest_rtt / 2
self._rtt_smoothed = latest_rtt
else:
self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs(
self._rtt_min - self._rtt_latest
)
self._rtt_smoothed = (
7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest
)
if self._quic_logger is not None:
self._quic_logger.log_event(
category="RECOVERY",
event="METRIC_UPDATE",
data={
"latest_rtt": int(self._rtt_latest * 1000),
"min_rtt": int(self._rtt_min * 1000),
"smoothed_rtt": int(self._rtt_smoothed * 1000),
"rtt_variance": int(self._rtt_variance * 1000),
},
)
self.detect_loss(space, now=now)
self._pto_count = 0
===========unchanged ref 0===========
at: aioquic.quic.logger.QuicLogger
log_event(*, category: str, event: str, data: Dict) -> None
at: aioquic.quic.packet_builder
QuicDeliveryState()
at: aioquic.quic.packet_builder.QuicSentPacket
epoch: Epoch
in_flight: bool
is_ack_eliciting: bool
is_crypto_packet: bool
packet_number: int
packet_type: int
sent_time: Optional[float] = None
sent_bytes: int = 0
delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(
default_factory=list
)
quic_logger_frames: List[Dict] = field(default_factory=list)
at: aioquic.quic.rangeset
RangeSet(ranges: Iterable[range]=[])
at: aioquic.quic.rangeset.RangeSet
bounds() -> range
at: aioquic.quic.recovery
QuicPacketSpace()
at: aioquic.quic.recovery.QuicPacketRecovery
detect_loss(space: QuicPacketSpace, now: float) -> None
on_packet_acked(packet: QuicSentPacket) -> None
at: aioquic.quic.recovery.QuicPacketRecovery.__init__
self.ack_delay_exponent = 3
self.max_ack_delay = 25 # ms
self._quic_logger = quic_logger
self._pto_count = 0
self._rtt_initialized = False
self._rtt_latest = 0.0
self._rtt_min = math.inf
self._rtt_smoothed = 0.0
self._rtt_variance = 0.0
at: aioquic.quic.recovery.QuicPacketRecovery.on_loss_detection_timeout
self._pto_count += 1
===========unchanged ref 1===========
at: aioquic.quic.recovery.QuicPacketSpace.__init__
self.ack_eliciting_in_flight = 0
self.largest_acked_packet = 0
self.sent_packets: Dict[int, QuicSentPacket] = {}
at: typing.MutableMapping
pop(key: _KT) -> _VT
pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T]
===========changed ref 0===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def get_probe_timeout(self) -> float:
return (
self._rtt_smoothed
+ max(4 * self._rtt_variance, K_GRANULARITY)
+ + self.max_ack_delay
- + self.max_ack_delay / 1000
)
===========changed ref 1===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def get_loss_detection_time(self) -> float:
# loss timer
loss_space = self.get_earliest_loss_time()
if loss_space is not None:
return loss_space.loss_time
# packet timer
if (
self.is_client_without_1rtt
or sum(space.ack_eliciting_in_flight for space in self.spaces) > 0
):
if not self._rtt_initialized:
timeout = 2 * K_INITIAL_RTT * (2 ** self._pto_count)
else:
timeout = (
self._rtt_smoothed
+ max(4 * self._rtt_variance, K_GRANULARITY)
+ + self.max_ack_delay
- + self.max_ack_delay / 1000
) * (2 ** self._pto_count)
return self._time_of_last_sent_ack_eliciting_packet + timeout
return None
===========changed ref 2===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def __init__(
self,
is_client_without_1rtt: bool,
send_probe: Callable[[], None],
quic_logger: Optional[QuicLogger] = None,
) -> None:
- self.ack_delay_exponent = 3
self.is_client_without_1rtt = is_client_without_1rtt
+ self.max_ack_delay = 0.025
- self.max_ack_delay = 25 # ms
self.spaces: List[QuicPacketSpace] = []
# callbacks
self._quic_logger = quic_logger
self._send_probe = send_probe
# loss detection
self._pto_count = 0
self._rtt_initialized = False
self._rtt_latest = 0.0
self._rtt_min = math.inf
self._rtt_smoothed = 0.0
self._rtt_variance = 0.0
self._time_of_last_sent_ack_eliciting_packet = 0.0
# congestion control
self.bytes_in_flight = 0
self.congestion_window = K_INITIAL_WINDOW
self._congestion_recovery_start_time = 0.0
self._ssthresh: Optional[int] = None
===========changed ref 3===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_ack_frame(self, rangeset: RangeSet, delay: float):
+ return {
+ "ack_delay": str(int(delay * 1000)), # convert to ms
+ "acked_ranges": [[str(x.start), str(x.stop - 1)] for x in rangeset],
+ "frame_type": "ACK",
+ }
+
|
aioquic.quic.connection/QuicConnection.__init__
|
Modified
|
aiortc~aioquic
|
97694d608d0bb1c99dc322b53c673367352ce051
|
[recovery] fix max_ack_delay handling, log ACK packets to QLOG
|
# 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_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
# frame handlers
self.__frame</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> = [
(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._handle_max_streams_bidi_frame,</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>S("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.quic.connection/QuicConnection.datagrams_to_send
|
Modified
|
aiortc~aioquic
|
97694d608d0bb1c99dc322b53c673367352ce051
|
[recovery] fix max_ack_delay handling, log ACK packets to QLOG
|
# module: aioquic.quic.connection
class QuicConnection:
def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]:
<0> """
<1> Return a list of `(data, addr)` tuples of datagrams which need to be
<2> sent, and the network address to which they need to be sent.
<3>
<4> :param now: The current time.
<5> """
<6> network_path = self._network_paths[0]
<7>
<8> if self._state in END_STATES:
<9> return []
<10>
<11> # build datagrams
<12> builder = QuicPacketBuilder(
<13> host_cid=self.host_cid,
<14> packet_number=self._packet_number,
<15> pad_first_datagram=(
<16> self._is_client and self._state == QuicConnectionState.FIRSTFLIGHT
<17> ),
<18> peer_cid=self._peer_cid,
<19> peer_token=self._peer_token,
<20> spin_bit=self._spin_bit,
<21> version=self._version,
<22> )
<23> if self._close_pending:
<24> for epoch, packet_type in (
<25> (tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT),
<26> (tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE),
<27> (tls.Epoch.INITIAL, PACKET_TYPE_INITIAL),
<28> ):
<29> crypto = self._cryptos[epoch]
<30> if crypto.send.is_valid():
<31> builder.start_packet(packet_type, crypto)
<32> write_close_frame(
<33> builder=builder,
<34> error_code=self._close_event.error_code,
<35> frame_type=self._close_event.frame_type,
<36> reason_phrase=self._close_event.reason_phrase,
<37> )
<38> builder.end_packet()
<39> self._close_pending = False
<40> break
<41> self._close_begin(is_initiator=True, now</s>
|
===========below chunk 0===========
# module: aioquic.quic.connection
class QuicConnection:
def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]:
# offset: 1
else:
# congestion control
builder.max_flight_bytes = (
self._loss.congestion_window - self._loss.bytes_in_flight
)
if self._probe_pending and builder.max_flight_bytes < PACKET_MAX_SIZE:
builder.max_flight_bytes = PACKET_MAX_SIZE
# limit data on un-validated network paths
if not network_path.is_validated:
builder.max_total_bytes = (
network_path.bytes_received * 3 - network_path.bytes_sent
)
try:
if not self._handshake_confirmed:
for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]:
self._write_handshake(builder, epoch)
self._write_application(builder, network_path, now)
except QuicPacketBuilderStop:
pass
datagrams, packets = builder.flush()
if datagrams:
self._packet_number = builder.packet_number
# register packets
sent_handshake = False
for packet in packets:
packet.sent_time = now
self._loss.on_packet_sent(
packet=packet, space=self._spaces[packet.epoch]
)
if packet.epoch == tls.Epoch.HANDSHAKE:
sent_handshake = True
# log packet
if self._quic_logger is not None:
self._quic_logger.log_event(
category="TRANSPORT",
event="PACKET_SENT",
data={
"packet_type": self._quic_logger.packet_type(
packet.packet_type
),
"header": {
"packet_number": str(packet.packet_number),
"packet_size": packet.sent_bytes,
"scid":</s>
===========below chunk 1===========
# module: aioquic.quic.connection
class QuicConnection:
def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]:
# offset: 2
<s>_number": str(packet.packet_number),
"packet_size": packet.sent_bytes,
"scid": dump_cid(self.host_cid)
if is_long_header(packet.packet_type)
else "",
"dcid": dump_cid(self._peer_cid),
},
"frames": [],
},
)
# check if we can discard initial keys
if sent_handshake and self._is_client:
self._discard_epoch(tls.Epoch.INITIAL)
# return datagrams to send and the destination network address
ret = []
for datagram in datagrams:
byte_length = len(datagram)
network_path.bytes_sent += byte_length
ret.append((datagram, network_path.addr))
if self._quic_logger is not None:
self._quic_logger.log_event(
category="TRANSPORT",
event="DATAGRAM_SENT",
data={"byte_length": byte_length, "count": 1},
)
return ret
===========unchanged ref 0===========
at: aioquic.quic.connection
NetworkAddress = Any
dump_cid(cid: bytes) -> str
write_close_frame(builder: QuicPacketBuilder, error_code: int, frame_type: Optional[int], reason_phrase: str) -> None
QuicConnectionState()
END_STATES = frozenset(
[
QuicConnectionState.CLOSING,
QuicConnectionState.DRAINING,
QuicConnectionState.TERMINATED,
]
)
at: aioquic.quic.connection.QuicConnection
_close_begin(is_initiator: bool, now: float) -> None
_connect(now: float) -> None
_write_application(builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float) -> None
_write_handshake(builder: QuicPacketBuilder, epoch: tls.Epoch) -> None
at: aioquic.quic.connection.QuicConnection.__init__
self._is_client = configuration.is_client
self._close_event: Optional[events.ConnectionTerminated] = None
self._cryptos: Dict[tls.Epoch, CryptoPair] = {}
self._handshake_confirmed = False
self.host_cid = self._host_cids[0].cid
self._loss = QuicPacketRecovery(
is_client_without_1rtt=self._is_client,
quic_logger=self._quic_logger,
send_probe=self._send_probe,
)
self._network_paths: List[QuicNetworkPath] = []
self._packet_number = 0
self._peer_cid = os.urandom(8)
self._peer_token = b""
self._spin_bit = False
self._state = QuicConnectionState.FIRSTFLIGHT
self._version: Optional[int] = None
self._close_pending = False
self._probe_pending = False
===========unchanged ref 1===========
at: aioquic.quic.connection.QuicConnection._handle_ack_frame
self._handshake_confirmed = True
at: aioquic.quic.connection.QuicConnection._handle_connection_close_frame
self._close_event = events.ConnectionTerminated(
error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase
)
at: aioquic.quic.connection.QuicConnection._initialize
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
self._packet_number = 0
at: aioquic.quic.connection.QuicConnection._send_probe
self._probe_pending = True
at: aioquic.quic.connection.QuicConnection._set_state
self._state = state
at: aioquic.quic.connection.QuicConnection._write_application
self._probe_pending = False
at: aioquic.quic.connection.QuicConnection._write_handshake
self._probe_pending = False
at: aioquic.quic.connection.QuicConnection.change_connection_id
self._peer_cid = connection_id.cid
at: aioquic.quic.connection.QuicConnection.close
self._close_event = events.ConnectionTerminated(
error_code=error_code,
frame_type=frame_type,
reason_phrase=reason_phrase,
)
self._close_pending = True
at: aioquic.quic.connection.QuicConnection.connect
self._network_paths = [QuicNetworkPath(addr, is_validated=True)]
self._version = self._configuration.supported_versions[0]
|
|
aioquic.quic.connection/QuicConnection._handle_ack_frame
|
Modified
|
aiortc~aioquic
|
97694d608d0bb1c99dc322b53c673367352ce051
|
[recovery] fix max_ack_delay handling, log ACK packets to QLOG
|
<8>:<add> ack_delay = (ack_delay_encoded << self._remote_ack_delay_exponent) / 1000000
<10>:<add> if self._quic_logger is not None:
<del> if context.quic_logger_frames is not None:
<12>:<del> {
<13>:<del> "ack_delay": str(
<14>:<del> (ack_delay_encoded << self._loss.ack_delay_exponent) // 1000
<15>:<del> ),
<16>:<del> "acked_ranges": [
<17>:<del> [str(x.start), str(x.stop - 1)] for x in ack_rangeset
<18>:<del> ],
<19>:<del> "frame_type": "ACK",
<20>:<del> }
<21>:<add> self._quic_logger.encode_ack_frame(ack_rangeset, ack_delay)
<26>:<add> ack_delay=ack_delay,
<del> ack_delay_encoded=ack_delay_encoded,
|
# 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> # log frame
<10> if context.quic_logger_frames is not None:
<11> context.quic_logger_frames.append(
<12> {
<13> "ack_delay": str(
<14> (ack_delay_encoded << self._loss.ack_delay_exponent) // 1000
<15> ),
<16> "acked_ranges": [
<17> [str(x.start), str(x.stop - 1)] for x in ack_rangeset
<18> ],
<19> "frame_type": "ACK",
<20> }
<21> )
<22>
<23> self._loss.on_ack_received(
<24> space=self._spaces[context.epoch],
<25> ack_rangeset=ack_rangeset,
<26> ack_delay_encoded=ack_delay_encoded,
<27> now=context.time,
<28> )
<29>
<30> # check if we can discard handshake keys
<31> if (
<32> not self._handshake_confirmed
<33> and self._handshake_complete
<34> and context.epoch == tls.Epoch.ONE_RTT
<35> ):
<36> self._discard_epoch(tls.Epoch.HANDSHAKE)
<37> self._handshake_confirmed = True
<38>
|
===========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, quic_logger_frames: Optional[List[Any]], time: float)
at: aioquic.quic.connection.QuicConnection
_discard_epoch(epoch: tls.Epoch) -> None
at: aioquic.quic.connection.QuicConnection.__init__
self._quic_logger = configuration.quic_logger
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._packet_number = 0
self._remote_ack_delay_exponent = 3
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.QuicConnection._parse_transport_parameters
self._remote_ack_delay_exponent = self._remote_ack_delay_exponent
at: aioquic.quic.connection.QuicConnection.datagrams_to_send
self._packet_number = builder.packet_number
at: aioquic.quic.connection.QuicReceiveContext
epoch: tls.Epoch
===========unchanged ref 1===========
host_cid: bytes
network_path: QuicNetworkPath
quic_logger_frames: Optional[List[Any]]
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]
at: aioquic.tls
Epoch()
===========changed ref 0===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def get_probe_timeout(self) -> float:
return (
self._rtt_smoothed
+ max(4 * self._rtt_variance, K_GRANULARITY)
+ + self.max_ack_delay
- + self.max_ack_delay / 1000
)
===========changed ref 1===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_ack_frame(self, rangeset: RangeSet, delay: float):
+ return {
+ "ack_delay": str(int(delay * 1000)), # convert to ms
+ "acked_ranges": [[str(x.start), str(x.stop - 1)] for x in rangeset],
+ "frame_type": "ACK",
+ }
+
===========changed ref 2===========
# module: aioquic.quic.packet_builder
@dataclass
class QuicSentPacket:
epoch: Epoch
in_flight: bool
is_ack_eliciting: bool
is_crypto_packet: bool
packet_number: int
packet_type: int
sent_time: Optional[float] = None
sent_bytes: int = 0
delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(
default_factory=list
)
+ quic_logger_frames: List[Dict] = field(default_factory=list)
===========changed ref 3===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def get_loss_detection_time(self) -> float:
# loss timer
loss_space = self.get_earliest_loss_time()
if loss_space is not None:
return loss_space.loss_time
# packet timer
if (
self.is_client_without_1rtt
or sum(space.ack_eliciting_in_flight for space in self.spaces) > 0
):
if not self._rtt_initialized:
timeout = 2 * K_INITIAL_RTT * (2 ** self._pto_count)
else:
timeout = (
self._rtt_smoothed
+ max(4 * self._rtt_variance, K_GRANULARITY)
+ + self.max_ack_delay
- + self.max_ack_delay / 1000
) * (2 ** self._pto_count)
return self._time_of_last_sent_ack_eliciting_packet + timeout
return None
===========changed ref 4===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def __init__(
self,
is_client_without_1rtt: bool,
send_probe: Callable[[], None],
quic_logger: Optional[QuicLogger] = None,
) -> None:
- self.ack_delay_exponent = 3
self.is_client_without_1rtt = is_client_without_1rtt
+ self.max_ack_delay = 0.025
- self.max_ack_delay = 25 # ms
self.spaces: List[QuicPacketSpace] = []
# callbacks
self._quic_logger = quic_logger
self._send_probe = send_probe
# loss detection
self._pto_count = 0
self._rtt_initialized = False
self._rtt_latest = 0.0
self._rtt_min = math.inf
self._rtt_smoothed = 0.0
self._rtt_variance = 0.0
self._time_of_last_sent_ack_eliciting_packet = 0.0
# congestion control
self.bytes_in_flight = 0
self.congestion_window = K_INITIAL_WINDOW
self._congestion_recovery_start_time = 0.0
self._ssthresh: Optional[int] = None
|
aioquic.quic.connection/QuicConnection._parse_transport_parameters
|
Modified
|
aiortc~aioquic
|
97694d608d0bb1c99dc322b53c673367352ce051
|
[recovery] fix max_ack_delay handling, log ACK packets to QLOG
|
<18>:<add> if quic_transport_parameters.ack_delay_exponent is not None:
<add> self._remote_ack_delay_exponent = self._remote_ack_delay_exponent
<24>:<del> for param in ["ack_delay_exponent", "max_ack_delay"]:
<25>:<del> value = getattr(quic_transport_parameters, param)
<26>:<del> if value is not None:
<27>:<del> setattr(self._loss, param, value)
<28>:<add> if quic_transport_parameters.max_ack_delay is not None:
<add> self._loss.max_ack_delay = quic_transport_parameters.max_ack_delay / 1000.0
|
# module: aioquic.quic.connection
class QuicConnection:
def _parse_transport_parameters(
self, data: bytes, from_session_ticket: bool = False
) -> None:
<0> quic_transport_parameters = pull_quic_transport_parameters(Buffer(data=data))
<1>
<2> # validate remote parameters
<3> if (
<4> self._is_client
<5> and not from_session_ticket
<6> and (
<7> quic_transport_parameters.original_connection_id
<8> != self._original_connection_id
<9> )
<10> ):
<11> raise QuicConnectionError(
<12> error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR,
<13> frame_type=QuicFrameType.CRYPTO,
<14> reason_phrase="original_connection_id does not match",
<15> )
<16>
<17> # store remote parameters
<18> if quic_transport_parameters.active_connection_id_limit is not None:
<19> self._remote_active_connection_id_limit = (
<20> quic_transport_parameters.active_connection_id_limit
<21> )
<22> if quic_transport_parameters.idle_timeout is not None:
<23> self._remote_idle_timeout = quic_transport_parameters.idle_timeout / 1000.0
<24> for param in ["ack_delay_exponent", "max_ack_delay"]:
<25> value = getattr(quic_transport_parameters, param)
<26> if value is not None:
<27> setattr(self._loss, param, value)
<28> for param in [
<29> "max_data",
<30> "max_stream_data_bidi_local",
<31> "max_stream_data_bidi_remote",
<32> "max_stream_data_uni",
<33> "max_streams_bidi",
<34> "max_streams_uni",
<35> ]:
<36> value = getattr(quic_transport_parameters, "initial_" + param)
<37> if value is not None:
<38> setattr(self, "_remote_" + param, value)
<39>
|
===========unchanged ref 0===========
at: aioquic.quic.connection
QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str)
at: aioquic.quic.connection.QuicConnection.__init__
self._is_client = configuration.is_client
self._local_ack_delay_exponent = 3
self._local_active_connection_id_limit = 8
self._loss = QuicPacketRecovery(
is_client_without_1rtt=self._is_client,
quic_logger=self._quic_logger,
send_probe=self._send_probe,
)
self._original_connection_id = original_connection_id
self._remote_ack_delay_exponent = 3
self._remote_active_connection_id_limit = 0
self._remote_idle_timeout = 0.0 # seconds
at: aioquic.quic.connection.QuicConnection._parse_transport_parameters
quic_transport_parameters = pull_quic_transport_parameters(Buffer(data=data))
at: aioquic.quic.connection.QuicConnection.receive_datagram
self._original_connection_id = self._peer_cid
at: aioquic.quic.packet
QuicErrorCode(x: Union[str, bytes, bytearray], base: int)
QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
===========unchanged ref 1===========
QuicTransportParameters(initial_version: Optional[QuicProtocolVersion]=None, negotiated_version: Optional[QuicProtocolVersion]=None, supported_versions: List[QuicProtocolVersion]=field(default_factory=list), original_connection_id: Optional[bytes]=None, idle_timeout: Optional[int]=None, stateless_reset_token: Optional[bytes]=None, max_packet_size: Optional[int]=None, initial_max_data: Optional[int]=None, initial_max_stream_data_bidi_local: Optional[int]=None, initial_max_stream_data_bidi_remote: Optional[int]=None, initial_max_stream_data_uni: Optional[int]=None, initial_max_streams_bidi: Optional[int]=None, initial_max_streams_uni: Optional[int]=None, ack_delay_exponent: Optional[int]=None, max_ack_delay: Optional[int]=None, disable_migration: Optional[bool]=False, preferred_address: Optional[bytes]=None, active_connection_id_limit: Optional[int]=None)
QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
QuicFrameType(x: Union[str, bytes, bytearray], base: int)
at: aioquic.quic.packet.QuicTransportParameters
initial_version: Optional[QuicProtocolVersion] = None
negotiated_version: Optional[QuicProtocolVersion] = None
supported_versions: List[QuicProtocolVersion] = field(default_factory=list)
original_connection_id: Optional[bytes] = None
idle_timeout: Optional[int] = None
stateless_reset_token: Optional[bytes] = None
max_packet_size: Optional[int] = None
initial_max_data: Optional[int] = None
initial_max_stream_data_bidi_local: Optional[int] = None
initial_max_stream_data_bidi_remote: Optional[int] = None
===========unchanged ref 2===========
initial_max_stream_data_uni: Optional[int] = None
initial_max_streams_bidi: Optional[int] = None
initial_max_streams_uni: Optional[int] = None
ack_delay_exponent: Optional[int] = None
max_ack_delay: Optional[int] = None
disable_migration: Optional[bool] = False
preferred_address: Optional[bytes] = None
active_connection_id_limit: Optional[int] = None
===========changed ref 0===========
# 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()
+ ack_delay = (ack_delay_encoded << self._remote_ack_delay_exponent) / 1000000
# log frame
+ if self._quic_logger is not None:
- 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": [
- [str(x.start), str(x.stop - 1)] for x in ack_rangeset
- ],
- "frame_type": "ACK",
- }
+ self._quic_logger.encode_ack_frame(ack_rangeset, ack_delay)
)
self._loss.on_ack_received(
space=self._spaces[context.epoch],
ack_rangeset=ack_rangeset,
+ ack_delay=ack_delay,
- 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 1===========
# module: aioquic.quic.recovery
class QuicPacketRecovery:
def get_probe_timeout(self) -> float:
return (
self._rtt_smoothed
+ max(4 * self._rtt_variance, K_GRANULARITY)
+ + self.max_ack_delay
- + self.max_ack_delay / 1000
)
===========changed ref 2===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_ack_frame(self, rangeset: RangeSet, delay: float):
+ return {
+ "ack_delay": str(int(delay * 1000)), # convert to ms
+ "acked_ranges": [[str(x.start), str(x.stop - 1)] for x in rangeset],
+ "frame_type": "ACK",
+ }
+
===========changed ref 3===========
# module: aioquic.quic.packet_builder
@dataclass
class QuicSentPacket:
epoch: Epoch
in_flight: bool
is_ack_eliciting: bool
is_crypto_packet: bool
packet_number: int
packet_type: int
sent_time: Optional[float] = None
sent_bytes: int = 0
delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(
default_factory=list
)
+ quic_logger_frames: List[Dict] = field(default_factory=list)
|
aioquic.quic.connection/QuicConnection._serialize_transport_parameters
|
Modified
|
aiortc~aioquic
|
97694d608d0bb1c99dc322b53c673367352ce051
|
[recovery] fix max_ack_delay handling, log ACK packets to QLOG
|
<1>:<add> ack_delay_exponent=self._local_ack_delay_exponent,
<9>:<add> max_ack_delay=25,
<del> ack_delay_exponent=10,
|
# module: aioquic.quic.connection
class QuicConnection:
def _serialize_transport_parameters(self) -> bytes:
<0> quic_transport_parameters = QuicTransportParameters(
<1> active_connection_id_limit=self._local_active_connection_id_limit,
<2> idle_timeout=int(self._configuration.idle_timeout * 1000),
<3> initial_max_data=self._local_max_data,
<4> initial_max_stream_data_bidi_local=self._local_max_stream_data_bidi_local,
<5> initial_max_stream_data_bidi_remote=self._local_max_stream_data_bidi_remote,
<6> initial_max_stream_data_uni=self._local_max_stream_data_uni,
<7> initial_max_streams_bidi=self._local_max_streams_bidi,
<8> initial_max_streams_uni=self._local_max_streams_uni,
<9> ack_delay_exponent=10,
<10> )
<11> if not self._is_client:
<12> quic_transport_parameters.original_connection_id = (
<13> self._original_connection_id
<14> )
<15>
<16> buf = Buffer(capacity=512)
<17> push_quic_transport_parameters(buf, quic_transport_parameters)
<18> return buf.data
<19>
|
===========unchanged ref 0===========
at: aioquic._buffer
Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)
at: aioquic.quic.connection
QuicConnectionState()
at: aioquic.quic.connection.QuicConnection.__init__
self._is_client = configuration.is_client
self._local_max_data = MAX_DATA_WINDOW
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._original_connection_id = original_connection_id
self._state = QuicConnectionState.FIRSTFLIGHT
===========unchanged ref 1===========
at: aioquic.quic.connection.QuicConnection._serialize_transport_parameters
quic_transport_parameters = QuicTransportParameters(
ack_delay_exponent=self._local_ack_delay_exponent,
active_connection_id_limit=self._local_active_connection_id_limit,
idle_timeout=int(self._configuration.idle_timeout * 1000),
initial_max_data=self._local_max_data,
initial_max_stream_data_bidi_local=self._local_max_stream_data_bidi_local,
initial_max_stream_data_bidi_remote=self._local_max_stream_data_bidi_remote,
initial_max_stream_data_uni=self._local_max_stream_data_uni,
initial_max_streams_bidi=self._local_max_streams_bidi,
initial_max_streams_uni=self._local_max_streams_uni,
max_ack_delay=25,
)
at: aioquic.quic.connection.QuicConnection._write_connection_limits
self._local_max_data *= 2
at: aioquic.quic.connection.QuicConnection.receive_datagram
self._original_connection_id = self._peer_cid
at: aioquic.quic.packet
push_quic_transport_parameters(buf: Buffer, params: QuicTransportParameters) -> None
at: aioquic.quic.packet.QuicTransportParameters
original_connection_id: Optional[bytes] = None
===========changed ref 0===========
# module: aioquic.quic.connection
class QuicConnection:
def _parse_transport_parameters(
self, data: bytes, from_session_ticket: bool = False
) -> None:
quic_transport_parameters = pull_quic_transport_parameters(Buffer(data=data))
# validate remote parameters
if (
self._is_client
and not from_session_ticket
and (
quic_transport_parameters.original_connection_id
!= self._original_connection_id
)
):
raise QuicConnectionError(
error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR,
frame_type=QuicFrameType.CRYPTO,
reason_phrase="original_connection_id does not match",
)
# store remote parameters
+ if quic_transport_parameters.ack_delay_exponent is not None:
+ self._remote_ack_delay_exponent = self._remote_ack_delay_exponent
if quic_transport_parameters.active_connection_id_limit is not None:
self._remote_active_connection_id_limit = (
quic_transport_parameters.active_connection_id_limit
)
if quic_transport_parameters.idle_timeout is not None:
self._remote_idle_timeout = quic_transport_parameters.idle_timeout / 1000.0
- for param in ["ack_delay_exponent", "max_ack_delay"]:
- value = getattr(quic_transport_parameters, param)
- if value is not None:
- setattr(self._loss, param, value)
+ if quic_transport_parameters.max_ack_delay is not None:
+ self._loss.max_ack_delay = quic_transport_parameters.max_ack_delay / 1000.0
for param in [
"max_data",
"max_stream_data_bidi_local",
"max_stream_data_bidi_remote",
"max_stream_data_uni",
"max_streams_bidi",
"</s>
===========changed ref 1===========
# module: aioquic.quic.connection
class QuicConnection:
def _parse_transport_parameters(
self, data: bytes, from_session_ticket: bool = False
) -> None:
# offset: 1
<s>bidi_remote",
"max_stream_data_uni",
"max_streams_bidi",
"max_streams_uni",
]:
value = getattr(quic_transport_parameters, "initial_" + param)
if value is not None:
setattr(self, "_remote_" + param, value)
===========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()
+ ack_delay = (ack_delay_encoded << self._remote_ack_delay_exponent) / 1000000
# log frame
+ if self._quic_logger is not None:
- 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": [
- [str(x.start), str(x.stop - 1)] for x in ack_rangeset
- ],
- "frame_type": "ACK",
- }
+ self._quic_logger.encode_ack_frame(ack_rangeset, ack_delay)
)
self._loss.on_ack_received(
space=self._spaces[context.epoch],
ack_rangeset=ack_rangeset,
+ ack_delay=ack_delay,
- 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.recovery
class QuicPacketRecovery:
def get_probe_timeout(self) -> float:
return (
self._rtt_smoothed
+ max(4 * self._rtt_variance, K_GRANULARITY)
+ + self.max_ack_delay
- + self.max_ack_delay / 1000
)
===========changed ref 4===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_ack_frame(self, rangeset: RangeSet, delay: float):
+ return {
+ "ack_delay": str(int(delay * 1000)), # convert to ms
+ "acked_ranges": [[str(x.start), str(x.stop - 1)] for x in rangeset],
+ "frame_type": "ACK",
+ }
+
|
tests.test_connection/QuicConnectionTest.test_connect_with_loss_1
|
Modified
|
aiortc~aioquic
|
97694d608d0bb1c99dc322b53c673367352ce051
|
[recovery] fix max_ack_delay handling, log ACK packets to QLOG
|
<37>:<add> self.assertEqual(datagram_sizes(items), [1280, 1084])
<del> self.assertEqual(datagram_sizes(items), [1280, 1079])
|
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_connect_with_loss_1(self):
<0> """
<1> Check connection is established even in the client's INITIAL is lost.
<2> """
<3>
<4> def datagram_sizes(items):
<5> return [len(x[0]) for x in items]
<6>
<7> client = QuicConnection(configuration=QuicConfiguration(is_client=True))
<8> client._ack_delay = 0
<9>
<10> server = QuicConnection(
<11> configuration=QuicConfiguration(
<12> is_client=False,
<13> certificate=SERVER_CERTIFICATE,
<14> private_key=SERVER_PRIVATE_KEY,
<15> )
<16> )
<17> server._ack_delay = 0
<18>
<19> # client sends INITIAL
<20> now = 0.0
<21> client.connect(SERVER_ADDR, now=now)
<22> items = client.datagrams_to_send(now=now)
<23> self.assertEqual(datagram_sizes(items), [1280])
<24> self.assertEqual(client.get_timer(), 1.0)
<25>
<26> # INITIAL is lost
<27> now = 1.0
<28> client.handle_timer(now=now)
<29> items = client.datagrams_to_send(now=now)
<30> self.assertEqual(datagram_sizes(items), [1280])
<31> self.assertEqual(client.get_timer(), 3.0)
<32>
<33> # server receives INITIAL, sends INITIAL + HANDSHAKE
<34> now = 1.1
<35> server.receive_datagram(items[0][0], CLIENT_ADDR, now=now)
<36> items = server.datagrams_to_send(now=now)
<37> self.assertEqual(datagram_sizes(items), [1280, 1079])
<38> self.assertEqual(server.get_timer(), 2.1)
<39> self.assertEqual(len(server._loss.spaces[0].sent_packets), 1)
<40> self.assertEqual(len(server._loss.spaces[1</s>
|
===========below chunk 0===========
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_connect_with_loss_1(self):
# offset: 1
# handshake continues normally
now = 1.2
client.receive_datagram(items[0][0], SERVER_ADDR, now=now)
client.receive_datagram(items[1][0], SERVER_ADDR, now=now)
items = client.datagrams_to_send(now=now)
self.assertEqual(datagram_sizes(items), [1280, 223])
self.assertAlmostEqual(client.get_timer(), 1.825)
now = 1.3
server.receive_datagram(items[0][0], CLIENT_ADDR, now=now)
server.receive_datagram(items[1][0], CLIENT_ADDR, now=now)
items = server.datagrams_to_send(now=now)
self.assertEqual(datagram_sizes(items), [276])
self.assertAlmostEqual(server.get_timer(), 1.825)
self.assertEqual(len(server._loss.spaces[0].sent_packets), 0)
self.assertEqual(len(server._loss.spaces[1].sent_packets), 1)
now = 1.4
client.receive_datagram(items[0][0], SERVER_ADDR, now=now)
items = client.datagrams_to_send(now=now)
self.assertEqual(datagram_sizes(items), [32])
self.assertAlmostEqual(client.get_timer(), 61.4) # idle timeout
self.assertEqual(type(client.next_event()), events.ProtocolNegotiated)
self.assertEqual(type(client.next_event()), events.HandshakeCompleted)
now = 1.5
server.receive_datagram(items[0][0], CLIENT_ADDR, now=now)
items = server.datagrams_to_send(now=now)
self.assertEqual(datagram_sizes(items), [])
</s>
===========below chunk 1===========
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_connect_with_loss_1(self):
# offset: 2
<s>.datagrams_to_send(now=now)
self.assertEqual(datagram_sizes(items), [])
self.assertAlmostEqual(server.get_timer(), 61.5) # idle timeout
self.assertEqual(type(server.next_event()), events.ProtocolNegotiated)
self.assertEqual(type(server.next_event()), events.HandshakeCompleted)
===========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[int]=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[int] = 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) -> None
datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]]
get_timer() -> Optional[float]
handle_timer(now: float) -> None
receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None
===========unchanged ref 1===========
at: aioquic.quic.connection.QuicConnection.__init__
self._ack_delay = K_GRANULARITY
self._loss = QuicPacketRecovery(
is_client_without_1rtt=self._is_client,
quic_logger=self._quic_logger,
send_probe=self._send_probe,
)
at: aioquic.quic.recovery.QuicPacketRecovery.__init__
self.spaces: List[QuicPacketSpace] = []
at: aioquic.quic.recovery.QuicPacketSpace.__init__
self.sent_packets: Dict[int, QuicSentPacket] = {}
at: tests.test_connection
CLIENT_ADDR = ("1.2.3.4", 1234)
SERVER_ADDR = ("2.3.4.5", 4433)
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: unittest.case.TestCase
failureException: Type[BaseException]
longMessage: bool
maxDiff: Optional[int]
_testMethodName: str
_testMethodDoc: str
assertEqual(first: Any, second: Any, msg: Any=...) -> None
assertAlmostEqual(first: float, second: float, places: Optional[int]=..., msg: Any=..., delta: Optional[float]=...) -> None
assertAlmostEqual(first: datetime.datetime, second: datetime.datetime, places: Optional[int]=..., msg: Any=..., delta: Optional[datetime.timedelta]=...) -> None
|
tests.test_connection/QuicConnectionTest.test_connect_with_loss_2
|
Modified
|
aiortc~aioquic
|
97694d608d0bb1c99dc322b53c673367352ce051
|
[recovery] fix max_ack_delay handling, log ACK packets to QLOG
|
<26>:<add> self.assertEqual(datagram_sizes(items), [1280, 1084])
<del> self.assertEqual(datagram_sizes(items), [1280, 1079])
|
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_connect_with_loss_2(self):
<0> def datagram_sizes(items):
<1> return [len(x[0]) for x in items]
<2>
<3> client = QuicConnection(configuration=QuicConfiguration(is_client=True))
<4> client._ack_delay = 0
<5>
<6> server = QuicConnection(
<7> configuration=QuicConfiguration(
<8> is_client=False,
<9> certificate=SERVER_CERTIFICATE,
<10> private_key=SERVER_PRIVATE_KEY,
<11> )
<12> )
<13> server._ack_delay = 0
<14>
<15> # client sends INITIAL
<16> now = 0.0
<17> client.connect(SERVER_ADDR, now=now)
<18> items = client.datagrams_to_send(now=now)
<19> self.assertEqual(datagram_sizes(items), [1280])
<20> self.assertEqual(client.get_timer(), 1.0)
<21>
<22> # server receives INITIAL, sends INITIAL + HANDSHAKE but second datagram is lost
<23> now = 0.1
<24> server.receive_datagram(items[0][0], CLIENT_ADDR, now=now)
<25> items = server.datagrams_to_send(now=now)
<26> self.assertEqual(datagram_sizes(items), [1280, 1079])
<27> self.assertEqual(server.get_timer(), 1.1)
<28> self.assertEqual(len(server._loss.spaces[0].sent_packets), 1)
<29> self.assertEqual(len(server._loss.spaces[1].sent_packets), 2)
<30>
<31> # client only receives first datagram and sends ACKS
<32> now = 0.2
<33> client.receive_datagram(items[0][0], SERVER_ADDR, now=now)
<34> items = client.datagrams_to_send(now=now)
<35> self.assertEqual(datagram_sizes(items), [97])
<36> self.assertAlmostEqual(client</s>
|
===========below chunk 0===========
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_connect_with_loss_2(self):
# offset: 1
# client PTO - padded HANDSHAKE
now = client.get_timer() # ~0.625
client.handle_timer(now=now)
items = client.datagrams_to_send(now=now)
self.assertEqual(datagram_sizes(items), [1280])
self.assertAlmostEqual(client.get_timer(), 1.25)
# server receives padding, discards INITIAL
now = 0.725
server.receive_datagram(items[0][0], CLIENT_ADDR, now=now)
items = server.datagrams_to_send(now=now)
self.assertEqual(datagram_sizes(items), [])
self.assertAlmostEqual(server.get_timer(), 1.1)
self.assertEqual(len(server._loss.spaces[0].sent_packets), 0)
self.assertEqual(len(server._loss.spaces[1].sent_packets), 2)
# ACKs are lost, server retransmits HANDSHAKE
now = server.get_timer()
server.handle_timer(now=now)
items = server.datagrams_to_send(now=now)
self.assertEqual(datagram_sizes(items), [1280, 900])
self.assertAlmostEqual(server.get_timer(), 3.1)
self.assertEqual(len(server._loss.spaces[0].sent_packets), 0)
self.assertEqual(len(server._loss.spaces[1].sent_packets), 2)
# handshake continues normally
now = 1.2
client.receive_datagram(items[0][0], SERVER_ADDR, now=now)
client.receive_datagram(items[1][0], SERVER_ADDR, now=now)
items = client.datagrams_to_send(now=now)
self.assertEqual(datagram_sizes(items</s>
===========below chunk 1===========
# module: tests.test_connection
class QuicConnectionTest(TestCase):
def test_connect_with_loss_2(self):
# offset: 2
<s> items = client.datagrams_to_send(now=now)
self.assertEqual(datagram_sizes(items), [334])
self.assertAlmostEqual(client.get_timer(), 2.45)
self.assertEqual(type(client.next_event()), events.ProtocolNegotiated)
self.assertEqual(type(client.next_event()), events.HandshakeCompleted)
now = 1.3
server.receive_datagram(items[0][0], CLIENT_ADDR, now=now)
items = server.datagrams_to_send(now=now)
self.assertEqual(datagram_sizes(items), [228])
self.assertAlmostEqual(server.get_timer(), 1.825)
self.assertEqual(type(server.next_event()), events.ProtocolNegotiated)
self.assertEqual(type(server.next_event()), events.HandshakeCompleted)
now = 1.4
client.receive_datagram(items[0][0], SERVER_ADDR, now=now)
items = client.datagrams_to_send(now=now)
self.assertEqual(datagram_sizes(items), [32])
self.assertAlmostEqual(client.get_timer(), 61.4) # idle timeout
===========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[int]=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) -> None
datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]]
get_timer() -> Optional[float]
handle_timer(now: float) -> None
receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None
at: aioquic.quic.connection.QuicConnection.__init__
self._ack_delay = K_GRANULARITY
self._loss = QuicPacketRecovery(
is_client_without_1rtt=self._is_client,
quic_logger=self._quic_logger,
send_probe=self._send_probe,
)
at: aioquic.quic.recovery.QuicPacketRecovery.__init__
self.spaces: List[QuicPacketSpace] = []
at: aioquic.quic.recovery.QuicPacketSpace.__init__
self.sent_packets: Dict[int, QuicSentPacket] = {}
===========unchanged ref 1===========
at: tests.test_connection
CLIENT_ADDR = ("1.2.3.4", 1234)
SERVER_ADDR = ("2.3.4.5", 4433)
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: unittest.case.TestCase
assertEqual(first: Any, second: Any, msg: Any=...) -> None
assertAlmostEqual(first: float, second: float, places: Optional[int]=..., msg: Any=..., delta: Optional[float]=...) -> None
assertAlmostEqual(first: datetime.datetime, second: datetime.datetime, places: Optional[int]=..., msg: Any=..., delta: Optional[datetime.timedelta]=...) -> None
|
aioquic.quic.connection/QuicConnection._write_handshake
|
Modified
|
aiortc~aioquic
|
4514353cac4cadae040ec2c80be6519b473dc973
|
[qlog] log sent ACK frames in handshake epochs too
|
<21>:<add> # log frame
<add> if self._quic_logger is not None:
<add> builder._packet.quic_logger_frames.append(
<add> self._quic_logger.encode_ack_frame(space.ack_queue, 0.0)
<add> )
<add>
|
# module: aioquic.quic.connection
class QuicConnection:
def _write_handshake(self, builder: QuicPacketBuilder, epoch: tls.Epoch) -> None:
<0> crypto = self._cryptos[epoch]
<1> if not crypto.send.is_valid():
<2> return
<3>
<4> buf = builder.buffer
<5> crypto_stream = self._crypto_streams[epoch]
<6> space = self._spaces[epoch]
<7>
<8> while True:
<9> if epoch == tls.Epoch.INITIAL:
<10> packet_type = PACKET_TYPE_INITIAL
<11> else:
<12> packet_type = PACKET_TYPE_HANDSHAKE
<13> builder.start_packet(packet_type, crypto)
<14>
<15> # ACK
<16> if space.ack_at is not None:
<17> builder.start_frame(QuicFrameType.ACK)
<18> push_ack_frame(buf, space.ack_queue, 0)
<19> space.ack_at = None
<20>
<21> # CRYPTO
<22> if not crypto_stream.send_buffer_is_empty:
<23> write_crypto_frame(builder=builder, space=space, stream=crypto_stream)
<24>
<25> # PADDING (anti-deadlock packet)
<26> if self._probe_pending and self._is_client and epoch == tls.Epoch.HANDSHAKE:
<27> buf.push_bytes(bytes(builder.remaining_space))
<28> self._probe_pending = False
<29>
<30> if not builder.end_packet():
<31> break
<32>
|
===========unchanged ref 0===========
at: aioquic._buffer.Buffer
push_bytes(value: bytes) -> None
at: aioquic.quic.connection
write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None
at: aioquic.quic.connection.QuicConnection.__init__
self._quic_logger = configuration.quic_logger
self._is_client = configuration.is_client
self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}
self._probe_pending = False
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.QuicConnection._send_probe
self._probe_pending = True
at: aioquic.quic.connection.QuicConnection._write_application
self._probe_pending = False
at: aioquic.quic.connection.QuicConnection._write_handshake
crypto = self._cryptos[epoch]
buf = builder.buffer
crypto_stream = self._crypto_streams[epoch]
at: aioquic.quic.logger.QuicLogger
encode_ack_frame(rangeset: RangeSet, delay: float)
at: aioquic.quic.packet
PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00
PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20
QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
QuicFrameType(x: Union[str, bytes, bytearray], base: int)
push_ack_frame(buf: Buffer, rangeset: RangeSet, delay: int) -> None
===========unchanged ref 1===========
at: aioquic.quic.packet_builder.QuicPacketBuilder
start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None
start_packet(packet_type: int, crypto: CryptoPair) -> None
end_packet() -> bool
at: aioquic.quic.packet_builder.QuicPacketBuilder.__init__
self._packet: Optional[QuicSentPacket] = None
at: aioquic.quic.packet_builder.QuicPacketBuilder.end_packet
self._packet = None
at: aioquic.quic.packet_builder.QuicPacketBuilder.start_packet
self._packet = QuicSentPacket(
epoch=epoch,
in_flight=False,
is_ack_eliciting=False,
is_crypto_packet=False,
packet_number=self._packet_number,
packet_type=packet_type,
)
at: aioquic.quic.packet_builder.QuicSentPacket
epoch: Epoch
in_flight: bool
is_ack_eliciting: bool
is_crypto_packet: bool
packet_number: int
packet_type: int
sent_time: Optional[float] = None
sent_bytes: int = 0
delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(
default_factory=list
)
quic_logger_frames: List[Dict] = field(default_factory=list)
at: aioquic.quic.recovery.QuicPacketSpace.__init__
self.ack_at: Optional[float] = None
self.ack_queue = RangeSet()
at: aioquic.quic.stream.QuicStream.__init__
self.send_buffer_is_empty = True
at: aioquic.quic.stream.QuicStream.get_frame
self.send_buffer_is_empty = True
===========unchanged ref 2===========
at: aioquic.quic.stream.QuicStream.on_data_delivery
self.send_buffer_is_empty = False
at: aioquic.quic.stream.QuicStream.write
self.send_buffer_is_empty = False
at: aioquic.tls
Epoch()
===========changed ref 0===========
# module: aioquic.quic.connection
class QuicConnection:
def _write_application(
self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float
) -> None:
crypto_stream: Optional[QuicStream] = None
if self._cryptos[tls.Epoch.ONE_RTT].send.is_valid():
crypto = self._cryptos[tls.Epoch.ONE_RTT]
crypto_stream = self._crypto_streams[tls.Epoch.ONE_RTT]
packet_type = PACKET_TYPE_ONE_RTT
elif self._cryptos[tls.Epoch.ZERO_RTT].send.is_valid():
crypto = self._cryptos[tls.Epoch.ZERO_RTT]
packet_type = PACKET_TYPE_ZERO_RTT
else:
return
space = self._spaces[tls.Epoch.ONE_RTT]
buf = builder.buffer
while True:
# write header
builder.start_packet(packet_type, crypto)
if self._handshake_complete:
# ACK
if space.ack_at is not None and space.ack_at <= now:
- ack_delay = 0.0
builder.start_frame(
QuicFrameType.ACK,
self._on_ack_delivery,
(space, space.largest_received_packet),
)
- push_ack_frame(
- buf,
- space.ack_queue,
- int(ack_delay / 1000000) >> self._local_ack_delay_exponent,
- )
+ push_ack_frame(buf, space.ack_queue, 0)
space.ack_at = None
# log frame
if self._quic_logger is not None:
builder._packet.quic_logger_frames.append(
+ self._quic_logger.encode_ack_frame(space.ack_queue, 0.0)
- self._quic_logger.encode_ack_frame(
- space.ack_queue, ack_</s>
|
examples.http3_server/HttpServerProtocol.__init__
|
Modified
|
aiortc~aioquic
|
c45d7dec885e3bc1c3cfe274b25f787e8a970792
|
[examples] add initial support for WebSockets
|
<1>:<add> self._handlers: Dict[int, Handler] = {}
<del> self._handlers: Dict[int, HttpRequestHandler] = {}
|
# module: examples.http3_server
class HttpServerProtocol(QuicConnectionProtocol):
def __init__(self, *args, **kwargs):
<0> super().__init__(*args, **kwargs)
<1> self._handlers: Dict[int, HttpRequestHandler] = {}
<2> self._http: Optional[HttpConnection] = None
<3>
|
===========unchanged ref 0===========
at: email.utils
formatdate(timeval: Optional[float]=..., localtime: bool=..., usegmt: bool=...) -> str
at: time
time() -> float
===========changed ref 0===========
# module: examples.http3_server
class HttpRequestHandler:
+ def http_event_received(self, event: HttpEvent):
+ if isinstance(event, DataReceived):
+ self.queue.put_nowait(
+ {
+ "type": "http.request",
+ "body": event.data,
+ "more_body": not event.stream_ended,
+ }
+ )
+
===========changed ref 1===========
# module: examples.http3_server
try:
import uvloop
except ImportError:
uvloop = None
AsgiApplication = Callable
HttpConnection = Union[H0Connection, H3Connection]
+ Handler = Union[HttpRequestHandler, WebSocketHandler]
+
|
examples.http3_server/HttpServerProtocol.http_event_received
|
Modified
|
aiortc~aioquic
|
c45d7dec885e3bc1c3cfe274b25f787e8a970792
|
[examples] add initial support for WebSockets
|
<0>:<add> if isinstance(event, RequestReceived) and event.stream_id not in self._handlers:
<del> if isinstance(event, RequestReceived):
<4>:<add> protocol = None
<11>:<add> elif header == b":protocol":
<add> protocol = value.decode("utf8")
<19>:<add> handler: Handler
<add> if method == "CONNECT" and protocol == "websocket":
<add> scope = {
<del> scope = {
<20>:<add> "headers": headers,
<del> "headers": headers,
<21>:<add> "http_version": "0.9"
<add> if isinstance(self._http, H0Connection)
<del> "http_version": "0.9" if isinstance(self._http, H0Connection) else "3",
<22>:<add> else "3",
<add> "method": method,
<del> "method": method,
<23>:<add> "path": path_bytes.decode("utf8"),
<del> "path": path_bytes.decode("utf8"),
<24>:<add> "query_string": query_string,
<del> "query_string": query_string,
<25>:<add> "raw_path": raw_path,
<del> "raw_path": raw_path,
<26>:<add> "root_path": "",
<del> "root_path": "",
<27>:<add> "scheme": "wss",
<del> "scheme": "https",
<28>:<add> "type": "websocket",
<del> "type": "http",
<29>:<add> }
<del> }
<30>:<del>
<31>:<add> handler = WebSocketHandler(
<del> handler = HttpRequestHandler(
<32>:<add>
|
# 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> stream_id=event.stream_id,
<35> transmit=self.transmit,
<36> )
<37> self._handlers[event.stream_id] = handler
<38> asyncio.ensure_future(handler.run_asgi(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,
<45> "more_</s>
|
===========below chunk 0===========
# module: examples.http3_server
class HttpServerProtocol(QuicConnectionProtocol):
def http_event_received(self, event: HttpEvent) -> None:
# offset: 1
}
)
===========unchanged ref 0===========
at: aioquic.h0.connection.H0Connection
send_data(stream_id: int, data: bytes, end_stream: bool) -> None
at: aioquic.h3.connection.H3Connection
send_data(stream_id: int, data: bytes, end_stream: bool) -> None
at: aioquic.h3.events
HttpEvent()
DataReceived(data: bytes, 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]
application = getattr(module, attr_str)
at: examples.http3_server.HttpRequestHandler.__init__
self.connection = connection
self.stream_id = stream_id
self.transmit = transmit
at: examples.http3_server.WebSocketHandler.send
self.websocket = wsproto.Connection(wsproto.ConnectionType.SERVER)
at: typing
Callable = _CallableType(collections.abc.Callable, 2)
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: examples.http3_server
class HttpServerProtocol(QuicConnectionProtocol):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
+ self._handlers: Dict[int, Handler] = {}
- self._handlers: Dict[int, HttpRequestHandler] = {}
self._http: Optional[HttpConnection] = None
===========changed ref 1===========
# module: examples.http3_server
class HttpRequestHandler:
+ def http_event_received(self, event: HttpEvent):
+ if isinstance(event, DataReceived):
+ self.queue.put_nowait(
+ {
+ "type": "http.request",
+ "body": event.data,
+ "more_body": not event.stream_ended,
+ }
+ )
+
===========changed ref 2===========
# module: examples.http3_server
try:
import uvloop
except ImportError:
uvloop = None
AsgiApplication = Callable
HttpConnection = Union[H0Connection, H3Connection]
+ Handler = Union[HttpRequestHandler, WebSocketHandler]
+
|
examples.http3_client/HttpClient.__init__
|
Modified
|
aiortc~aioquic
|
c45d7dec885e3bc1c3cfe274b25f787e8a970792
|
[examples] add initial support for WebSockets
|
<5>:<add> self._websockets: Dict[int, WebSocket] = {}
|
# module: examples.http3_client
class HttpClient(QuicConnectionProtocol):
def __init__(self, *args, **kwargs):
<0> super().__init__(*args, **kwargs)
<1>
<2> self._http: Optional[HttpConnection] = None
<3> self._request_events: Dict[int, Deque[HttpEvent]] = {}
<4> self._request_waiter: Dict[int, asyncio.Future[Deque[HttpEvent]]] = {}
<5>
<6> if self._quic.configuration.alpn_protocols[0].startswith("hq-"):
<7> self._http = H0Connection(self._quic)
<8> else:
<9> self._http = H3Connection(self._quic)
<10>
|
===========unchanged ref 0===========
at: asyncio.queues
Queue(maxsize: int=..., *, loop: Optional[AbstractEventLoop]=...)
at: examples.http3_client
HttpConnection = Union[H0Connection, H3Connection]
at: typing
Callable = _CallableType(collections.abc.Callable, 2)
===========changed ref 0===========
# module: examples.http3_server
+ class WebSocketHandler:
+ def receive(self) -> Dict:
+ return await self.queue.get()
+
===========changed ref 1===========
# module: examples.demo
+ @app.websocket_route("/ws")
+ async def ws(websocket):
+ """
+ WebSocket echo endpoint.
+ """
+ await websocket.accept()
+ message = await websocket.receive_text()
+ await websocket.send_text(message)
+ await websocket.close()
+
===========changed ref 2===========
# module: examples.http3_server
try:
import uvloop
except ImportError:
uvloop = None
AsgiApplication = Callable
HttpConnection = Union[H0Connection, H3Connection]
+ Handler = Union[HttpRequestHandler, WebSocketHandler]
+
===========changed ref 3===========
# module: examples.http3_server
+ class WebSocketHandler:
+ def http_event_received(self, event: HttpEvent) -> None:
+ if isinstance(event, DataReceived):
+ self.websocket.receive_data(event.data)
+
+ for ws_event in self.websocket.events():
+ self.websocket_event_received(ws_event)
+
===========changed ref 4===========
# module: examples.http3_server
class HttpServerProtocol(QuicConnectionProtocol):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
+ self._handlers: Dict[int, Handler] = {}
- self._handlers: Dict[int, HttpRequestHandler] = {}
self._http: Optional[HttpConnection] = None
===========changed ref 5===========
# module: examples.http3_server
class HttpRequestHandler:
+ def http_event_received(self, event: HttpEvent):
+ if isinstance(event, DataReceived):
+ self.queue.put_nowait(
+ {
+ "type": "http.request",
+ "body": event.data,
+ "more_body": not event.stream_ended,
+ }
+ )
+
===========changed ref 6===========
# module: examples.http3_server
+ class WebSocketHandler:
+ def __init__(
+ self,
+ *,
+ connection: HttpConnection,
+ scope: Dict,
+ stream_id: int,
+ transmit: Callable[[], None],
+ ):
+ self.connection = connection
+ self.queue: asyncio.Queue[Dict] = asyncio.Queue()
+ self.scope = scope
+ self.stream_id = stream_id
+ self.transmit = transmit
+ self.websocket: Optional[wsproto.Connection] = None
+
===========changed ref 7===========
# module: examples.http3_server
+ class WebSocketHandler:
+ def run_asgi(self, app: AsgiApplication) -> None:
+ self.queue.put_nowait({"type": "websocket.connect"})
+
+ await application(self.scope, self.receive, self.send)
+
+ self.connection.send_data(stream_id=self.stream_id, data=b"", end_stream=True)
+ self.transmit()
+
===========changed ref 8===========
# module: examples.http3_server
+ class WebSocketHandler:
+ def websocket_event_received(self, event: wsproto.events.Event) -> None:
+ if isinstance(event, wsproto.events.TextMessage):
+ self.queue.put_nowait({"type": "websocket.receive", "text": event.data})
+ elif isinstance(event, wsproto.events.Message):
+ self.queue.put_nowait({"type": "websocket.receive", "bytes": event.data})
+
===========changed ref 9===========
# module: examples.http3_server
+ class WebSocketHandler:
+ def send(self, message: Dict):
+ data = b""
+ if message["type"] == "websocket.accept":
+ self.websocket = wsproto.Connection(wsproto.ConnectionType.SERVER)
+
+ self.connection.send_headers(
+ stream_id=self.stream_id,
+ headers=[
+ (b":status", b"200"),
+ (b"server", b"aioquic"),
+ (b"date", formatdate(time.time(), usegmt=True).encode()),
+ ],
+ )
+ elif message["type"] == "websocket.close":
+ data = self.websocket.send(
+ wsproto.events.CloseConnection(code=message["code"])
+ )
+ elif message["type"] == "websocket.send":
+ if message.get("text") is not None:
+ data = self.websocket.send(
+ wsproto.events.TextMessage(data=message["text"])
+ )
+ elif message.get("bytes") is not None:
+ data = self.websocket.send(
+ wsproto.events.Message(data=message["bytes"])
+ )
+
+ if data:
+ self.connection.send_data(
+ stream_id=self.stream_id, data=data, end_stream=False
+ )
+
+ self.transmit()
+
===========changed ref 10===========
# module: examples.http3_server
class HttpServerProtocol(QuicConnectionProtocol):
def http_event_received(self, event: HttpEvent) -> None:
+ if isinstance(event, RequestReceived) and event.stream_id not in self._handlers:
- if isinstance(event, RequestReceived):
headers = []
raw_path = b""
method = ""
+ protocol = None
for header, value in event.headers:
if header == b":authority":
headers.append((b"host", value))
elif header == b":method":
method = value.decode("utf8")
elif header == b":path":
raw_path = value
+ elif header == b":protocol":
+ protocol = value.decode("utf8")
elif header and not header.startswith(b":"):
headers.append((header, value))
if b"?" in raw_path:
path_bytes, query_string = raw_path.split(b"?", maxsplit=1)
else:
path_bytes, query_string = raw_path, b""
+ handler: Handler
+ if method == "CONNECT" and protocol == "websocket":
+ scope = {
- scope = {
+ "headers": headers,
- "headers": headers,
+ "http_version": "0.9"
+ if isinstance(self._http, H0Connection)
- "http_version": "0.9" if isinstance(self._http, H0Connection) else "3",
+ else "3",
+ "method": method,
- "method": method,
+ "path": path_bytes.decode("utf8"),
- "path": path_bytes.decode("utf8"),
+ "query_string": query_string,
- "query_string": query_string,
+ "raw_path": raw_path,
- "raw_path": raw_path,
+ "root_path": "",
- "root_path": "",
+ "scheme": "wss",
- "scheme": "https</s>
|
examples.http3_client/HttpClient.http_event_received
|
Modified
|
aiortc~aioquic
|
c45d7dec885e3bc1c3cfe274b25f787e8a970792
|
[examples] add initial support for WebSockets
|
<0>:<del> if (
<1>:<add> if isinstance(event, (ResponseReceived, DataReceived)):
<del> isinstance(event, (ResponseReceived, DataReceived))
<2>:<add> stream_id = event.stream_id
<add> if stream_id in self._request_events:
<del> and event.stream_id in self._request_events
<3>:<add> # http
<del> ):
<4>:<add> self._request_events[event.stream_id].append(event)
<del> self._request_events[event.stream_id].append(event)
<5>:<add> if event.stream_ended:
<del> if event.stream_ended:
<6>:<add> request_waiter = self._request_waiter.pop(stream_id)
<del> request_waiter = self._request_waiter.pop(event.stream_id)
<7>:<add> request_waiter.set_result(self._request_events.pop(stream_id))
<del> request_waiter.set_result(self._request_events.pop(event.stream_id))
|
# module: examples.http3_client
class HttpClient(QuicConnectionProtocol):
def http_event_received(self, event: HttpEvent):
<0> if (
<1> isinstance(event, (ResponseReceived, DataReceived))
<2> and event.stream_id in self._request_events
<3> ):
<4> self._request_events[event.stream_id].append(event)
<5> if event.stream_ended:
<6> request_waiter = self._request_waiter.pop(event.stream_id)
<7> request_waiter.set_result(self._request_events.pop(event.stream_id))
<8>
|
===========unchanged ref 0===========
at: aioquic.h0.connection.H0Connection
send_data(stream_id: int, data: bytes, end_stream: bool) -> None
at: aioquic.h3.connection.H3Connection
send_data(stream_id: int, data: bytes, end_stream: bool) -> None
at: aioquic.h3.events
HttpEvent()
DataReceived(data: bytes, stream_id: int, stream_ended: bool)
ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)
at: examples.http3_client.WebSocket.__init__
self.http = http
self.stream_id = stream_id
self.transmit = transmit
self.websocket = wsproto.Connection(wsproto.ConnectionType.CLIENT)
at: examples.http3_client.WebSocket.send
data = self.websocket.send(wsproto.events.TextMessage(data=message))
===========changed ref 0===========
# module: examples.http3_client
+ class WebSocket:
+ def recv(self) -> str:
+ """
+ Receive the next message.
+ """
+ return await self.queue.get()
+
===========changed ref 1===========
# module: examples.http3_client
+ class WebSocket:
+ def send(self, message: str):
+ """
+ Send a message.
+ """
+ assert isinstance(message, str)
+
+ data = self.websocket.send(wsproto.events.TextMessage(data=message))
+ self.http.send_data(stream_id=self.stream_id, data=data, end_stream=False)
+ self.transmit()
+
===========changed ref 2===========
# module: examples.http3_client
+ class WebSocket:
+ def __init__(
+ self, http: HttpConnection, stream_id: int, transmit: Callable[[], None]
+ ) -> None:
+ self.http = http
+ self.queue: asyncio.Queue[str] = asyncio.Queue()
+ self.stream_id = stream_id
+ self.transmit = transmit
+ self.websocket = wsproto.Connection(wsproto.ConnectionType.CLIENT)
+
===========changed ref 3===========
# module: examples.http3_client
+ class WebSocket:
+ def close(self, code=1000, reason=""):
+ """
+ Perform the closing handshake.
+ """
+ data = self.websocket.send(
+ wsproto.events.ConnectionClose(code=code, reason=reason)
+ )
+ self.http.send_data(stream_id=self.stream_id, data=data, end_stream=False)
+ self.transmit()
+
===========changed ref 4===========
# module: examples.http3_client
class HttpClient(QuicConnectionProtocol):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._http: Optional[HttpConnection] = None
self._request_events: Dict[int, Deque[HttpEvent]] = {}
self._request_waiter: Dict[int, asyncio.Future[Deque[HttpEvent]]] = {}
+ self._websockets: Dict[int, WebSocket] = {}
if self._quic.configuration.alpn_protocols[0].startswith("hq-"):
self._http = H0Connection(self._quic)
else:
self._http = H3Connection(self._quic)
===========changed ref 5===========
# module: examples.http3_server
+ class WebSocketHandler:
+ def receive(self) -> Dict:
+ return await self.queue.get()
+
===========changed ref 6===========
# module: examples.demo
+ @app.websocket_route("/ws")
+ async def ws(websocket):
+ """
+ WebSocket echo endpoint.
+ """
+ await websocket.accept()
+ message = await websocket.receive_text()
+ await websocket.send_text(message)
+ await websocket.close()
+
===========changed ref 7===========
# module: examples.http3_server
try:
import uvloop
except ImportError:
uvloop = None
AsgiApplication = Callable
HttpConnection = Union[H0Connection, H3Connection]
+ Handler = Union[HttpRequestHandler, WebSocketHandler]
+
===========changed ref 8===========
# module: examples.http3_server
+ class WebSocketHandler:
+ def http_event_received(self, event: HttpEvent) -> None:
+ if isinstance(event, DataReceived):
+ self.websocket.receive_data(event.data)
+
+ for ws_event in self.websocket.events():
+ self.websocket_event_received(ws_event)
+
===========changed ref 9===========
# module: examples.http3_server
class HttpServerProtocol(QuicConnectionProtocol):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
+ self._handlers: Dict[int, Handler] = {}
- self._handlers: Dict[int, HttpRequestHandler] = {}
self._http: Optional[HttpConnection] = None
===========changed ref 10===========
# module: examples.http3_server
class HttpRequestHandler:
+ def http_event_received(self, event: HttpEvent):
+ if isinstance(event, DataReceived):
+ self.queue.put_nowait(
+ {
+ "type": "http.request",
+ "body": event.data,
+ "more_body": not event.stream_ended,
+ }
+ )
+
===========changed ref 11===========
# module: examples.http3_server
+ class WebSocketHandler:
+ def __init__(
+ self,
+ *,
+ connection: HttpConnection,
+ scope: Dict,
+ stream_id: int,
+ transmit: Callable[[], None],
+ ):
+ self.connection = connection
+ self.queue: asyncio.Queue[Dict] = asyncio.Queue()
+ self.scope = scope
+ self.stream_id = stream_id
+ self.transmit = transmit
+ self.websocket: Optional[wsproto.Connection] = None
+
===========changed ref 12===========
# module: examples.http3_server
+ class WebSocketHandler:
+ def run_asgi(self, app: AsgiApplication) -> None:
+ self.queue.put_nowait({"type": "websocket.connect"})
+
+ await application(self.scope, self.receive, self.send)
+
+ self.connection.send_data(stream_id=self.stream_id, data=b"", end_stream=True)
+ self.transmit()
+
===========changed ref 13===========
# module: examples.http3_server
+ class WebSocketHandler:
+ def websocket_event_received(self, event: wsproto.events.Event) -> None:
+ if isinstance(event, wsproto.events.TextMessage):
+ self.queue.put_nowait({"type": "websocket.receive", "text": event.data})
+ elif isinstance(event, wsproto.events.Message):
+ self.queue.put_nowait({"type": "websocket.receive", "bytes": event.data})
+
|
examples.http3_client/run
|
Modified
|
aiortc~aioquic
|
c45d7dec885e3bc1c3cfe274b25f787e8a970792
|
[examples] add initial support for WebSockets
|
<19>:<add> if websocket:
<add> ws = await client.websocket(parsed.netloc, parsed.path)
<add> await ws.send("Hello, WebSocket!")
<add> message = await ws.recv()
<add> print(message)
<add> else:
<add> # perform request
<del> # perform request
<20>:<add> start = time.time()
<del> start = time.time()
<21>:<add> http_events = await client.get(parsed.netloc, parsed.path)
<del> http_events = await client.get(parsed.netloc, parsed.path)
<22>:<add> elapsed = time.time() - start
<del> elapsed = time.time() - start
<24>:<add> # print speed
<del> # print speed
<25>:<add> octets = 0
<del> octets = 0
<26>:<add> for http_event in http_events:
<del> for http_event in http_events:
<27>:<add> if isinstance(http_event, DataReceived):
<del> if isinstance(http_event, DataReceived):
<28>:<add> octets += len(http_event.data)
<del> octets += len(http_event.data)
<29>:<add> logger.info(
<del> logger.info(
<30>:<add> "Received %d bytes in %.1f s (%.3f Mbps)"
<del> "Received %d bytes in %.1f s (%.3f Mbps)"
<31>:<add> % (octets, elapsed, octets * 8 / elapsed / 1000000)
<del> % (octets, elapsed, octets * 8 / elapsed / 1000000)
<32>:<add> )
<del> )
<34>:<add>
|
# module: examples.http3_client
+ def run(configuration: QuicConfiguration, url: str, websocket: bool) -> None:
- def run(url: str, configuration: QuicConfiguration) -> None:
<0> # parse URL
<1> parsed = urlparse(url)
<2> assert parsed.scheme == "https", "Only HTTPS URLs are supported."
<3> if ":" in parsed.netloc:
<4> host, port_str = parsed.netloc.split(":")
<5> port = int(port_str)
<6> else:
<7> host = parsed.netloc
<8> port = 443
<9>
<10> async with connect(
<11> host,
<12> port,
<13> configuration=configuration,
<14> create_protocol=HttpClient,
<15> session_ticket_handler=save_session_ticket,
<16> ) as client:
<17> client = cast(HttpClient, client)
<18>
<19> # perform request
<20> start = time.time()
<21> http_events = await client.get(parsed.netloc, parsed.path)
<22> elapsed = time.time() - start
<23>
<24> # print speed
<25> octets = 0
<26> for http_event in http_events:
<27> if isinstance(http_event, DataReceived):
<28> octets += len(http_event.data)
<29> logger.info(
<30> "Received %d bytes in %.1f s (%.3f Mbps)"
<31> % (octets, elapsed, octets * 8 / elapsed / 1000000)
<32> )
<33>
<34> # print response
<35> for http_event in http_events:
<36> if isinstance(http_event, ResponseReceived):
<37> headers = b""
<38> for k, v in http_event.headers:
<39> headers += k + b": " + v + b"\r\n"
<40> if headers:
<41> sys.stderr.buffer.write(headers + b"\r\n")
<42> sys.stderr.buffer.flush()
<43> elif isinstance(http_event, DataReceived):
<44> sys.stdout.buffer.write(http_event.data)
<45> sys.stdout.buffer.flush()</s>
|
===========unchanged ref 0===========
at: aioquic.asyncio.protocol.QuicConnectionProtocol
transmit() -> 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(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.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
WebSocket(http: HttpConnection, stream_id: int, transmit: Callable[[], None])
at: examples.http3_client.HttpClient.__init__
self._request_events: Dict[int, Deque[HttpEvent]] = {}
self._request_waiter: Dict[int, asyncio.Future[Deque[HttpEvent]]] = {}
self._websockets: Dict[int, WebSocket] = {}
at: typing
Deque = _alias(collections.deque, 1, name='Deque')
===========changed ref 0===========
# module: examples.http3_client
+ class WebSocket:
+ def websocket_event_received(self, event: wsproto.events.Event) -> None:
+ if isinstance(event, wsproto.events.TextMessage):
+ self.queue.put_nowait(event.data)
+
===========changed ref 1===========
# module: examples.http3_client
+ class WebSocket:
+ def recv(self) -> str:
+ """
+ Receive the next message.
+ """
+ return await self.queue.get()
+
===========changed ref 2===========
# module: examples.http3_client
+ class WebSocket:
+ def http_event_received(self, event: HttpEvent):
+ if isinstance(event, ResponseReceived):
+ pass
+ elif isinstance(event, DataReceived):
+ self.websocket.receive_data(event.data)
+
+ for ws_event in self.websocket.events():
+ self.websocket_event_received(ws_event)
+
===========changed ref 3===========
# module: examples.http3_client
+ class WebSocket:
+ def send(self, message: str):
+ """
+ Send a message.
+ """
+ assert isinstance(message, str)
+
+ data = self.websocket.send(wsproto.events.TextMessage(data=message))
+ self.http.send_data(stream_id=self.stream_id, data=data, end_stream=False)
+ self.transmit()
+
===========changed ref 4===========
# module: examples.http3_client
+ class WebSocket:
+ def __init__(
+ self, http: HttpConnection, stream_id: int, transmit: Callable[[], None]
+ ) -> None:
+ self.http = http
+ self.queue: asyncio.Queue[str] = asyncio.Queue()
+ self.stream_id = stream_id
+ self.transmit = transmit
+ self.websocket = wsproto.Connection(wsproto.ConnectionType.CLIENT)
+
===========changed ref 5===========
# module: examples.http3_client
+ class WebSocket:
+ def close(self, code=1000, reason=""):
+ """
+ Perform the closing handshake.
+ """
+ data = self.websocket.send(
+ wsproto.events.ConnectionClose(code=code, reason=reason)
+ )
+ self.http.send_data(stream_id=self.stream_id, data=data, end_stream=False)
+ self.transmit()
+
===========changed ref 6===========
# module: examples.http3_client
class HttpClient(QuicConnectionProtocol):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._http: Optional[HttpConnection] = None
self._request_events: Dict[int, Deque[HttpEvent]] = {}
self._request_waiter: Dict[int, asyncio.Future[Deque[HttpEvent]]] = {}
+ self._websockets: Dict[int, WebSocket] = {}
if self._quic.configuration.alpn_protocols[0].startswith("hq-"):
self._http = H0Connection(self._quic)
else:
self._http = H3Connection(self._quic)
===========changed ref 7===========
# module: examples.http3_client
class HttpClient(QuicConnectionProtocol):
def http_event_received(self, event: HttpEvent):
- if (
+ if isinstance(event, (ResponseReceived, DataReceived)):
- isinstance(event, (ResponseReceived, DataReceived))
+ stream_id = event.stream_id
+ if stream_id in self._request_events:
- and event.stream_id in self._request_events
+ # http
- ):
+ self._request_events[event.stream_id].append(event)
- self._request_events[event.stream_id].append(event)
+ if event.stream_ended:
- if event.stream_ended:
+ request_waiter = self._request_waiter.pop(stream_id)
- request_waiter = self._request_waiter.pop(event.stream_id)
+ request_waiter.set_result(self._request_events.pop(stream_id))
- request_waiter.set_result(self._request_events.pop(event.stream_id))
===========changed ref 8===========
# module: examples.http3_server
+ class WebSocketHandler:
+ def receive(self) -> Dict:
+ return await self.queue.get()
+
===========changed ref 9===========
# module: examples.demo
+ @app.websocket_route("/ws")
+ async def ws(websocket):
+ """
+ WebSocket echo endpoint.
+ """
+ await websocket.accept()
+ message = await websocket.receive_text()
+ await websocket.send_text(message)
+ await websocket.close()
+
===========changed ref 10===========
# module: examples.http3_server
try:
import uvloop
except ImportError:
uvloop = None
AsgiApplication = Callable
HttpConnection = Union[H0Connection, H3Connection]
+ Handler = Union[HttpRequestHandler, WebSocketHandler]
+
===========changed ref 11===========
# module: examples.http3_server
+ class WebSocketHandler:
+ def http_event_received(self, event: HttpEvent) -> None:
+ if isinstance(event, DataReceived):
+ self.websocket.receive_data(event.data)
+
+ for ws_event in self.websocket.events():
+ self.websocket_event_received(ws_event)
+
===========changed ref 12===========
# module: examples.http3_server
class HttpServerProtocol(QuicConnectionProtocol):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
+ self._handlers: Dict[int, Handler] = {}
- self._handlers: Dict[int, HttpRequestHandler] = {}
self._http: Optional[HttpConnection] = None
|
examples.http3_server/WebSocketHandler.send
|
Modified
|
aiortc~aioquic
|
90168371f5ee051ebd4c7a6e58019807da134922
|
[websocket] add example for subprotocol negotiation
|
<2>:<add> subprotocol = message.get("subprotocol")
<add>
<4>:<del> self.connection.send_headers(
<5>:<del> stream_id=self.stream_id,
<6>:<add> headers = [
<del> headers=[
<7>:<add> (b":status", b"200"),
<del> (b":status", b"200"),
<8>:<add> (b"server", b"aioquic"),
<del> (b"server", b"aioquic"),
<9>:<add> (b"date", formatdate(time.time(), usegmt=True).encode()),
<del> (b"date", formatdate(time.time(), usegmt=True).encode()),
<10>:<del> ],
<11>:<add> ]
<del> )
<12>:<add> if subprotocol is not None:
<add> headers.append((b"sec-websocket-protocol", subprotocol.encode("utf8")))
<add> self.connection.send_headers(stream_id=self.stream_id, headers=headers)
|
# module: examples.http3_server
class WebSocketHandler:
def send(self, message: Dict):
<0> data = b""
<1> if message["type"] == "websocket.accept":
<2> self.websocket = wsproto.Connection(wsproto.ConnectionType.SERVER)
<3>
<4> self.connection.send_headers(
<5> stream_id=self.stream_id,
<6> headers=[
<7> (b":status", b"200"),
<8> (b"server", b"aioquic"),
<9> (b"date", formatdate(time.time(), usegmt=True).encode()),
<10> ],
<11> )
<12> elif message["type"] == "websocket.close":
<13> data = self.websocket.send(
<14> wsproto.events.CloseConnection(code=message["code"])
<15> )
<16> elif message["type"] == "websocket.send":
<17> if message.get("text") is not None:
<18> data = self.websocket.send(
<19> wsproto.events.TextMessage(data=message["text"])
<20> )
<21> elif message.get("bytes") is not None:
<22> data = self.websocket.send(
<23> wsproto.events.Message(data=message["bytes"])
<24> )
<25>
<26> if data:
<27> self.connection.send_data(
<28> stream_id=self.stream_id, data=data, end_stream=False
<29> )
<30>
<31> self.transmit()
<32>
|
===========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: email.utils
formatdate(timeval: Optional[float]=..., localtime: bool=..., usegmt: bool=...) -> str
at: examples.http3_server.WebSocketHandler.__init__
self.connection = connection
self.stream_id = stream_id
self.websocket: Optional[wsproto.Connection] = None
at: time
time() -> float
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
|
examples.http3_server/HttpServerProtocol.http_event_received
|
Modified
|
aiortc~aioquic
|
90168371f5ee051ebd4c7a6e58019807da134922
|
[websocket] add example for subprotocol negotiation
|
<24>:<add> subprotocols: List[str] = []
<add> for header, value in event.headers:
<add> if header == b"sec-websocket-protocol":
<add> subprotocols = [
<add> x.strip() for x in value.decode("utf8").split(",")
<add> ]
<35>:<add> "subprotocols": subprotocols,
|
# module: examples.http3_server
class HttpServerProtocol(QuicConnectionProtocol):
def http_event_received(self, event: HttpEvent) -> None:
<0> if isinstance(event, RequestReceived) and event.stream_id not in self._handlers:
<1> headers = []
<2> raw_path = b""
<3> method = ""
<4> protocol = None
<5> for header, value in event.headers:
<6> if header == b":authority":
<7> headers.append((b"host", value))
<8> elif header == b":method":
<9> method = value.decode("utf8")
<10> elif header == b":path":
<11> raw_path = value
<12> elif header == b":protocol":
<13> protocol = value.decode("utf8")
<14> elif header and not header.startswith(b":"):
<15> headers.append((header, value))
<16>
<17> if b"?" in raw_path:
<18> path_bytes, query_string = raw_path.split(b"?", maxsplit=1)
<19> else:
<20> path_bytes, query_string = raw_path, b""
<21>
<22> handler: Handler
<23> if method == "CONNECT" and protocol == "websocket":
<24> scope = {
<25> "headers": headers,
<26> "http_version": "0.9"
<27> if isinstance(self._http, H0Connection)
<28> else "3",
<29> "method": method,
<30> "path": path_bytes.decode("utf8"),
<31> "query_string": query_string,
<32> "raw_path": raw_path,
<33> "root_path": "",
<34> "scheme": "wss",
<35> "type": "websocket",
<36> }
<37> handler = WebSocketHandler(
<38> connection=self._http,
<39> scope=scope,
<40> stream_id=event.stream_id,
<41> transmit=self.transmit,
<42> )
<43> else:
<44> scope = {
<45> "headers": headers,
<46> "http_version": "0.9"
<47> if</s>
|
===========below chunk 0===========
# module: examples.http3_server
class HttpServerProtocol(QuicConnectionProtocol):
def http_event_received(self, event: HttpEvent) -> None:
# offset: 1
else "3",
"method": method,
"path": path_bytes.decode("utf8"),
"query_string": query_string,
"raw_path": raw_path,
"root_path": "",
"scheme": "https",
"type": "http",
}
handler = HttpRequestHandler(
connection=self._http,
scope=scope,
stream_id=event.stream_id,
transmit=self.transmit,
)
self._handlers[event.stream_id] = handler
asyncio.ensure_future(handler.run_asgi(application))
elif isinstance(event, DataReceived) and event.stream_id in self._handlers:
handler = self._handlers[event.stream_id]
handler.http_event_received(event)
===========unchanged ref 0===========
at: aioquic.asyncio.protocol.QuicConnectionProtocol
transmit() -> None
at: aioquic.h0.connection
H0Connection(quic: QuicConnection)
at: aioquic.h3.events
HttpEvent()
RequestReceived(headers: Headers, stream_id: int, stream_ended: bool)
at: examples.http3_server
HttpConnection = Union[H0Connection, H3Connection]
HttpRequestHandler(*, connection: HttpConnection, scope: Dict, stream_id: int, transmit: Callable[[], None])
WebSocketHandler(*, connection: HttpConnection, scope: Dict, stream_id: int, transmit: Callable[[], None])
Handler = Union[HttpRequestHandler, WebSocketHandler]
at: examples.http3_server.HttpServerProtocol.__init__
self._handlers: Dict[int, Handler] = {}
at: examples.http3_server.HttpServerProtocol.quic_event_received
self._http = H3Connection(self._quic)
self._http = H0Connection(self._quic)
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: examples.http3_server
class WebSocketHandler:
def send(self, message: Dict):
data = b""
if message["type"] == "websocket.accept":
+ subprotocol = message.get("subprotocol")
+
self.websocket = wsproto.Connection(wsproto.ConnectionType.SERVER)
- self.connection.send_headers(
- stream_id=self.stream_id,
+ headers = [
- headers=[
+ (b":status", b"200"),
- (b":status", b"200"),
+ (b"server", b"aioquic"),
- (b"server", b"aioquic"),
+ (b"date", formatdate(time.time(), usegmt=True).encode()),
- (b"date", formatdate(time.time(), usegmt=True).encode()),
- ],
+ ]
- )
+ if subprotocol is not None:
+ headers.append((b"sec-websocket-protocol", subprotocol.encode("utf8")))
+ self.connection.send_headers(stream_id=self.stream_id, headers=headers)
elif message["type"] == "websocket.close":
data = self.websocket.send(
wsproto.events.CloseConnection(code=message["code"])
)
elif message["type"] == "websocket.send":
if message.get("text") is not None:
data = self.websocket.send(
wsproto.events.TextMessage(data=message["text"])
)
elif message.get("bytes") is not None:
data = self.websocket.send(
wsproto.events.Message(data=message["bytes"])
)
if data:
self.connection.send_data(
stream_id=self.stream_id, data=data, end_stream=False
)
self.transmit()
|
examples.demo/ws
|
Modified
|
aiortc~aioquic
|
90168371f5ee051ebd4c7a6e58019807da134922
|
[websocket] add example for subprotocol negotiation
|
<3>:<add> if "chat" in websocket.scope["subprotocols"]:
<add> subprotocol = "chat"
<add> else:
<add> subprotocol = None
<add> await websocket.accept(subprotocol=subprotocol)
<add>
<del> await websocket.accept()
|
# module: examples.demo
@app.websocket_route("/ws")
async def ws(websocket):
<0> """
<1> WebSocket echo endpoint.
<2> """
<3> await websocket.accept()
<4> message = await websocket.receive_text()
<5> await websocket.send_text(message)
<6> await websocket.close()
<7>
|
===========unchanged ref 0===========
at: examples.demo
app = Starlette()
===========changed ref 0===========
# module: examples.http3_server
class WebSocketHandler:
def send(self, message: Dict):
data = b""
if message["type"] == "websocket.accept":
+ subprotocol = message.get("subprotocol")
+
self.websocket = wsproto.Connection(wsproto.ConnectionType.SERVER)
- self.connection.send_headers(
- stream_id=self.stream_id,
+ headers = [
- headers=[
+ (b":status", b"200"),
- (b":status", b"200"),
+ (b"server", b"aioquic"),
- (b"server", b"aioquic"),
+ (b"date", formatdate(time.time(), usegmt=True).encode()),
- (b"date", formatdate(time.time(), usegmt=True).encode()),
- ],
+ ]
- )
+ if subprotocol is not None:
+ headers.append((b"sec-websocket-protocol", subprotocol.encode("utf8")))
+ self.connection.send_headers(stream_id=self.stream_id, headers=headers)
elif message["type"] == "websocket.close":
data = self.websocket.send(
wsproto.events.CloseConnection(code=message["code"])
)
elif message["type"] == "websocket.send":
if message.get("text") is not None:
data = self.websocket.send(
wsproto.events.TextMessage(data=message["text"])
)
elif message.get("bytes") is not None:
data = self.websocket.send(
wsproto.events.Message(data=message["bytes"])
)
if data:
self.connection.send_data(
stream_id=self.stream_id, data=data, end_stream=False
)
self.transmit()
===========changed ref 1===========
# module: examples.http3_server
class HttpServerProtocol(QuicConnectionProtocol):
def http_event_received(self, event: HttpEvent) -> None:
if isinstance(event, RequestReceived) and event.stream_id not in self._handlers:
headers = []
raw_path = b""
method = ""
protocol = None
for header, value in event.headers:
if header == b":authority":
headers.append((b"host", value))
elif header == b":method":
method = value.decode("utf8")
elif header == b":path":
raw_path = value
elif header == b":protocol":
protocol = value.decode("utf8")
elif header and not header.startswith(b":"):
headers.append((header, value))
if b"?" in raw_path:
path_bytes, query_string = raw_path.split(b"?", maxsplit=1)
else:
path_bytes, query_string = raw_path, b""
handler: Handler
if method == "CONNECT" and protocol == "websocket":
+ subprotocols: List[str] = []
+ for header, value in event.headers:
+ if header == b"sec-websocket-protocol":
+ subprotocols = [
+ x.strip() for x in value.decode("utf8").split(",")
+ ]
scope = {
"headers": headers,
"http_version": "0.9"
if isinstance(self._http, H0Connection)
else "3",
"method": method,
"path": path_bytes.decode("utf8"),
"query_string": query_string,
"raw_path": raw_path,
"root_path": "",
"scheme": "wss",
+ "subprotocols": subprotocols,
"type": "websocket",
}
handler = WebSocketHandler(
connection=self._http,
scope=scope,
stream_id=event.stream_id,
transmit=self.transmit,
</s>
===========changed ref 2===========
# module: examples.http3_server
class HttpServerProtocol(QuicConnectionProtocol):
def http_event_received(self, event: HttpEvent) -> None:
# offset: 1
<s>,
scope=scope,
stream_id=event.stream_id,
transmit=self.transmit,
)
else:
scope = {
"headers": headers,
"http_version": "0.9"
if isinstance(self._http, H0Connection)
else "3",
"method": method,
"path": path_bytes.decode("utf8"),
"query_string": query_string,
"raw_path": raw_path,
"root_path": "",
"scheme": "https",
"type": "http",
}
handler = HttpRequestHandler(
connection=self._http,
scope=scope,
stream_id=event.stream_id,
transmit=self.transmit,
)
self._handlers[event.stream_id] = handler
asyncio.ensure_future(handler.run_asgi(application))
elif isinstance(event, DataReceived) and event.stream_id in self._handlers:
handler = self._handlers[event.stream_id]
handler.http_event_received(event)
|
examples.http3_client/WebSocket.__init__
|
Modified
|
aiortc~aioquic
|
90168371f5ee051ebd4c7a6e58019807da134922
|
[websocket] add example for subprotocol negotiation
|
<3>:<add> self.subprotocol: Optional[str] = None
|
# module: examples.http3_client
class WebSocket:
def __init__(
self, http: HttpConnection, stream_id: int, transmit: Callable[[], None]
) -> None:
<0> self.http = http
<1> self.queue: asyncio.Queue[str] = asyncio.Queue()
<2> self.stream_id = stream_id
<3> self.transmit = transmit
<4> self.websocket = wsproto.Connection(wsproto.ConnectionType.CLIENT)
<5>
|
===========unchanged ref 0===========
at: asyncio.queues
Queue(maxsize: int=..., *, loop: Optional[AbstractEventLoop]=...)
at: examples.http3_client
HttpConnection = Union[H0Connection, H3Connection]
at: examples.http3_client.WebSocket.http_event_received
self.subprotocol = value.decode("utf8")
at: typing
Callable = _CallableType(collections.abc.Callable, 2)
===========changed ref 0===========
# module: examples.demo
@app.websocket_route("/ws")
async def ws(websocket):
"""
WebSocket echo endpoint.
"""
+ if "chat" in websocket.scope["subprotocols"]:
+ subprotocol = "chat"
+ else:
+ subprotocol = None
+ await websocket.accept(subprotocol=subprotocol)
+
- await websocket.accept()
message = await websocket.receive_text()
await websocket.send_text(message)
await websocket.close()
===========changed ref 1===========
# module: examples.http3_server
class WebSocketHandler:
def send(self, message: Dict):
data = b""
if message["type"] == "websocket.accept":
+ subprotocol = message.get("subprotocol")
+
self.websocket = wsproto.Connection(wsproto.ConnectionType.SERVER)
- self.connection.send_headers(
- stream_id=self.stream_id,
+ headers = [
- headers=[
+ (b":status", b"200"),
- (b":status", b"200"),
+ (b"server", b"aioquic"),
- (b"server", b"aioquic"),
+ (b"date", formatdate(time.time(), usegmt=True).encode()),
- (b"date", formatdate(time.time(), usegmt=True).encode()),
- ],
+ ]
- )
+ if subprotocol is not None:
+ headers.append((b"sec-websocket-protocol", subprotocol.encode("utf8")))
+ self.connection.send_headers(stream_id=self.stream_id, headers=headers)
elif message["type"] == "websocket.close":
data = self.websocket.send(
wsproto.events.CloseConnection(code=message["code"])
)
elif message["type"] == "websocket.send":
if message.get("text") is not None:
data = self.websocket.send(
wsproto.events.TextMessage(data=message["text"])
)
elif message.get("bytes") is not None:
data = self.websocket.send(
wsproto.events.Message(data=message["bytes"])
)
if data:
self.connection.send_data(
stream_id=self.stream_id, data=data, end_stream=False
)
self.transmit()
===========changed ref 2===========
# module: examples.http3_server
class HttpServerProtocol(QuicConnectionProtocol):
def http_event_received(self, event: HttpEvent) -> None:
if isinstance(event, RequestReceived) and event.stream_id not in self._handlers:
headers = []
raw_path = b""
method = ""
protocol = None
for header, value in event.headers:
if header == b":authority":
headers.append((b"host", value))
elif header == b":method":
method = value.decode("utf8")
elif header == b":path":
raw_path = value
elif header == b":protocol":
protocol = value.decode("utf8")
elif header and not header.startswith(b":"):
headers.append((header, value))
if b"?" in raw_path:
path_bytes, query_string = raw_path.split(b"?", maxsplit=1)
else:
path_bytes, query_string = raw_path, b""
handler: Handler
if method == "CONNECT" and protocol == "websocket":
+ subprotocols: List[str] = []
+ for header, value in event.headers:
+ if header == b"sec-websocket-protocol":
+ subprotocols = [
+ x.strip() for x in value.decode("utf8").split(",")
+ ]
scope = {
"headers": headers,
"http_version": "0.9"
if isinstance(self._http, H0Connection)
else "3",
"method": method,
"path": path_bytes.decode("utf8"),
"query_string": query_string,
"raw_path": raw_path,
"root_path": "",
"scheme": "wss",
+ "subprotocols": subprotocols,
"type": "websocket",
}
handler = WebSocketHandler(
connection=self._http,
scope=scope,
stream_id=event.stream_id,
transmit=self.transmit,
</s>
===========changed ref 3===========
# module: examples.http3_server
class HttpServerProtocol(QuicConnectionProtocol):
def http_event_received(self, event: HttpEvent) -> None:
# offset: 1
<s>,
scope=scope,
stream_id=event.stream_id,
transmit=self.transmit,
)
else:
scope = {
"headers": headers,
"http_version": "0.9"
if isinstance(self._http, H0Connection)
else "3",
"method": method,
"path": path_bytes.decode("utf8"),
"query_string": query_string,
"raw_path": raw_path,
"root_path": "",
"scheme": "https",
"type": "http",
}
handler = HttpRequestHandler(
connection=self._http,
scope=scope,
stream_id=event.stream_id,
transmit=self.transmit,
)
self._handlers[event.stream_id] = handler
asyncio.ensure_future(handler.run_asgi(application))
elif isinstance(event, DataReceived) and event.stream_id in self._handlers:
handler = self._handlers[event.stream_id]
handler.http_event_received(event)
|
examples.http3_client/WebSocket.http_event_received
|
Modified
|
aiortc~aioquic
|
90168371f5ee051ebd4c7a6e58019807da134922
|
[websocket] add example for subprotocol negotiation
|
<1>:<add> for header, value in event.headers:
<add> if header == b"sec-websocket-protocol":
<add> self.subprotocol = value.decode("utf8")
<del> pass
|
# module: examples.http3_client
class WebSocket:
def http_event_received(self, event: HttpEvent):
<0> if isinstance(event, ResponseReceived):
<1> pass
<2> elif isinstance(event, DataReceived):
<3> self.websocket.receive_data(event.data)
<4>
<5> for ws_event in self.websocket.events():
<6> self.websocket_event_received(ws_event)
<7>
|
===========unchanged ref 0===========
at: aioquic.h3.events
HttpEvent()
DataReceived(data: bytes, stream_id: int, stream_ended: bool)
ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)
at: examples.http3_client.WebSocket.__init__
self.subprotocol: Optional[str] = None
self.websocket = wsproto.Connection(wsproto.ConnectionType.CLIENT)
===========changed ref 0===========
# module: examples.http3_client
class WebSocket:
def __init__(
self, http: HttpConnection, stream_id: int, transmit: Callable[[], None]
) -> None:
self.http = http
self.queue: asyncio.Queue[str] = asyncio.Queue()
self.stream_id = stream_id
+ self.subprotocol: Optional[str] = None
self.transmit = transmit
self.websocket = wsproto.Connection(wsproto.ConnectionType.CLIENT)
===========changed ref 1===========
# module: examples.demo
@app.websocket_route("/ws")
async def ws(websocket):
"""
WebSocket echo endpoint.
"""
+ if "chat" in websocket.scope["subprotocols"]:
+ subprotocol = "chat"
+ else:
+ subprotocol = None
+ await websocket.accept(subprotocol=subprotocol)
+
- await websocket.accept()
message = await websocket.receive_text()
await websocket.send_text(message)
await websocket.close()
===========changed ref 2===========
# module: examples.http3_server
class WebSocketHandler:
def send(self, message: Dict):
data = b""
if message["type"] == "websocket.accept":
+ subprotocol = message.get("subprotocol")
+
self.websocket = wsproto.Connection(wsproto.ConnectionType.SERVER)
- self.connection.send_headers(
- stream_id=self.stream_id,
+ headers = [
- headers=[
+ (b":status", b"200"),
- (b":status", b"200"),
+ (b"server", b"aioquic"),
- (b"server", b"aioquic"),
+ (b"date", formatdate(time.time(), usegmt=True).encode()),
- (b"date", formatdate(time.time(), usegmt=True).encode()),
- ],
+ ]
- )
+ if subprotocol is not None:
+ headers.append((b"sec-websocket-protocol", subprotocol.encode("utf8")))
+ self.connection.send_headers(stream_id=self.stream_id, headers=headers)
elif message["type"] == "websocket.close":
data = self.websocket.send(
wsproto.events.CloseConnection(code=message["code"])
)
elif message["type"] == "websocket.send":
if message.get("text") is not None:
data = self.websocket.send(
wsproto.events.TextMessage(data=message["text"])
)
elif message.get("bytes") is not None:
data = self.websocket.send(
wsproto.events.Message(data=message["bytes"])
)
if data:
self.connection.send_data(
stream_id=self.stream_id, data=data, end_stream=False
)
self.transmit()
===========changed ref 3===========
# module: examples.http3_server
class HttpServerProtocol(QuicConnectionProtocol):
def http_event_received(self, event: HttpEvent) -> None:
if isinstance(event, RequestReceived) and event.stream_id not in self._handlers:
headers = []
raw_path = b""
method = ""
protocol = None
for header, value in event.headers:
if header == b":authority":
headers.append((b"host", value))
elif header == b":method":
method = value.decode("utf8")
elif header == b":path":
raw_path = value
elif header == b":protocol":
protocol = value.decode("utf8")
elif header and not header.startswith(b":"):
headers.append((header, value))
if b"?" in raw_path:
path_bytes, query_string = raw_path.split(b"?", maxsplit=1)
else:
path_bytes, query_string = raw_path, b""
handler: Handler
if method == "CONNECT" and protocol == "websocket":
+ subprotocols: List[str] = []
+ for header, value in event.headers:
+ if header == b"sec-websocket-protocol":
+ subprotocols = [
+ x.strip() for x in value.decode("utf8").split(",")
+ ]
scope = {
"headers": headers,
"http_version": "0.9"
if isinstance(self._http, H0Connection)
else "3",
"method": method,
"path": path_bytes.decode("utf8"),
"query_string": query_string,
"raw_path": raw_path,
"root_path": "",
"scheme": "wss",
+ "subprotocols": subprotocols,
"type": "websocket",
}
handler = WebSocketHandler(
connection=self._http,
scope=scope,
stream_id=event.stream_id,
transmit=self.transmit,
</s>
===========changed ref 4===========
# module: examples.http3_server
class HttpServerProtocol(QuicConnectionProtocol):
def http_event_received(self, event: HttpEvent) -> None:
# offset: 1
<s>,
scope=scope,
stream_id=event.stream_id,
transmit=self.transmit,
)
else:
scope = {
"headers": headers,
"http_version": "0.9"
if isinstance(self._http, H0Connection)
else "3",
"method": method,
"path": path_bytes.decode("utf8"),
"query_string": query_string,
"raw_path": raw_path,
"root_path": "",
"scheme": "https",
"type": "http",
}
handler = HttpRequestHandler(
connection=self._http,
scope=scope,
stream_id=event.stream_id,
transmit=self.transmit,
)
self._handlers[event.stream_id] = handler
asyncio.ensure_future(handler.run_asgi(application))
elif isinstance(event, DataReceived) and event.stream_id in self._handlers:
handler = self._handlers[event.stream_id]
handler.http_event_received(event)
|
examples.http3_client/HttpClient.websocket
|
Modified
|
aiortc~aioquic
|
90168371f5ee051ebd4c7a6e58019807da134922
|
[websocket] add example for subprotocol negotiation
|
<7>:<del> self._http.send_headers(
<8>:<del> stream_id=stream_id,
<9>:<add> headers = [
<del> headers=[
<10>:<add> (b":method", b"CONNECT"),
<del> (b":method", b"CONNECT"),
<11>:<add> (b":scheme", b"https"),
<del> (b":scheme", b"https"),
<12>:<add> (b":authority", authority.encode("utf8")),
<del> (b":authority", authority.encode("utf8")),
<13>:<add> (b":path", path.encode("utf8")),
<del> (b":path", path.encode("utf8")),
<14>:<add> (b":protocol", b"websocket"),
<del> (b":protocol", b"websocket"),
<15>:<del> ],
<16>:<add> ]
<del> )
<17>:<add> if subprotocols:
<add> headers.append(
<add> (b"sec-websocket-protocol", ", ".join(subprotocols).encode("utf8"))
<add> )
<add> self._http.send_headers(stream_id=stream_id, headers=headers)
<add>
|
# module: examples.http3_client
class HttpClient(QuicConnectionProtocol):
+ def websocket(
+ self, authority: str, path: str, subprotocols: List[str] = []
+ ) -> WebSocket:
- def websocket(self, authority: str, path: str) -> WebSocket:
<0> stream_id = self._quic.get_next_available_stream_id()
<1> websocket = WebSocket(
<2> http=self._http, stream_id=stream_id, transmit=self.transmit
<3> )
<4>
<5> self._websockets[stream_id] = websocket
<6>
<7> self._http.send_headers(
<8> stream_id=stream_id,
<9> headers=[
<10> (b":method", b"CONNECT"),
<11> (b":scheme", b"https"),
<12> (b":authority", authority.encode("utf8")),
<13> (b":path", path.encode("utf8")),
<14> (b":protocol", b"websocket"),
<15> ],
<16> )
<17> self.transmit()
<18>
<19> return websocket
<20>
|
===========unchanged ref 0===========
at: aioquic.asyncio.protocol.QuicConnectionProtocol
transmit() -> None
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.tasks
shield(arg: _FutureT[_T], *, loop: Optional[AbstractEventLoop]=...) -> Future[_T]
at: examples.http3_client
WebSocket(http: HttpConnection, stream_id: int, transmit: Callable[[], None])
at: examples.http3_client.HttpClient.__init__
self._http = H3Connection(self._quic)
self._http: Optional[HttpConnection] = None
self._http = H0Connection(self._quic)
self._websockets: Dict[int, WebSocket] = {}
at: examples.http3_client.HttpClient.get
waiter = self._loop.create_future()
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: examples.http3_client
class WebSocket:
def http_event_received(self, event: HttpEvent):
if isinstance(event, ResponseReceived):
+ for header, value in event.headers:
+ if header == b"sec-websocket-protocol":
+ self.subprotocol = value.decode("utf8")
- pass
elif isinstance(event, DataReceived):
self.websocket.receive_data(event.data)
for ws_event in self.websocket.events():
self.websocket_event_received(ws_event)
===========changed ref 1===========
# module: examples.http3_client
class WebSocket:
def __init__(
self, http: HttpConnection, stream_id: int, transmit: Callable[[], None]
) -> None:
self.http = http
self.queue: asyncio.Queue[str] = asyncio.Queue()
self.stream_id = stream_id
+ self.subprotocol: Optional[str] = None
self.transmit = transmit
self.websocket = wsproto.Connection(wsproto.ConnectionType.CLIENT)
===========changed ref 2===========
# module: examples.demo
@app.websocket_route("/ws")
async def ws(websocket):
"""
WebSocket echo endpoint.
"""
+ if "chat" in websocket.scope["subprotocols"]:
+ subprotocol = "chat"
+ else:
+ subprotocol = None
+ await websocket.accept(subprotocol=subprotocol)
+
- await websocket.accept()
message = await websocket.receive_text()
await websocket.send_text(message)
await websocket.close()
===========changed ref 3===========
# module: examples.http3_server
class WebSocketHandler:
def send(self, message: Dict):
data = b""
if message["type"] == "websocket.accept":
+ subprotocol = message.get("subprotocol")
+
self.websocket = wsproto.Connection(wsproto.ConnectionType.SERVER)
- self.connection.send_headers(
- stream_id=self.stream_id,
+ headers = [
- headers=[
+ (b":status", b"200"),
- (b":status", b"200"),
+ (b"server", b"aioquic"),
- (b"server", b"aioquic"),
+ (b"date", formatdate(time.time(), usegmt=True).encode()),
- (b"date", formatdate(time.time(), usegmt=True).encode()),
- ],
+ ]
- )
+ if subprotocol is not None:
+ headers.append((b"sec-websocket-protocol", subprotocol.encode("utf8")))
+ self.connection.send_headers(stream_id=self.stream_id, headers=headers)
elif message["type"] == "websocket.close":
data = self.websocket.send(
wsproto.events.CloseConnection(code=message["code"])
)
elif message["type"] == "websocket.send":
if message.get("text") is not None:
data = self.websocket.send(
wsproto.events.TextMessage(data=message["text"])
)
elif message.get("bytes") is not None:
data = self.websocket.send(
wsproto.events.Message(data=message["bytes"])
)
if data:
self.connection.send_data(
stream_id=self.stream_id, data=data, end_stream=False
)
self.transmit()
===========changed ref 4===========
# module: examples.http3_server
class HttpServerProtocol(QuicConnectionProtocol):
def http_event_received(self, event: HttpEvent) -> None:
if isinstance(event, RequestReceived) and event.stream_id not in self._handlers:
headers = []
raw_path = b""
method = ""
protocol = None
for header, value in event.headers:
if header == b":authority":
headers.append((b"host", value))
elif header == b":method":
method = value.decode("utf8")
elif header == b":path":
raw_path = value
elif header == b":protocol":
protocol = value.decode("utf8")
elif header and not header.startswith(b":"):
headers.append((header, value))
if b"?" in raw_path:
path_bytes, query_string = raw_path.split(b"?", maxsplit=1)
else:
path_bytes, query_string = raw_path, b""
handler: Handler
if method == "CONNECT" and protocol == "websocket":
+ subprotocols: List[str] = []
+ for header, value in event.headers:
+ if header == b"sec-websocket-protocol":
+ subprotocols = [
+ x.strip() for x in value.decode("utf8").split(",")
+ ]
scope = {
"headers": headers,
"http_version": "0.9"
if isinstance(self._http, H0Connection)
else "3",
"method": method,
"path": path_bytes.decode("utf8"),
"query_string": query_string,
"raw_path": raw_path,
"root_path": "",
"scheme": "wss",
+ "subprotocols": subprotocols,
"type": "websocket",
}
handler = WebSocketHandler(
connection=self._http,
scope=scope,
stream_id=event.stream_id,
transmit=self.transmit,
</s>
===========changed ref 5===========
# module: examples.http3_server
class HttpServerProtocol(QuicConnectionProtocol):
def http_event_received(self, event: HttpEvent) -> None:
# offset: 1
<s>,
scope=scope,
stream_id=event.stream_id,
transmit=self.transmit,
)
else:
scope = {
"headers": headers,
"http_version": "0.9"
if isinstance(self._http, H0Connection)
else "3",
"method": method,
"path": path_bytes.decode("utf8"),
"query_string": query_string,
"raw_path": raw_path,
"root_path": "",
"scheme": "https",
"type": "http",
}
handler = HttpRequestHandler(
connection=self._http,
scope=scope,
stream_id=event.stream_id,
transmit=self.transmit,
)
self._handlers[event.stream_id] = handler
asyncio.ensure_future(handler.run_asgi(application))
elif isinstance(event, DataReceived) and event.stream_id in self._handlers:
handler = self._handlers[event.stream_id]
handler.http_event_received(event)
|
examples.http3_client/run
|
Modified
|
aiortc~aioquic
|
90168371f5ee051ebd4c7a6e58019807da134922
|
[websocket] add example for subprotocol negotiation
|
<20>:<add> ws = await client.websocket(
<add> parsed.netloc, parsed.path, subprotocols=["chat", "superchat"]
<add> )
<del> ws = await client.websocket(parsed.netloc, parsed.path)
|
# module: examples.http3_client
def run(configuration: QuicConfiguration, url: str, websocket: bool) -> None:
<0> # parse URL
<1> parsed = urlparse(url)
<2> assert parsed.scheme == "https", "Only HTTPS URLs are supported."
<3> if ":" in parsed.netloc:
<4> host, port_str = parsed.netloc.split(":")
<5> port = int(port_str)
<6> else:
<7> host = parsed.netloc
<8> port = 443
<9>
<10> async with connect(
<11> host,
<12> port,
<13> configuration=configuration,
<14> create_protocol=HttpClient,
<15> session_ticket_handler=save_session_ticket,
<16> ) as client:
<17> client = cast(HttpClient, client)
<18>
<19> if websocket:
<20> ws = await client.websocket(parsed.netloc, parsed.path)
<21> await ws.send("Hello, WebSocket!")
<22> message = await ws.recv()
<23> print(message)
<24> else:
<25> # perform request
<26> start = time.time()
<27> http_events = await client.get(parsed.netloc, parsed.path)
<28> elapsed = time.time() - start
<29>
<30> # print speed
<31> octets = 0
<32> for http_event in http_events:
<33> if isinstance(http_event, DataReceived):
<34> octets += len(http_event.data)
<35> logger.info(
<36> "Received %d bytes in %.1f s (%.3f Mbps)"
<37> % (octets, elapsed, octets * 8 / elapsed / 1000000)
<38> )
<39>
<40> # print response
<41> for http_event in http_events:
<42> if isinstance(http_event, ResponseReceived):
<43> headers = b""
<44> for k, v in http_event.headers:
<45> headers += k + b": " + v + b"\r\n"
<46> if headers:
<47> sys.stderr.buffer.write(headers + b"\r\n")
<48> sys.stderr.buffer.flush()</s>
|
===========below chunk 0===========
# module: examples.http3_client
def run(configuration: QuicConfiguration, url: str, websocket: bool) -> None:
# offset: 1
sys.stdout.buffer.write(http_event.data)
sys.stdout.buffer.flush()
===========unchanged ref 0===========
at: _pickle
dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None)
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.h3.events
DataReceived(data: bytes, 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[int]=field(
default_factory=lambda: [QuicProtocolVersion.DRAFT_22]
))
at: examples.http3_client
logger = logging.getLogger("client")
HttpClient(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None, /, *, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None)
save_session_ticket(ticket)
args = parser.parse_args()
at: examples.http3_client.HttpClient
get(authority: str, path: str) -> Deque[HttpEvent]
websocket(self, authority: str, path: str, subprotocols: List[str]=[]) -> WebSocket
websocket(authority: str, path: str, subprotocols: List[str]=[]) -> WebSocket
at: examples.http3_client.WebSocket
recv() -> str
send(message: str)
===========unchanged ref 1===========
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: 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: 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 websocket(
+ self, authority: str, path: str, subprotocols: List[str] = []
+ ) -> WebSocket:
- def websocket(self, authority: str, path: str) -> WebSocket:
stream_id = self._quic.get_next_available_stream_id()
websocket = WebSocket(
http=self._http, stream_id=stream_id, transmit=self.transmit
)
self._websockets[stream_id] = websocket
- self._http.send_headers(
- stream_id=stream_id,
+ headers = [
- headers=[
+ (b":method", b"CONNECT"),
- (b":method", b"CONNECT"),
+ (b":scheme", b"https"),
- (b":scheme", b"https"),
+ (b":authority", authority.encode("utf8")),
- (b":authority", authority.encode("utf8")),
+ (b":path", path.encode("utf8")),
- (b":path", path.encode("utf8")),
+ (b":protocol", b"websocket"),
- (b":protocol", b"websocket"),
- ],
+ ]
- )
+ if subprotocols:
+ headers.append(
+ (b"sec-websocket-protocol", ", ".join(subprotocols).encode("utf8"))
+ )
+ self._http.send_headers(stream_id=stream_id, headers=headers)
+
self.transmit()
return websocket
===========changed ref 1===========
# module: examples.http3_client
class WebSocket:
def http_event_received(self, event: HttpEvent):
if isinstance(event, ResponseReceived):
+ for header, value in event.headers:
+ if header == b"sec-websocket-protocol":
+ self.subprotocol = value.decode("utf8")
- pass
elif isinstance(event, DataReceived):
self.websocket.receive_data(event.data)
for ws_event in self.websocket.events():
self.websocket_event_received(ws_event)
===========changed ref 2===========
# module: examples.http3_client
class WebSocket:
def __init__(
self, http: HttpConnection, stream_id: int, transmit: Callable[[], None]
) -> None:
self.http = http
self.queue: asyncio.Queue[str] = asyncio.Queue()
self.stream_id = stream_id
+ self.subprotocol: Optional[str] = None
self.transmit = transmit
self.websocket = wsproto.Connection(wsproto.ConnectionType.CLIENT)
===========changed ref 3===========
# module: examples.demo
@app.websocket_route("/ws")
async def ws(websocket):
"""
WebSocket echo endpoint.
"""
+ if "chat" in websocket.scope["subprotocols"]:
+ subprotocol = "chat"
+ else:
+ subprotocol = None
+ await websocket.accept(subprotocol=subprotocol)
+
- await websocket.accept()
message = await websocket.receive_text()
await websocket.send_text(message)
await websocket.close()
|
examples.http3_client/WebSocket.close
|
Modified
|
aiortc~aioquic
|
def64d650cf9267e74b82520d6264deb06650872
|
[http3 client] make client perform websocket close
|
<4>:<add> wsproto.events.CloseConnection(code=code, reason=reason)
<del> wsproto.events.ConnectionClose(code=code, reason=reason)
<6>:<add> self.http.send_data(stream_id=self.stream_id, data=data, end_stream=True)
<del> self.http.send_data(stream_id=self.stream_id, data=data, end_stream=False)
|
# module: examples.http3_client
class WebSocket:
+ def close(self, code=1000, reason="") -> None:
- def close(self, code=1000, reason=""):
<0> """
<1> Perform the closing handshake.
<2> """
<3> data = self.websocket.send(
<4> wsproto.events.ConnectionClose(code=code, reason=reason)
<5> )
<6> self.http.send_data(stream_id=self.stream_id, data=data, end_stream=False)
<7> self.transmit()
<8>
|
===========unchanged ref 0===========
at: aioquic.h0.connection.H0Connection
send_data(stream_id: int, data: bytes, end_stream: bool) -> None
at: aioquic.h3.connection.H3Connection
send_data(stream_id: int, data: bytes, end_stream: bool) -> None
at: examples.http3_client.WebSocket.__init__
self.http = http
self.stream_id = stream_id
self.transmit = transmit
self.websocket = wsproto.Connection(wsproto.ConnectionType.CLIENT)
|
examples.http3_client/run
|
Modified
|
aiortc~aioquic
|
def64d650cf9267e74b82520d6264deb06650872
|
[http3 client] make client perform websocket close
|
<26>:<add> await ws.close()
|
# module: examples.http3_client
def run(configuration: QuicConfiguration, url: str, websocket: bool) -> None:
<0> # parse URL
<1> parsed = urlparse(url)
<2> assert parsed.scheme == "https", "Only HTTPS URLs are supported."
<3> if ":" in parsed.netloc:
<4> host, port_str = parsed.netloc.split(":")
<5> port = int(port_str)
<6> else:
<7> host = parsed.netloc
<8> port = 443
<9>
<10> async with connect(
<11> host,
<12> port,
<13> configuration=configuration,
<14> create_protocol=HttpClient,
<15> session_ticket_handler=save_session_ticket,
<16> ) as client:
<17> client = cast(HttpClient, client)
<18>
<19> if websocket:
<20> ws = await client.websocket(
<21> parsed.netloc, parsed.path, subprotocols=["chat", "superchat"]
<22> )
<23> await ws.send("Hello, WebSocket!")
<24> message = await ws.recv()
<25> print(message)
<26> else:
<27> # perform request
<28> start = time.time()
<29> http_events = await client.get(parsed.netloc, parsed.path)
<30> elapsed = time.time() - start
<31>
<32> # print speed
<33> octets = 0
<34> for http_event in http_events:
<35> if isinstance(http_event, DataReceived):
<36> octets += len(http_event.data)
<37> logger.info(
<38> "Received %d bytes in %.1f s (%.3f Mbps)"
<39> % (octets, elapsed, octets * 8 / elapsed / 1000000)
<40> )
<41>
<42> # print response
<43> for http_event in http_events:
<44> if isinstance(http_event, ResponseReceived):
<45> headers = b""
<46> for k, v in http_event.headers:
<47> headers += k + b": " + v + b"\r\n"
<48> if headers:
<49> sys.stderr.buffer.write(headers +</s>
|
===========below chunk 0===========
# module: examples.http3_client
def run(configuration: QuicConfiguration, url: str, websocket: bool) -> None:
# offset: 1
sys.stderr.buffer.flush()
elif isinstance(http_event, DataReceived):
sys.stdout.buffer.write(http_event.data)
sys.stdout.buffer.flush()
===========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.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[int]=field(
default_factory=lambda: [QuicProtocolVersion.DRAFT_22]
))
at: examples.http3_client
logger = logging.getLogger("client")
HttpClient(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None, /, *, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None)
save_session_ticket(ticket)
at: examples.http3_client.HttpClient
get(authority: str, path: str) -> Deque[HttpEvent]
websocket(authority: str, path: str, subprotocols: List[str]=[]) -> WebSocket
at: examples.http3_client.WebSocket
close(code=1000, reason="") -> None
close(self, code=1000, reason="") -> None
recv() -> str
send(message: str)
===========unchanged ref 1===========
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
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__ = ()
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 WebSocket:
+ def close(self, code=1000, reason="") -> None:
- def close(self, code=1000, reason=""):
"""
Perform the closing handshake.
"""
data = self.websocket.send(
+ wsproto.events.CloseConnection(code=code, reason=reason)
- wsproto.events.ConnectionClose(code=code, reason=reason)
)
+ self.http.send_data(stream_id=self.stream_id, data=data, end_stream=True)
- self.http.send_data(stream_id=self.stream_id, data=data, end_stream=False)
self.transmit()
|
examples.http3_server/WebSocketHandler.__init__
|
Modified
|
aiortc~aioquic
|
6cf4df0ad3d4009c3ef1b10b5708bf09dfd18dfd
|
[http3 server] close websocket when ASGI app ends
|
<0>:<add> self.closed = False
|
# module: examples.http3_server
class WebSocketHandler:
def __init__(
self,
*,
connection: HttpConnection,
scope: Dict,
stream_id: int,
transmit: Callable[[], None],
):
<0> self.connection = connection
<1> self.queue: asyncio.Queue[Dict] = asyncio.Queue()
<2> self.scope = scope
<3> self.stream_id = stream_id
<4> self.transmit = transmit
<5> self.websocket: Optional[wsproto.Connection] = None
<6>
|
===========unchanged ref 0===========
at: asyncio.queues
Queue(maxsize: int=..., *, loop: Optional[AbstractEventLoop]=...)
at: examples.http3_server
HttpConnection = Union[H0Connection, H3Connection]
at: examples.http3_server.WebSocketHandler.send
self.closed = True
at: typing
Callable = _CallableType(collections.abc.Callable, 2)
Dict = _alias(dict, 2, inst=False, name='Dict')
|
examples.http3_server/WebSocketHandler.run_asgi
|
Modified
|
aiortc~aioquic
|
6cf4df0ad3d4009c3ef1b10b5708bf09dfd18dfd
|
[http3 server] close websocket when ASGI app ends
|
<2>:<add> try:
<add> await application(self.scope, self.receive, self.send)
<del> await application(self.scope, self.receive, self.send)
<3>:<add> finally:
<add> if not self.closed:
<add> await self.send({"type": "websocket.close", "code": 1000})
<4>:<del> self.connection.send_data(stream_id=self.stream_id, data=b"", end_stream=True)
<5>:<del> self.transmit()
<6>:<del>
|
# module: examples.http3_server
class WebSocketHandler:
def run_asgi(self, app: AsgiApplication) -> None:
<0> self.queue.put_nowait({"type": "websocket.connect"})
<1>
<2> await application(self.scope, self.receive, self.send)
<3>
<4> self.connection.send_data(stream_id=self.stream_id, data=b"", end_stream=True)
<5> self.transmit()
<6>
|
===========unchanged ref 0===========
at: asyncio.queues.Queue
__class_getitem__ = classmethod(GenericAlias)
put_nowait(item: _T) -> None
at: examples.http3_server
AsgiApplication = Callable
application = getattr(module, attr_str)
at: examples.http3_server.WebSocketHandler
receive() -> Dict
send(message: Dict)
send(self, message: Dict)
at: examples.http3_server.WebSocketHandler.__init__
self.queue: asyncio.Queue[Dict] = asyncio.Queue()
self.scope = scope
===========changed ref 0===========
# module: examples.http3_server
class WebSocketHandler:
def __init__(
self,
*,
connection: HttpConnection,
scope: Dict,
stream_id: int,
transmit: Callable[[], None],
):
+ self.closed = False
self.connection = connection
self.queue: asyncio.Queue[Dict] = asyncio.Queue()
self.scope = scope
self.stream_id = stream_id
self.transmit = transmit
self.websocket: Optional[wsproto.Connection] = None
|
examples.http3_server/WebSocketHandler.send
|
Modified
|
aiortc~aioquic
|
6cf4df0ad3d4009c3ef1b10b5708bf09dfd18dfd
|
[http3 server] close websocket when ASGI app ends
|
<1>:<add> end_stream = False
<18>:<add> end_stream = True
<30>:<add> stream_id=self.stream_id, data=data, end_stream=end_stream
<del> stream_id=self.stream_id, data=data, end_stream=False
<32>:<add> if end_stream:
<add> self.closed = True
<del>
|
# module: examples.http3_server
class WebSocketHandler:
def send(self, message: Dict):
<0> data = b""
<1> if message["type"] == "websocket.accept":
<2> subprotocol = message.get("subprotocol")
<3>
<4> self.websocket = wsproto.Connection(wsproto.ConnectionType.SERVER)
<5>
<6> headers = [
<7> (b":status", b"200"),
<8> (b"server", b"aioquic"),
<9> (b"date", formatdate(time.time(), usegmt=True).encode()),
<10> ]
<11> if subprotocol is not None:
<12> headers.append((b"sec-websocket-protocol", subprotocol.encode("utf8")))
<13> self.connection.send_headers(stream_id=self.stream_id, headers=headers)
<14> elif message["type"] == "websocket.close":
<15> data = self.websocket.send(
<16> wsproto.events.CloseConnection(code=message["code"])
<17> )
<18> elif message["type"] == "websocket.send":
<19> if message.get("text") is not None:
<20> data = self.websocket.send(
<21> wsproto.events.TextMessage(data=message["text"])
<22> )
<23> elif message.get("bytes") is not None:
<24> data = self.websocket.send(
<25> wsproto.events.Message(data=message["bytes"])
<26> )
<27>
<28> if data:
<29> self.connection.send_data(
<30> stream_id=self.stream_id, data=data, end_stream=False
<31> )
<32>
<33> self.transmit()
<34>
|
===========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: asyncio.queues.Queue
get() -> _T
at: email.utils
formatdate(timeval: Optional[float]=..., localtime: bool=..., usegmt: bool=...) -> str
at: examples.http3_server.WebSocketHandler.__init__
self.connection = connection
self.queue: asyncio.Queue[Dict] = asyncio.Queue()
self.stream_id = stream_id
self.websocket: Optional[wsproto.Connection] = None
at: time
time() -> float
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
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 WebSocketHandler:
def __init__(
self,
*,
connection: HttpConnection,
scope: Dict,
stream_id: int,
transmit: Callable[[], None],
):
+ self.closed = False
self.connection = connection
self.queue: asyncio.Queue[Dict] = asyncio.Queue()
self.scope = scope
self.stream_id = stream_id
self.transmit = transmit
self.websocket: Optional[wsproto.Connection] = None
===========changed ref 1===========
# module: examples.http3_server
class WebSocketHandler:
def run_asgi(self, app: AsgiApplication) -> None:
self.queue.put_nowait({"type": "websocket.connect"})
+ try:
+ await application(self.scope, self.receive, self.send)
- await application(self.scope, self.receive, self.send)
+ finally:
+ if not self.closed:
+ await self.send({"type": "websocket.close", "code": 1000})
- self.connection.send_data(stream_id=self.stream_id, data=b"", end_stream=True)
- self.transmit()
-
|
examples.http3_server/HttpServerProtocol.http_event_received
|
Modified
|
aiortc~aioquic
|
6cf4df0ad3d4009c3ef1b10b5708bf09dfd18dfd
|
[http3 server] close websocket when ASGI app ends
|
<2>:<add> http_version = "0.9" if isinstance(self._http, H0Connection) else "3"
<21>:<add> path = path_bytes.decode("utf8")
<32>:<add> "http_version": http_version,
<del> "http_version": "0.9"
<33>:<del> if isinstance(self._http, H0Connection)
<34>:<del> else "3",
<36>:<add> "path": path,
<del> "path": path_bytes.decode("utf8"),
|
# module: examples.http3_server
class HttpServerProtocol(QuicConnectionProtocol):
def http_event_received(self, event: HttpEvent) -> None:
<0> if isinstance(event, RequestReceived) and event.stream_id not in self._handlers:
<1> headers = []
<2> raw_path = b""
<3> method = ""
<4> protocol = None
<5> for header, value in event.headers:
<6> if header == b":authority":
<7> headers.append((b"host", value))
<8> elif header == b":method":
<9> method = value.decode("utf8")
<10> elif header == b":path":
<11> raw_path = value
<12> elif header == b":protocol":
<13> protocol = value.decode("utf8")
<14> elif header and not header.startswith(b":"):
<15> headers.append((header, value))
<16>
<17> if b"?" in raw_path:
<18> path_bytes, query_string = raw_path.split(b"?", maxsplit=1)
<19> else:
<20> path_bytes, query_string = raw_path, b""
<21>
<22> handler: Handler
<23> if method == "CONNECT" and protocol == "websocket":
<24> subprotocols: List[str] = []
<25> for header, value in event.headers:
<26> if header == b"sec-websocket-protocol":
<27> subprotocols = [
<28> x.strip() for x in value.decode("utf8").split(",")
<29> ]
<30> scope = {
<31> "headers": headers,
<32> "http_version": "0.9"
<33> if isinstance(self._http, H0Connection)
<34> else "3",
<35> "method": method,
<36> "path": path_bytes.decode("utf8"),
<37> "query_string": query_string,
<38> "raw_path": raw_path,
<39> "root_path": "",
<40> "scheme": "wss",
<41> "subprotocols": subprotocols,
<42> "type": "websocket",
<43> }
<44> handler = WebSocketHandler</s>
|
===========below chunk 0===========
# module: examples.http3_server
class HttpServerProtocol(QuicConnectionProtocol):
def http_event_received(self, event: HttpEvent) -> None:
# offset: 1
connection=self._http,
scope=scope,
stream_id=event.stream_id,
transmit=self.transmit,
)
else:
scope = {
"headers": headers,
"http_version": "0.9"
if isinstance(self._http, H0Connection)
else "3",
"method": method,
"path": path_bytes.decode("utf8"),
"query_string": query_string,
"raw_path": raw_path,
"root_path": "",
"scheme": "https",
"type": "http",
}
handler = HttpRequestHandler(
connection=self._http,
scope=scope,
stream_id=event.stream_id,
transmit=self.transmit,
)
self._handlers[event.stream_id] = handler
asyncio.ensure_future(handler.run_asgi(application))
elif isinstance(event, DataReceived) and event.stream_id in self._handlers:
handler = self._handlers[event.stream_id]
handler.http_event_received(event)
===========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)
transmit() -> None
at: aioquic.h0.connection
H0Connection(quic: QuicConnection)
at: aioquic.h3.events
HttpEvent()
RequestReceived(headers: Headers, stream_id: int, stream_ended: bool)
at: asyncio.tasks
ensure_future(coro_or_future: _FutureT[_T], *, loop: Optional[AbstractEventLoop]=...) -> Future[_T]
at: examples.http3_server
HttpConnection = Union[H0Connection, H3Connection]
HttpRequestHandler(*, connection: HttpConnection, scope: Dict, stream_id: int, transmit: Callable[[], None])
WebSocketHandler(*, connection: HttpConnection, scope: Dict, stream_id: int, transmit: Callable[[], None])
Handler = Union[HttpRequestHandler, WebSocketHandler]
application = getattr(module, attr_str)
at: examples.http3_server.HttpServerProtocol.quic_event_received
self._http = H3Connection(self._quic)
self._http = H0Connection(self._quic)
at: typing
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: examples.http3_server
class WebSocketHandler:
def __init__(
self,
*,
connection: HttpConnection,
scope: Dict,
stream_id: int,
transmit: Callable[[], None],
):
+ self.closed = False
self.connection = connection
self.queue: asyncio.Queue[Dict] = asyncio.Queue()
self.scope = scope
self.stream_id = stream_id
self.transmit = transmit
self.websocket: Optional[wsproto.Connection] = None
===========changed ref 1===========
# module: examples.http3_server
class WebSocketHandler:
def run_asgi(self, app: AsgiApplication) -> None:
self.queue.put_nowait({"type": "websocket.connect"})
+ try:
+ await application(self.scope, self.receive, self.send)
- await application(self.scope, self.receive, self.send)
+ finally:
+ if not self.closed:
+ await self.send({"type": "websocket.close", "code": 1000})
- self.connection.send_data(stream_id=self.stream_id, data=b"", end_stream=True)
- self.transmit()
-
===========changed ref 2===========
# module: examples.http3_server
class WebSocketHandler:
def send(self, message: Dict):
data = b""
+ end_stream = False
if message["type"] == "websocket.accept":
subprotocol = message.get("subprotocol")
self.websocket = wsproto.Connection(wsproto.ConnectionType.SERVER)
headers = [
(b":status", b"200"),
(b"server", b"aioquic"),
(b"date", formatdate(time.time(), usegmt=True).encode()),
]
if subprotocol is not None:
headers.append((b"sec-websocket-protocol", subprotocol.encode("utf8")))
self.connection.send_headers(stream_id=self.stream_id, headers=headers)
elif message["type"] == "websocket.close":
data = self.websocket.send(
wsproto.events.CloseConnection(code=message["code"])
)
+ end_stream = True
elif message["type"] == "websocket.send":
if message.get("text") is not None:
data = self.websocket.send(
wsproto.events.TextMessage(data=message["text"])
)
elif message.get("bytes") is not None:
data = self.websocket.send(
wsproto.events.Message(data=message["bytes"])
)
if data:
self.connection.send_data(
+ stream_id=self.stream_id, data=data, end_stream=end_stream
- stream_id=self.stream_id, data=data, end_stream=False
)
+ if end_stream:
+ self.closed = True
-
self.transmit()
|
examples.http3_server/WebSocketHandler.websocket_event_received
|
Modified
|
aiortc~aioquic
|
c0734e58aaf648a92111ab7d885edfb8d27b138c
|
[http3 server] handle websocket close
|
<4>:<add> elif isinstance(event, wsproto.events.CloseConnection):
<add> self.queue.put_nowait({"type": "websocket.disconnect", "code": event.code})
|
# module: examples.http3_server
class WebSocketHandler:
def websocket_event_received(self, event: wsproto.events.Event) -> None:
<0> if isinstance(event, wsproto.events.TextMessage):
<1> self.queue.put_nowait({"type": "websocket.receive", "text": event.data})
<2> elif isinstance(event, wsproto.events.Message):
<3> self.queue.put_nowait({"type": "websocket.receive", "bytes": event.data})
<4>
|
===========unchanged ref 0===========
at: asyncio.queues.Queue
__class_getitem__ = classmethod(GenericAlias)
put_nowait(item: _T) -> None
at: examples.http3_server.WebSocketHandler.__init__
self.queue: asyncio.Queue[Dict] = asyncio.Queue()
|
examples.demo/ws
|
Modified
|
aiortc~aioquic
|
c0734e58aaf648a92111ab7d885edfb8d27b138c
|
[http3 server] handle websocket close
|
<9>:<add> try:
<add> while True:
<add> message = await websocket.receive_text()
<del> message = await websocket.receive_text()
<10>:<add> await websocket.send_text(message)
<del> await websocket.send_text(message)
<11>:<add> except WebSocketDisconnect:
<add> pass
<del> await websocket.close()
|
# module: examples.demo
@app.websocket_route("/ws")
async def ws(websocket):
<0> """
<1> WebSocket echo endpoint.
<2> """
<3> if "chat" in websocket.scope["subprotocols"]:
<4> subprotocol = "chat"
<5> else:
<6> subprotocol = None
<7> await websocket.accept(subprotocol=subprotocol)
<8>
<9> message = await websocket.receive_text()
<10> await websocket.send_text(message)
<11> await websocket.close()
<12>
|
===========unchanged ref 0===========
at: examples.demo
app = Starlette()
===========changed ref 0===========
# module: examples.http3_server
class WebSocketHandler:
def websocket_event_received(self, event: wsproto.events.Event) -> None:
if isinstance(event, wsproto.events.TextMessage):
self.queue.put_nowait({"type": "websocket.receive", "text": event.data})
elif isinstance(event, wsproto.events.Message):
self.queue.put_nowait({"type": "websocket.receive", "bytes": event.data})
+ elif isinstance(event, wsproto.events.CloseConnection):
+ self.queue.put_nowait({"type": "websocket.disconnect", "code": event.code})
|
examples.http3_client/run
|
Modified
|
aiortc~aioquic
|
d6222796d6b492746f5becfd9ff51656e7bab989
|
[http3 client] send / receive on websocket twice
|
<23>:<add>
<add> # send some messages and receive reply
<add> for i in range(2):
<add> message = "Hello {}, WebSocket!".format(i)
<add> print("> " + message)
<add> await ws.send(message)
<add>
<del> await ws.send("Hello, WebSocket!")
<24>:<add> message = await ws.recv()
<del> message = await ws.recv()
<25>:<add> print("< " + message)
<del> print(message)
<26>:<add>
|
# module: examples.http3_client
def run(configuration: QuicConfiguration, url: str, websocket: bool) -> None:
<0> # parse URL
<1> parsed = urlparse(url)
<2> assert parsed.scheme == "https", "Only HTTPS URLs are supported."
<3> if ":" in parsed.netloc:
<4> host, port_str = parsed.netloc.split(":")
<5> port = int(port_str)
<6> else:
<7> host = parsed.netloc
<8> port = 443
<9>
<10> async with connect(
<11> host,
<12> port,
<13> configuration=configuration,
<14> create_protocol=HttpClient,
<15> session_ticket_handler=save_session_ticket,
<16> ) as client:
<17> client = cast(HttpClient, client)
<18>
<19> if websocket:
<20> ws = await client.websocket(
<21> parsed.netloc, parsed.path, subprotocols=["chat", "superchat"]
<22> )
<23> await ws.send("Hello, WebSocket!")
<24> message = await ws.recv()
<25> print(message)
<26> await ws.close()
<27> else:
<28> # perform request
<29> start = time.time()
<30> http_events = await client.get(parsed.netloc, parsed.path)
<31> elapsed = time.time() - start
<32>
<33> # print speed
<34> octets = 0
<35> for http_event in http_events:
<36> if isinstance(http_event, DataReceived):
<37> octets += len(http_event.data)
<38> logger.info(
<39> "Received %d bytes in %.1f s (%.3f Mbps)"
<40> % (octets, elapsed, octets * 8 / elapsed / 1000000)
<41> )
<42>
<43> # print response
<44> for http_event in http_events:
<45> if isinstance(http_event, ResponseReceived):
<46> headers = b""
<47> for k, v in http_event.headers:
<48> headers += k + b": " + v + b"\r\n"
<49> if headers:
<50> sys.</s>
|
===========below chunk 0===========
# module: examples.http3_client
def run(configuration: QuicConfiguration, url: str, websocket: bool) -> None:
# offset: 1
sys.stderr.buffer.flush()
elif isinstance(http_event, DataReceived):
sys.stdout.buffer.write(http_event.data)
sys.stdout.buffer.flush()
===========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.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[int]=field(
default_factory=lambda: [QuicProtocolVersion.DRAFT_22]
))
at: examples.http3_client
logger = logging.getLogger("client")
HttpClient(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None, /, *, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None)
save_session_ticket(ticket)
at: examples.http3_client.HttpClient
get(authority: str, path: str) -> Deque[HttpEvent]
websocket(authority: str, path: str, subprotocols: List[str]=[]) -> WebSocket
at: examples.http3_client.WebSocket
close(code=1000, reason="") -> None
recv() -> str
send(message: str)
===========unchanged ref 1===========
at: logging.Logger
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
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: urllib.parse
urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult
urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes
|
examples.http3_client/run
|
Modified
|
aiortc~aioquic
|
2f7f566893bc79583c49ba22813479a20097e7ad
|
[http3 client] open a WebSocket if given a wss:// URL
|
<2>:<add> assert parsed.scheme in (
<add> "https",
<add> "wss",
<add> ), "Only https:// or wss:// URLs are supported."
<del> assert parsed.scheme == "https", "Only HTTPS URLs are supported."
<19>:<add> if parsed.scheme == "wss":
<del> if websocket:
|
# module: examples.http3_client
+ def run(configuration: QuicConfiguration, url: str) -> None:
- def run(configuration: QuicConfiguration, url: str, websocket: bool) -> None:
<0> # parse URL
<1> parsed = urlparse(url)
<2> assert parsed.scheme == "https", "Only HTTPS URLs are supported."
<3> if ":" in parsed.netloc:
<4> host, port_str = parsed.netloc.split(":")
<5> port = int(port_str)
<6> else:
<7> host = parsed.netloc
<8> port = 443
<9>
<10> async with connect(
<11> host,
<12> port,
<13> configuration=configuration,
<14> create_protocol=HttpClient,
<15> session_ticket_handler=save_session_ticket,
<16> ) as client:
<17> client = cast(HttpClient, client)
<18>
<19> if websocket:
<20> ws = await client.websocket(
<21> parsed.netloc, parsed.path, subprotocols=["chat", "superchat"]
<22> )
<23>
<24> # send some messages and receive reply
<25> for i in range(2):
<26> message = "Hello {}, WebSocket!".format(i)
<27> print("> " + message)
<28> await ws.send(message)
<29>
<30> message = await ws.recv()
<31> print("< " + message)
<32>
<33> await ws.close()
<34> else:
<35> # perform request
<36> start = time.time()
<37> http_events = await client.get(parsed.netloc, parsed.path)
<38> elapsed = time.time() - start
<39>
<40> # print speed
<41> octets = 0
<42> for http_event in http_events:
<43> if isinstance(http_event, DataReceived):
<44> octets += len(http_event.data)
<45> logger.info(
<46> "Received %d bytes in %.1f s (%.3f Mbps)"
<47> % (octets, elapsed, octets * 8 / elapsed / 1000000)
<48> )
<49>
<50> # print response
<51> for http_</s>
|
===========below chunk 0===========
# module: examples.http3_client
+ def run(configuration: QuicConfiguration, url: str) -> None:
- def run(configuration: QuicConfiguration, url: str, websocket: bool) -> None:
# offset: 1
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()
===========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.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[int]=field(
default_factory=lambda: [QuicProtocolVersion.DRAFT_22]
))
at: examples.http3_client
logger = logging.getLogger("client")
HttpClient(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None, /, *, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None)
save_session_ticket(ticket)
at: examples.http3_client.HttpClient
get(authority: str, path: str) -> Deque[HttpEvent]
websocket(authority: str, path: str, subprotocols: List[str]=[]) -> WebSocket
at: examples.http3_client.WebSocket
close(code=1000, reason="") -> None
recv() -> str
send(message: str)
===========unchanged ref 1===========
at: logging.Logger
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: sys
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__ = ()
at: urllib.parse
urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult
urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes
|
examples.interop/test_migration
|
Modified
|
aiortc~aioquic
|
c6572d4aa0706dce676bbf1bc5fcc8bf8e4f58df
|
[interop] replace transport during migration test
|
<6>:<add> # change connection ID and replace transport
<del> # change connection ID
<8>:<add> protocol._transport.close()
<add> await loop.create_datagram_endpoint(lambda: protocol, local_addr=("::", 0))
<del> await asyncio.sleep(0.1)
|
# module: examples.interop
def test_migration(server: Server, configuration: QuicConfiguration):
<0> async with connect(
<1> server.host, server.port, configuration=configuration
<2> ) as protocol:
<3> # cause some traffic
<4> await protocol.ping()
<5>
<6> # change connection ID
<7> protocol.change_connection_id()
<8> await asyncio.sleep(0.1)
<9>
<10> # cause more traffic
<11> await protocol.ping()
<12>
<13> # check log
<14> dcids = set()
<15> for stamp, category, event, data in configuration.quic_logger.to_dict()[
<16> "traces"
<17> ][0]["events"]:
<18> if (
<19> category == "TRANSPORT"
<20> and event == "PACKET_RECEIVED"
<21> and data["packet_type"] == "1RTT"
<22> ):
<23> dcids.add(data["header"]["dcid"])
<24> if len(dcids) == 2:
<25> server.result |= Result.M
<26>
|
===========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.asyncio.protocol.QuicConnectionProtocol.__init__
self._transport: Optional[asyncio.DatagramTransport] = None
at: aioquic.asyncio.protocol.QuicConnectionProtocol.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[int]=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[int] = field(
default_factory=lambda: [QuicProtocolVersion.DRAFT_22]
)
at: aioquic.quic.logger.QuicLogger
to_dict() -> Dict[str, Any]
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: asyncio.transports.BaseTransport
__slots__ = ('_extra',)
close() -> None
at: examples.interop
Server(name: str, host: str, port: int=4433, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)))
loop = asyncio.get_event_loop()
at: examples.interop.Server
name: str
host: str
port: int = 4433
retry_port: Optional[int] = 4434
path: str = "/"
result: Result = field(default_factory=lambda: Result(0))
|
examples.interop/run
|
Modified
|
aiortc~aioquic
|
ca36fee9fd982f3c60e4b1449da52f4466def69a
|
[interop] add throughput test
|
<9>:<add> if test_name == "test_throughput":
<add> timeout = 60
<add> else:
<add> timeout = 5
<10>:<add> await asyncio.wait_for(
<add> test_func(server, configuration), timeout=timeout
<del> await asyncio.wait_for(test_func(server, configuration), timeout=5)
<11>:<add> )
|
# module: examples.interop
def run(servers, tests, secrets_log_file=None) -> None:
<0> for server in servers:
<1> for test_name, test_func in tests:
<2> print("\n=== %s %s ===\n" % (server.name, test_name))
<3> configuration = QuicConfiguration(
<4> alpn_protocols=["hq-22", "h3-22"],
<5> is_client=True,
<6> quic_logger=QuicLogger(),
<7> secrets_log_file=secrets_log_file,
<8> )
<9> try:
<10> await asyncio.wait_for(test_func(server, configuration), timeout=5)
<11> except Exception as exc:
<12> print(exc)
<13> print("")
<14> print_result(server)
<15>
<16> # print summary
<17> if len(servers) > 1:
<18> print("SUMMARY")
<19> for server in servers:
<20> print_result(server)
<21>
|
===========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.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[int] = field(
default_factory=lambda: [QuicProtocolVersion.DRAFT_22]
)
at: examples.interop.Server
name: str
host: str
port: int = 4433
http3: bool = True
retry_port: Optional[int] = 4434
path: str = "/"
result: Result = field(default_factory=lambda: Result(0))
at: requests.api
get(url: Union[Text, bytes], params: Optional[
Union[
SupportsItems[_ParamsMappingKeyType, _ParamsMappingValueType],
Tuple[_ParamsMappingKeyType, _ParamsMappingValueType],
Iterable[Tuple[_ParamsMappingKeyType, _ParamsMappingValueType]],
Union[Text, bytes],
]
]=..., **kwargs) -> Response
at: requests.models.Response
__attrs__ = [
"_content",
"status_code",
"headers",
"url",
"history",
"encoding",
"reason",
"cookies",
"elapsed",
"request",
]
===========unchanged ref 1===========
at: time
time() -> float
===========changed ref 0===========
# module: examples.interop
@dataclass
class Server:
name: str
host: str
port: int = 4433
+ http3: bool = True
retry_port: Optional[int] = 4434
path: str = "/"
result: Result = field(default_factory=lambda: Result(0))
===========changed ref 1===========
# module: examples.interop
+ def test_throughput(server: Server, configuration: QuicConfiguration):
+ failures = 0
+
+ for size in [5000000, 10000000]:
+ print("Testing %d bytes download" % size)
+ path = "/%d" % size
+
+ # perform HTTP request over TCP
+ start = time.time()
+ response = requests.get("https://" + server.host + path, verify=False)
+ tcp_octets = len(response.content)
+ tcp_elapsed = time.time() - start
+ assert tcp_octets == size, "HTTP/TCP response size mismatch"
+
+ # perform HTTP request over QUIC
+ if server.http3:
+ configuration.alpn_protocols = ["h3-22"]
+ else:
+ configuration.alpn_protocols = ["hq-22"]
+ start = time.time()
+ async with connect(
+ server.host,
+ server.port,
+ configuration=configuration,
+ create_protocol=HttpClient,
+ ) as protocol:
+ protocol = cast(HttpClient, protocol)
+
+ http_events = await protocol.get(server.host, path)
+ quic_elapsed = time.time() - start
+ quic_octets = 0
+ for http_event in http_events:
+ if isinstance(http_event, DataReceived):
+ quic_octets += len(http_event.data)
+ assert quic_octets == size, "HTTP/QUIC response size mismatch"
+
+ print(" - HTTP/TCP completed in %.3f s" % tcp_elapsed)
+ print(" - HTTP/QUIC completed in %.3f s" % quic_elapsed)
+
+ if quic_elapsed > 1.1 * tcp_elapsed:
+ failures += 1
+ print(" => FAIL")
+ else:
+ print(" => PASS")
+
+ if failures == 0:
+ server.result |= Result.T
+
===========changed ref 2===========
# module: examples.interop
SERVERS = [
Server("aioquic", "quic.aiortc.org"),
Server("ats", "quic.ogre.com"),
Server("f5", "f5quic.com", retry_port=4433),
Server("gquic", "quic.rocks", retry_port=None),
Server("lsquic", "http3-test.litespeedtech.com"),
Server("mvfst", "fb.mvfst.net"),
Server("ngtcp2", "nghttp2.org"),
Server("ngx_quic", "cloudflare-quic.com", port=443, retry_port=443),
Server("pandora", "pandora.cm.in.tum.de"),
Server("picoquic", "test.privateoctopus.com"),
+ Server("quant", "quant.eggert.org", http3=False),
- Server("quant", "quant.eggert.org"),
Server("quic-go", "quic.seemann.io", port=443, retry_port=443),
Server("quiche", "quic.tech", port=8443, retry_port=4433),
Server("quicker", "quicker.edm.uhasselt.be", retry_port=None),
Server("quicly", "kazuhooku.com"),
Server("quinn", "ralith.com"),
Server("winquic", "quic.westus.cloudapp.azure.com"),
]
|
examples.demo/echo
|
Modified
|
aiortc~aioquic
|
ee8d4319d7e99cbeb62d0c6ca1ce4de96d66d700
|
[http3 demo] return the same content type as the request
|
<4>:<add> media_type = request.headers.get("content-type")
<add> return Response(content, media_type=media_type)
<del> return Response(content)
|
# module: examples.demo
@app.route("/echo", methods=["POST"])
async def echo(request):
<0> """
<1> HTTP echo endpoint.
<2> """
<3> content = await request.body()
<4> return Response(content)
<5>
|
===========unchanged ref 0===========
at: examples.demo
app = Starlette()
|
examples.http3_client/HttpClient.websocket
|
Modified
|
aiortc~aioquic
|
62df497eaf4a6b8bd28dbf8d8f801daa452ea062
|
Fix WebSocket example
|
<13>:<add> (b"sec-websocket-version", b"13"),
|
# module: examples.http3_client
class HttpClient(QuicConnectionProtocol):
def websocket(
self, authority: str, path: str, subprotocols: List[str] = []
) -> WebSocket:
<0> stream_id = self._quic.get_next_available_stream_id()
<1> websocket = WebSocket(
<2> http=self._http, stream_id=stream_id, transmit=self.transmit
<3> )
<4>
<5> self._websockets[stream_id] = websocket
<6>
<7> headers = [
<8> (b":method", b"CONNECT"),
<9> (b":scheme", b"https"),
<10> (b":authority", authority.encode("utf8")),
<11> (b":path", path.encode("utf8")),
<12> (b":protocol", b"websocket"),
<13> ]
<14> if subprotocols:
<15> headers.append(
<16> (b"sec-websocket-protocol", ", ".join(subprotocols).encode("utf8"))
<17> )
<18> self._http.send_headers(stream_id=stream_id, headers=headers)
<19>
<20> self.transmit()
<21>
<22> return websocket
<23>
|
===========unchanged ref 0===========
at: aioquic.asyncio.protocol.QuicConnectionProtocol
transmit() -> None
at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__
self._quic = quic
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.quic.connection.QuicConnection
get_next_available_stream_id(is_unidirectional=False) -> int
at: examples.http3_client
WebSocket(http: HttpConnection, stream_id: int, transmit: Callable[[], None])
at: examples.http3_client.HttpClient.__init__
self._http = H3Connection(self._quic)
self._http: Optional[HttpConnection] = None
self._http = H0Connection(self._quic)
self._websockets: Dict[int, WebSocket] = {}
at: typing
List = _alias(list, 1, inst=False, name='List')
|
aioquic.quic.logger/QuicLogger.__init__
|
Modified
|
aiortc~aioquic
|
79f631193bdf5bc82ef88f9032a6f3b474d73bc1
|
[qlog] log more frames, set vantage point
|
<1>:<add> self._vantage_point = {"name": "aioquic", "type": "unknown"}
|
# module: aioquic.quic.logger
class QuicLogger:
def __init__(self) -> None:
<0> self._events: Deque[Tuple[float, str, str, Dict[str, Any]]] = deque()
<1>
|
===========unchanged ref 0===========
at: collections
deque(iterable: Iterable[_T]=..., maxlen: Optional[int]=...)
at: typing
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
Deque = _alias(collections.deque, 1, name='Deque')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: aioquic.quic.packet
- def pull_crypto_frame(buf: Buffer) -> QuicStreamFrame:
- offset = buf.pull_uint_var()
- length = buf.pull_uint_var()
- return QuicStreamFrame(offset=offset, data=buf.pull_bytes(length))
-
|
aioquic.quic.logger/QuicLogger.to_dict
|
Modified
|
aiortc~aioquic
|
79f631193bdf5bc82ef88f9032a6f3b474d73bc1
|
[qlog] log more frames, set vantage point
|
<20>:<add> "vantage_point": self._vantage_point,
|
# module: aioquic.quic.logger
class QuicLogger:
def to_dict(self) -> Dict[str, Any]:
<0> """
<1> Return the trace as a dictionary which can be written as JSON.
<2> """
<3> traces = []
<4> if self._events:
<5> reference_time = self._events[0][0]
<6> trace = {
<7> "common_fields": {"reference_time": "%d" % (reference_time * 1000)},
<8> "event_fields": ["relative_time", "CATEGORY", "EVENT_TYPE", "DATA"],
<9> "events": list(
<10> map(
<11> lambda event: (
<12> "%d" % ((event[0] - reference_time) * 1000),
<13> event[1],
<14> event[2],
<15> event[3],
<16> ),
<17> self._events,
<18> )
<19> ),
<20> }
<21> traces.append(trace)
<22>
<23> return {"qlog_version": "draft-00", "traces": traces}
<24>
|
===========unchanged ref 0===========
at: aioquic.quic.logger.QuicLogger.__init__
self._events: Deque[Tuple[float, str, str, Dict[str, Any]]] = deque()
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_crypto_frame(self, frame: QuicStreamFrame) -> Dict:
+ return {
+ "fin": frame.fin,
+ "frame_type": "CRYPTO",
+ "length": str(len(frame.data)),
+ "offset": str(frame.offset),
+ }
+
===========changed ref 1===========
# module: aioquic.quic.logger
class QuicLogger:
def __init__(self) -> None:
self._events: Deque[Tuple[float, str, str, Dict[str, Any]]] = deque()
+ self._vantage_point = {"name": "aioquic", "type": "unknown"}
===========changed ref 2===========
# module: aioquic.quic.packet
- def pull_crypto_frame(buf: Buffer) -> QuicStreamFrame:
- offset = buf.pull_uint_var()
- length = buf.pull_uint_var()
- return QuicStreamFrame(offset=offset, data=buf.pull_bytes(length))
-
|
aioquic.quic.connection/QuicConnection.__init__
|
Modified
|
aiortc~aioquic
|
79f631193bdf5bc82ef88f9032a6f3b474d73bc1
|
[qlog] log more frames, set vantage point
|
<14>:<add> if self._quic_logger is not None:
<add> self._quic_logger.start_trace(is_client=configuration.is_client)
|
# 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_ack_delay_exponent = 3
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_ack_delay_exponent = 3
</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>ConnectionId] = []
self._peer_token = b""
self._remote_ack_delay_exponent = 3
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_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</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> 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_max_stream_data_</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> 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.quic.connection/QuicConnection._handle_crypto_frame
|
Modified
|
aiortc~aioquic
|
79f631193bdf5bc82ef88f9032a6f3b474d73bc1
|
[qlog] log more frames, set vantage point
|
<3>:<add> offset = buf.pull_uint_var()
<add> length = buf.pull_uint_var()
<add> frame = QuicStreamFrame(offset=offset, data=buf.pull_bytes(length))
<add>
<add> # log frame
<add> if self._quic_logger is not None:
<add> context.quic_logger_frames.append(
<add> self._quic_logger.encode_crypto_frame(frame)
<add> )
<add>
<4>:<add> stream.add_frame(frame)
<del> stream.add_frame(pull_crypto_frame(buf))
|
# module: aioquic.quic.connection
class QuicConnection:
def _handle_crypto_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
<0> """
<1> Handle a CRYPTO frame.
<2> """
<3> stream = self._crypto_streams[context.epoch]
<4> stream.add_frame(pull_crypto_frame(buf))
<5> data = stream.pull_data()
<6> if data:
<7> # pass data to TLS layer
<8> try:
<9> self.tls.handle_message(data, self._crypto_buffers)
<10> self._push_crypto_data()
<11> except tls.Alert as exc:
<12> raise QuicConnectionError(
<13> error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description),
<14> frame_type=QuicFrameType.CRYPTO,
<15> reason_phrase=str(exc),
<16> )
<17>
<18> # parse transport parameters
<19> if (
<20> not self._parameters_received
<21> and self.tls.received_extensions is not None
<22> ):
<23> for ext_type, ext_data in self.tls.received_extensions:
<24> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:
<25> self._parse_transport_parameters(ext_data)
<26> self._parameters_received = True
<27> break
<28> assert (
<29> self._parameters_received
<30> ), "No QUIC transport parameters received"
<31>
<32> # update current epoch
<33> if not self._handshake_complete and self.tls.state in [
<34> tls.State.CLIENT_POST_HANDSHAKE,
<35> tls.State.SERVER_POST_HANDSHAKE,
<36> ]:
<37> self._handshake_complete = True
<38> self._loss.is_client_without_1rtt = False
<39> self._replenish_connection_ids()
<40> self._events.append(
<41> events.HandshakeCompleted(
<42> alpn_protocol=self.tls.alpn_negotiated</s>
|
===========below chunk 0===========
# module: aioquic.quic.connection
class QuicConnection:
def _handle_crypto_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
# offset: 1
early_data_accepted=self.tls.early_data_accepted,
session_resumed=self.tls.session_resumed,
)
)
self._unblock_streams(is_unidirectional=False)
self._unblock_streams(is_unidirectional=True)
self._logger.info(
"ALPN negotiated protocol %s", self.tls.alpn_negotiated
)
===========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, quic_logger_frames: Optional[List[Any]], time: float)
at: aioquic.quic.connection.QuicConnection
_assert_stream_can_send(frame_type: int, stream_id: int) -> None
_get_or_create_stream(frame_type: int, stream_id: int) -> QuicStream
_unblock_streams(is_unidirectional: bool) -> None
at: aioquic.quic.connection.QuicConnection.__init__
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
self._remote_max_data = 0
at: aioquic.quic.connection.QuicConnection._initialize
self.tls = tls.Context(is_client=self._is_client, logger=self._logger)
at: aioquic.quic.events.HandshakeCompleted
alpn_protocol: Optional[str]
early_data_accepted: bool
session_resumed: bool
at: aioquic.quic.stream.QuicStream.__init__
self.max_stream_data_remote = max_stream_data_remote
at: aioquic.tls.Context.__init__
self.alpn_negotiated: Optional[str] = None
self.early_data_accepted = False
at: aioquic.tls.Context._client_handle_encrypted_extensions
self.alpn_negotiated = encrypted_extensions.alpn_protocol
self.early_data_accepted = encrypted_extensions.early_data
===========unchanged ref 1===========
at: aioquic.tls.Context._server_handle_hello
self.alpn_negotiated = negotiate(
self.alpn_protocols,
peer_hello.alpn_protocols,
AlertHandshakeFailure("No common ALPN protocols"),
)
self.early_data_accepted = True
at: logging.LoggerAdapter
debug(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
===========changed ref 0===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_ping_frame(self) -> Dict:
+ return {"frame_type": "PING"}
+
===========changed ref 1===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_padding_frame(self) -> Dict:
+ return {"frame_type": "PADDING"}
+
===========changed ref 2===========
# module: aioquic.quic.logger
class QuicLogger:
+ def start_trace(self, is_client: bool) -> None:
+ self._vantage_point["type"] = "CLIENT" if is_client else "SERVER"
+
===========changed ref 3===========
# module: aioquic.quic.packet
- def pull_crypto_frame(buf: Buffer) -> QuicStreamFrame:
- offset = buf.pull_uint_var()
- length = buf.pull_uint_var()
- return QuicStreamFrame(offset=offset, data=buf.pull_bytes(length))
-
===========changed ref 4===========
# module: aioquic.quic.logger
class QuicLogger:
def __init__(self) -> None:
self._events: Deque[Tuple[float, str, str, Dict[str, Any]]] = deque()
+ self._vantage_point = {"name": "aioquic", "type": "unknown"}
===========changed ref 5===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_crypto_frame(self, frame: QuicStreamFrame) -> Dict:
+ return {
+ "fin": frame.fin,
+ "frame_type": "CRYPTO",
+ "length": str(len(frame.data)),
+ "offset": str(frame.offset),
+ }
+
===========changed ref 6===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_stream_frame(self, frame: QuicStreamFrame, stream_id: int) -> Dict:
+ return {
+ "fin": frame.fin,
+ "frame_type": "STREAM",
+ "id": str(stream_id),
+ "length": str(len(frame.data)),
+ "offset": str(frame.offset),
+ }
+
===========changed ref 7===========
# module: aioquic.quic.connection
- def write_crypto_frame(
- builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream
- ) -> None:
- buf = builder.buffer
-
- frame_overhead = 3 + size_uint_var(stream.next_send_offset)
- frame = stream.get_frame(builder.remaining_space - frame_overhead)
- if frame is not None:
- builder.start_frame(
- QuicFrameType.CRYPTO,
- stream.on_data_delivery,
- (frame.offset, frame.offset + len(frame.data)),
- )
- buf.push_uint_var(frame.offset)
- buf.push_uint16(len(frame.data) | 0x4000)
- buf.push_bytes(frame.data)
-
===========changed ref 8===========
# module: aioquic.quic.logger
class QuicLogger:
def to_dict(self) -> Dict[str, Any]:
"""
Return the trace as a dictionary which can be written as JSON.
"""
traces = []
if self._events:
reference_time = self._events[0][0]
trace = {
"common_fields": {"reference_time": "%d" % (reference_time * 1000)},
"event_fields": ["relative_time", "CATEGORY", "EVENT_TYPE", "DATA"],
"events": list(
map(
lambda event: (
"%d" % ((event[0] - reference_time) * 1000),
event[1],
event[2],
event[3],
),
self._events,
)
),
+ "vantage_point": self._vantage_point,
}
traces.append(trace)
return {"qlog_version": "draft-00", "traces": traces}
|
aioquic.quic.connection/QuicConnection._handle_padding_frame
|
Modified
|
aiortc~aioquic
|
79f631193bdf5bc82ef88f9032a6f3b474d73bc1
|
[qlog] log more frames, set vantage point
|
<1>:<add> Handle a PADDING frame.
<del> Handle a PADDING or PING frame.
<3>:<add> buf.seek(buf.capacity)
<del> pass
|
# module: aioquic.quic.connection
class QuicConnection:
def _handle_padding_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
<0> """
<1> Handle a PADDING or PING frame.
<2> """
<3> pass
<4>
|
===========unchanged ref 0===========
at: aioquic._buffer
Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)
at: aioquic.quic.connection
QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, quic_logger_frames: Optional[List[Any]], time: float)
at: aioquic.quic.connection.QuicConnection.__init__
self._quic_logger = configuration.quic_logger
at: aioquic.quic.connection.QuicReceiveContext
epoch: tls.Epoch
host_cid: bytes
network_path: QuicNetworkPath
quic_logger_frames: Optional[List[Any]]
time: float
===========changed ref 0===========
# module: aioquic.quic.connection
class QuicConnection:
+ def _handle_ping_frame(
+ self, context: QuicReceiveContext, frame_type: int, buf: Buffer
+ ) -> None:
+ """
+ Handle a PING frame.
+ """
+ # log frame
+ if self._quic_logger is not None:
+ context.quic_logger_frames.append(self._quic_logger.encode_ping_frame())
+
===========changed ref 1===========
# module: aioquic.quic.connection
class QuicConnection:
def _handle_crypto_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a CRYPTO frame.
"""
+ offset = buf.pull_uint_var()
+ length = buf.pull_uint_var()
+ frame = QuicStreamFrame(offset=offset, data=buf.pull_bytes(length))
+
+ # log frame
+ if self._quic_logger is not None:
+ context.quic_logger_frames.append(
+ self._quic_logger.encode_crypto_frame(frame)
+ )
+
stream = self._crypto_streams[context.epoch]
+ stream.add_frame(frame)
- stream.add_frame(pull_crypto_frame(buf))
data = stream.pull_data()
if data:
# pass data to TLS layer
try:
self.tls.handle_message(data, self._crypto_buffers)
self._push_crypto_data()
except tls.Alert as exc:
raise QuicConnectionError(
error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description),
frame_type=QuicFrameType.CRYPTO,
reason_phrase=str(exc),
)
# parse transport parameters
if (
not self._parameters_received
and self.tls.received_extensions is not None
):
for ext_type, ext_data in self.tls.received_extensions:
if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:
self._parse_transport_parameters(ext_data)
self._parameters_received = True
break
assert (
self._parameters_received
), "No QUIC transport parameters received"
# update current epoch
if not self._handshake_complete and self.tls.state in [
tls.State.CLIENT_POST_HANDSHAKE,
tls.State.SERVER_POST_</s>
===========changed ref 2===========
# module: aioquic.quic.connection
class QuicConnection:
def _handle_crypto_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
# offset: 1
<s>.tls.state in [
tls.State.CLIENT_POST_HANDSHAKE,
tls.State.SERVER_POST_HANDSHAKE,
]:
self._handshake_complete = True
self._loss.is_client_without_1rtt = False
self._replenish_connection_ids()
self._events.append(
events.HandshakeCompleted(
alpn_protocol=self.tls.alpn_negotiated,
early_data_accepted=self.tls.early_data_accepted,
session_resumed=self.tls.session_resumed,
)
)
self._unblock_streams(is_unidirectional=False)
self._unblock_streams(is_unidirectional=True)
self._logger.info(
"ALPN negotiated protocol %s", self.tls.alpn_negotiated
)
===========changed ref 3===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_ping_frame(self) -> Dict:
+ return {"frame_type": "PING"}
+
===========changed ref 4===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_padding_frame(self) -> Dict:
+ return {"frame_type": "PADDING"}
+
===========changed ref 5===========
# module: aioquic.quic.logger
class QuicLogger:
+ def start_trace(self, is_client: bool) -> None:
+ self._vantage_point["type"] = "CLIENT" if is_client else "SERVER"
+
===========changed ref 6===========
# module: aioquic.quic.packet
- def pull_crypto_frame(buf: Buffer) -> QuicStreamFrame:
- offset = buf.pull_uint_var()
- length = buf.pull_uint_var()
- return QuicStreamFrame(offset=offset, data=buf.pull_bytes(length))
-
===========changed ref 7===========
# module: aioquic.quic.logger
class QuicLogger:
def __init__(self) -> None:
self._events: Deque[Tuple[float, str, str, Dict[str, Any]]] = deque()
+ self._vantage_point = {"name": "aioquic", "type": "unknown"}
===========changed ref 8===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_crypto_frame(self, frame: QuicStreamFrame) -> Dict:
+ return {
+ "fin": frame.fin,
+ "frame_type": "CRYPTO",
+ "length": str(len(frame.data)),
+ "offset": str(frame.offset),
+ }
+
===========changed ref 9===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_stream_frame(self, frame: QuicStreamFrame, stream_id: int) -> Dict:
+ return {
+ "fin": frame.fin,
+ "frame_type": "STREAM",
+ "id": str(stream_id),
+ "length": str(len(frame.data)),
+ "offset": str(frame.offset),
+ }
+
===========changed ref 10===========
# module: aioquic.quic.connection
- def write_crypto_frame(
- builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream
- ) -> None:
- buf = builder.buffer
-
- frame_overhead = 3 + size_uint_var(stream.next_send_offset)
- frame = stream.get_frame(builder.remaining_space - frame_overhead)
- if frame is not None:
- builder.start_frame(
- QuicFrameType.CRYPTO,
- stream.on_data_delivery,
- (frame.offset, frame.offset + len(frame.data)),
- )
- buf.push_uint_var(frame.offset)
- buf.push_uint16(len(frame.data) | 0x4000)
- buf.push_bytes(frame.data)
-
|
aioquic.quic.connection/QuicConnection._handle_stream_frame
|
Modified
|
aiortc~aioquic
|
79f631193bdf5bc82ef88f9032a6f3b474d73bc1
|
[qlog] log more frames, set vantage point
|
<15>:<add>
<add> # log frame
<add> if self._quic_logger is not None:
<add> context.quic_logger_frames.append(
<add> self._quic_logger.encode_stream_frame(frame, stream_id=stream_id)
<add> )
|
# module: aioquic.quic.connection
class QuicConnection:
def _handle_stream_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
<0> """
<1> Handle a STREAM frame.
<2> """
<3> stream_id = buf.pull_uint_var()
<4> if frame_type & 4:
<5> offset = buf.pull_uint_var()
<6> else:
<7> offset = 0
<8> if frame_type & 2:
<9> length = buf.pull_uint_var()
<10> else:
<11> length = buf.capacity - buf.tell()
<12> frame = QuicStreamFrame(
<13> offset=offset, data=buf.pull_bytes(length), fin=bool(frame_type & 1)
<14> )
<15>
<16> # check stream direction
<17> self._assert_stream_can_receive(frame_type, stream_id)
<18>
<19> # check flow-control limits
<20> stream = self._get_or_create_stream(frame_type, stream_id)
<21> if offset + length > stream.max_stream_data_local:
<22> raise QuicConnectionError(
<23> error_code=QuicErrorCode.FLOW_CONTROL_ERROR,
<24> frame_type=frame_type,
<25> reason_phrase="Over stream data limit",
<26> )
<27> newly_received = max(0, offset + length - stream._recv_highest)
<28> if self._local_max_data_used + newly_received > self._local_max_data:
<29> raise QuicConnectionError(
<30> error_code=QuicErrorCode.FLOW_CONTROL_ERROR,
<31> frame_type=frame_type,
<32> reason_phrase="Over connection data limit",
<33> )
<34>
<35> stream.add_frame(frame)
<36> self._local_max_data_used += newly_received
<37>
|
===========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
QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str)
QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, quic_logger_frames: Optional[List[Any]], time: float)
at: aioquic.quic.connection.QuicConnection
_assert_stream_can_receive(frame_type: int, stream_id: int) -> None
_get_or_create_stream(frame_type: int, stream_id: int) -> QuicStream
at: aioquic.quic.connection.QuicConnection.__init__
self._local_max_data = MAX_DATA_WINDOW
self._local_max_data_used = 0
at: aioquic.quic.connection.QuicConnection._handle_stream_frame
offset = buf.pull_uint_var()
offset = 0
length = buf.pull_uint_var()
length = buf.capacity - buf.tell()
frame = QuicStreamFrame(
offset=offset, data=buf.pull_bytes(length), fin=bool(frame_type & 1)
)
stream = self._get_or_create_stream(frame_type, stream_id)
at: aioquic.quic.connection.QuicConnection._write_connection_limits
self._local_max_data *= 2
at: aioquic.quic.packet
QuicErrorCode(x: Union[str, bytes, bytearray], base: int)
QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
at: aioquic.quic.packet_builder
QuicDeliveryState()
at: aioquic.quic.recovery
QuicPacketSpace()
===========unchanged ref 1===========
at: aioquic.quic.stream.QuicStream
add_frame(frame: QuicStreamFrame) -> None
at: aioquic.quic.stream.QuicStream.__init__
self._recv_highest = 0 # the highest offset ever seen
at: aioquic.quic.stream.QuicStream.add_frame
self._recv_highest = frame_end
===========changed ref 0===========
# module: aioquic.quic.connection
class QuicConnection:
def _handle_padding_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
+ Handle a PADDING frame.
- Handle a PADDING or PING frame.
"""
+ buf.seek(buf.capacity)
- pass
===========changed ref 1===========
# module: aioquic.quic.connection
class QuicConnection:
+ def _handle_ping_frame(
+ self, context: QuicReceiveContext, frame_type: int, buf: Buffer
+ ) -> None:
+ """
+ Handle a PING frame.
+ """
+ # log frame
+ if self._quic_logger is not None:
+ context.quic_logger_frames.append(self._quic_logger.encode_ping_frame())
+
===========changed ref 2===========
# module: aioquic.quic.connection
class QuicConnection:
def _handle_crypto_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a CRYPTO frame.
"""
+ offset = buf.pull_uint_var()
+ length = buf.pull_uint_var()
+ frame = QuicStreamFrame(offset=offset, data=buf.pull_bytes(length))
+
+ # log frame
+ if self._quic_logger is not None:
+ context.quic_logger_frames.append(
+ self._quic_logger.encode_crypto_frame(frame)
+ )
+
stream = self._crypto_streams[context.epoch]
+ stream.add_frame(frame)
- stream.add_frame(pull_crypto_frame(buf))
data = stream.pull_data()
if data:
# pass data to TLS layer
try:
self.tls.handle_message(data, self._crypto_buffers)
self._push_crypto_data()
except tls.Alert as exc:
raise QuicConnectionError(
error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description),
frame_type=QuicFrameType.CRYPTO,
reason_phrase=str(exc),
)
# parse transport parameters
if (
not self._parameters_received
and self.tls.received_extensions is not None
):
for ext_type, ext_data in self.tls.received_extensions:
if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:
self._parse_transport_parameters(ext_data)
self._parameters_received = True
break
assert (
self._parameters_received
), "No QUIC transport parameters received"
# update current epoch
if not self._handshake_complete and self.tls.state in [
tls.State.CLIENT_POST_HANDSHAKE,
tls.State.SERVER_POST_</s>
===========changed ref 3===========
# module: aioquic.quic.connection
class QuicConnection:
def _handle_crypto_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
# offset: 1
<s>.tls.state in [
tls.State.CLIENT_POST_HANDSHAKE,
tls.State.SERVER_POST_HANDSHAKE,
]:
self._handshake_complete = True
self._loss.is_client_without_1rtt = False
self._replenish_connection_ids()
self._events.append(
events.HandshakeCompleted(
alpn_protocol=self.tls.alpn_negotiated,
early_data_accepted=self.tls.early_data_accepted,
session_resumed=self.tls.session_resumed,
)
)
self._unblock_streams(is_unidirectional=False)
self._unblock_streams(is_unidirectional=True)
self._logger.info(
"ALPN negotiated protocol %s", self.tls.alpn_negotiated
)
===========changed ref 4===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_ping_frame(self) -> Dict:
+ return {"frame_type": "PING"}
+
===========changed ref 5===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_padding_frame(self) -> Dict:
+ return {"frame_type": "PADDING"}
+
===========changed ref 6===========
# module: aioquic.quic.logger
class QuicLogger:
+ def start_trace(self, is_client: bool) -> None:
+ self._vantage_point["type"] = "CLIENT" if is_client else "SERVER"
+
===========changed ref 7===========
# module: aioquic.quic.packet
- def pull_crypto_frame(buf: Buffer) -> QuicStreamFrame:
- offset = buf.pull_uint_var()
- length = buf.pull_uint_var()
- return QuicStreamFrame(offset=offset, data=buf.pull_bytes(length))
-
===========changed ref 8===========
# module: aioquic.quic.logger
class QuicLogger:
def __init__(self) -> None:
self._events: Deque[Tuple[float, str, str, Dict[str, Any]]] = deque()
+ self._vantage_point = {"name": "aioquic", "type": "unknown"}
|
aioquic.quic.connection/QuicConnection._payload_received
|
Modified
|
aiortc~aioquic
|
79f631193bdf5bc82ef88f9032a6f3b474d73bc1
|
[qlog] log more frames, set vantage point
|
<29>:<del> if frame_type != QuicFrameType.PADDING:
<30>:<add> try:
<del> try:
<31>:<add> frame_handler(context, frame_type, buf)
<del> frame_handler(context, frame_type, buf)
<32>:<add> except BufferReadError:
<del> except BufferReadError:
<33>:<add> raise QuicConnectionError(
<del> raise QuicConnectionError(
<34>:<add> error_code=QuicErrorCode.FRAME_ENCODING_ERROR,
<del> error_code=QuicErrorCode.FRAME_ENCODING_ERROR,
<35>:<add> frame_type=frame_type,
<del> frame_type=frame_type,
<36>:<add> reason_phrase="Failed to parse frame",
<del> reason_phrase="Failed to parse frame",
<37>:<add> )
<del> )
|
# module: aioquic.quic.connection
class QuicConnection:
def _payload_received(
self, context: QuicReceiveContext, plain: bytes
) -> Tuple[bool, bool]:
<0> """
<1> Handle a QUIC packet payload.
<2> """
<3> buf = Buffer(data=plain)
<4>
<5> is_ack_eliciting = False
<6> is_probing = None
<7> while not buf.eof():
<8> frame_type = buf.pull_uint_var()
<9>
<10> # check frame type is known
<11> try:
<12> frame_handler, frame_epochs = self.__frame_handlers[frame_type]
<13> except IndexError:
<14> raise QuicConnectionError(
<15> error_code=QuicErrorCode.PROTOCOL_VIOLATION,
<16> frame_type=frame_type,
<17> reason_phrase="Unknown frame type",
<18> )
<19>
<20> # check frame is allowed for the epoch
<21> if context.epoch not in frame_epochs:
<22> raise QuicConnectionError(
<23> error_code=QuicErrorCode.PROTOCOL_VIOLATION,
<24> frame_type=frame_type,
<25> reason_phrase="Unexpected frame type",
<26> )
<27>
<28> # handle the frame
<29> if frame_type != QuicFrameType.PADDING:
<30> try:
<31> frame_handler(context, frame_type, buf)
<32> except BufferReadError:
<33> raise QuicConnectionError(
<34> error_code=QuicErrorCode.FRAME_ENCODING_ERROR,
<35> frame_type=frame_type,
<36> reason_phrase="Failed to parse frame",
<37> )
<38>
<39> # update ACK only / probing flags
<40> if frame_type not in NON_ACK_ELICITING_FRAME_TYPES:
<41> is_ack_eliciting = True
<42>
<43> if frame_type not in PROBING_FRAME_TYPES:
<44> is_probing = False
<45> elif is_probing is None:
<46> is_probing = True
<47>
<48> return is_ack_eliciting</s>
|
===========below chunk 0===========
# module: aioquic.quic.connection
class QuicConnection:
def _payload_received(
self, context: QuicReceiveContext, plain: bytes
) -> Tuple[bool, bool]:
# offset: 1
===========unchanged ref 0===========
at: aioquic._buffer
BufferReadError(*args: object)
Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)
at: aioquic._buffer.Buffer
seek(pos: int) -> None
at: aioquic.quic.connection
QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str)
QuicConnectionId(cid: bytes, sequence_number: int, stateless_reset_token: bytes=b"", was_sent: bool=False)
at: aioquic.quic.connection.QuicConnection.__init__
self._crypto_buffers: Dict[tls.Epoch, Buffer] = {}
self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}
self._host_cids = [
QuicConnectionId(
cid=os.urandom(8),
sequence_number=0,
stateless_reset_token=os.urandom(16),
was_sent=True,
)
]
self._host_cid_seq = 1
self._remote_active_connection_id_limit = 0
self._probe_pending = False
at: aioquic.quic.connection.QuicConnection._initialize
self._crypto_buffers = {
tls.Epoch.INITIAL: Buffer(capacity=4096),
tls.Epoch.HANDSHAKE: Buffer(capacity=4096),
tls.Epoch.ONE_RTT: Buffer(capacity=4096),
}
self._crypto_streams = {
tls.Epoch.INITIAL: QuicStream(),
tls.Epoch.HANDSHAKE: QuicStream(),
tls.Epoch.ONE_RTT: QuicStream(),
}
at: aioquic.quic.connection.QuicConnection._parse_transport_parameters
self._remote_active_connection_id_limit = (
quic_transport_parameters.active_connection_id_limit
)
===========unchanged ref 1===========
at: aioquic.quic.connection.QuicConnection._payload_received
buf = Buffer(data=plain)
frame_type = buf.pull_uint_var()
frame_handler, frame_epochs = self.__frame_handlers[frame_type]
at: aioquic.quic.connection.QuicConnection._write_application
self._probe_pending = False
at: aioquic.quic.connection.QuicConnection._write_handshake
self._probe_pending = False
at: aioquic.quic.packet
QuicErrorCode(x: Union[str, bytes, bytearray], base: int)
QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
pull_quic_transport_parameters(buf: Buffer) -> QuicTransportParameters
NON_ACK_ELICITING_FRAME_TYPES = frozenset(
[QuicFrameType.ACK, QuicFrameType.ACK_ECN, QuicFrameType.PADDING]
)
PROBING_FRAME_TYPES = frozenset(
[
QuicFrameType.PATH_CHALLENGE,
QuicFrameType.PATH_RESPONSE,
QuicFrameType.PADDING,
QuicFrameType.NEW_CONNECTION_ID,
]
)
at: aioquic.quic.stream.QuicStream
write(data: bytes, end_stream: bool=False) -> None
at: os
urandom(size: int, /) -> bytes
===========changed ref 0===========
# module: aioquic.quic.connection
class QuicConnection:
def _handle_padding_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
+ Handle a PADDING frame.
- Handle a PADDING or PING frame.
"""
+ buf.seek(buf.capacity)
- pass
===========changed ref 1===========
# module: aioquic.quic.connection
class QuicConnection:
+ def _handle_ping_frame(
+ self, context: QuicReceiveContext, frame_type: int, buf: Buffer
+ ) -> None:
+ """
+ Handle a PING frame.
+ """
+ # log frame
+ if self._quic_logger is not None:
+ context.quic_logger_frames.append(self._quic_logger.encode_ping_frame())
+
===========changed ref 2===========
# module: aioquic.quic.connection
class QuicConnection:
def _handle_stream_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a STREAM frame.
"""
stream_id = buf.pull_uint_var()
if frame_type & 4:
offset = buf.pull_uint_var()
else:
offset = 0
if frame_type & 2:
length = buf.pull_uint_var()
else:
length = buf.capacity - buf.tell()
frame = QuicStreamFrame(
offset=offset, data=buf.pull_bytes(length), fin=bool(frame_type & 1)
)
+
+ # log frame
+ if self._quic_logger is not None:
+ context.quic_logger_frames.append(
+ self._quic_logger.encode_stream_frame(frame, stream_id=stream_id)
+ )
# check stream direction
self._assert_stream_can_receive(frame_type, stream_id)
# check flow-control limits
stream = self._get_or_create_stream(frame_type, stream_id)
if offset + length > stream.max_stream_data_local:
raise QuicConnectionError(
error_code=QuicErrorCode.FLOW_CONTROL_ERROR,
frame_type=frame_type,
reason_phrase="Over stream data limit",
)
newly_received = max(0, offset + length - stream._recv_highest)
if self._local_max_data_used + newly_received > self._local_max_data:
raise QuicConnectionError(
error_code=QuicErrorCode.FLOW_CONTROL_ERROR,
frame_type=frame_type,
reason_phrase="Over connection data limit",
)
stream.add_frame(frame)
self._local_max_data_used += newly_received
|
aioquic.quic.connection/QuicConnection._write_application
|
Modified
|
aiortc~aioquic
|
79f631193bdf5bc82ef88f9032a6f3b474d73bc1
|
[qlog] log more frames, set vantage point
|
<21>:<del> builder.start_frame(
<22>:<del> QuicFrameType.ACK,
<23>:<del> self._on_ack_delivery,
<24>:<del> (space, space.largest_received_packet),
<25>:<del> )
<26>:<del> push_ack_frame(buf, space.ack_queue, 0)
<27>:<del> space.ack_at = None
<28>:<del>
<29>:<del> # log frame
<30>:<del> if self._quic_logger is not None:
<31>:<del> builder._packet.quic_logger_frames.append(
<32>:<del> self._quic_logger.encode_ack_frame(space.ack_queue, 0.0)
<33>:<del> )
<34>:<add> self._write_ack_frame(builder=builder, space=space)
|
# module: aioquic.quic.connection
class QuicConnection:
def _write_application(
self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float
) -> None:
<0> crypto_stream: Optional[QuicStream] = None
<1> if self._cryptos[tls.Epoch.ONE_RTT].send.is_valid():
<2> crypto = self._cryptos[tls.Epoch.ONE_RTT]
<3> crypto_stream = self._crypto_streams[tls.Epoch.ONE_RTT]
<4> packet_type = PACKET_TYPE_ONE_RTT
<5> elif self._cryptos[tls.Epoch.ZERO_RTT].send.is_valid():
<6> crypto = self._cryptos[tls.Epoch.ZERO_RTT]
<7> packet_type = PACKET_TYPE_ZERO_RTT
<8> else:
<9> return
<10> space = self._spaces[tls.Epoch.ONE_RTT]
<11>
<12> buf = builder.buffer
<13>
<14> while True:
<15> # write header
<16> builder.start_packet(packet_type, crypto)
<17>
<18> if self._handshake_complete:
<19> # ACK
<20> if space.ack_at is not None and space.ack_at <= now:
<21> builder.start_frame(
<22> QuicFrameType.ACK,
<23> self._on_ack_delivery,
<24> (space, space.largest_received_packet),
<25> )
<26> push_ack_frame(buf, space.ack_queue, 0)
<27> space.ack_at = None
<28>
<29> # log frame
<30> if self._quic_logger is not None:
<31> builder._packet.quic_logger_frames.append(
<32> self._quic_logger.encode_ack_frame(space.ack_queue, 0.0)
<33> )
<34>
<35> # PATH CHALLENGE
<36> if (
<37> not network_path.is_validated
<38> and network_path.local_challenge is None
<39> ):
<40> self._</s>
|
===========below chunk 0===========
# module: aioquic.quic.connection
class QuicConnection:
def _write_application(
self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float
) -> None:
# offset: 1
"Network path %s sending challenge", network_path.addr
)
network_path.local_challenge = os.urandom(8)
builder.start_frame(QuicFrameType.PATH_CHALLENGE)
buf.push_bytes(network_path.local_challenge)
# PATH RESPONSE
if network_path.remote_challenge is not None:
builder.start_frame(QuicFrameType.PATH_RESPONSE)
buf.push_bytes(network_path.remote_challenge)
network_path.remote_challenge = None
# NEW_CONNECTION_ID
for connection_id in self._host_cids:
if not connection_id.was_sent:
builder.start_frame(
QuicFrameType.NEW_CONNECTION_ID,
self._on_new_connection_id_delivery,
(connection_id,),
)
push_new_connection_id_frame(
buf,
connection_id.sequence_number,
0, # FIXME: retire_prior_to
connection_id.cid,
connection_id.stateless_reset_token,
)
connection_id.was_sent = True
self._events.append(
events.ConnectionIdIssued(connection_id=connection_id.cid)
)
# RETIRE_CONNECTION_ID
while self._retire_connection_ids:
sequence_number = self._retire_connection_ids.pop(0)
builder.start_frame(
QuicFrameType.RETIRE_CONNECTION_ID,
self._on_retire_connection_id_delivery,
(sequence_number,),
)
buf.push_uint_var(sequence_number)
# STREAMS_BLOCKED
if self._streams_blocked_pending:
if self._streams</s>
===========below chunk 1===========
# module: aioquic.quic.connection
class QuicConnection:
def _write_application(
self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float
) -> None:
# offset: 2
<s>sequence_number)
# STREAMS_BLOCKED
if self._streams_blocked_pending:
if self._streams_blocked_bidi:
builder.start_frame(QuicFrameType.STREAMS_BLOCKED_BIDI)
buf.push_uint_var(self._remote_max_streams_bidi)
if self._streams_blocked_uni:
builder.start_frame(QuicFrameType.STREAMS_BLOCKED_UNI)
buf.push_uint_var(self._remote_max_streams_uni)
self._streams_blocked_pending = False
# connection-level limits
self._write_connection_limits(builder=builder, space=space)
# stream-level limits
for stream in self._streams.values():
self._write_stream_limits(builder=builder, space=space, stream=stream)
# PING (user-request)
if self._ping_pending:
self._logger.info("Sending PING in packet %d", builder.packet_number)
builder.start_frame(
QuicFrameType.PING,
self._on_ping_delivery,
(tuple(self._ping_pending),),
)
self._ping_pending.clear()
# PING (probe)
if self._probe_pending:
self._logger.info("Sending probe")
builder.start_frame(QuicFrameType.PING)
self._probe_pending = False
# CRYPTO
if crypto_stream is not None and not crypto_stream.send_buffer_is_empty:
write_crypto_frame(builder=builder, space=space, stream=crypto_stream)
for stream in self._streams</s>
===========below chunk 2===========
# module: aioquic.quic.connection
class QuicConnection:
def _write_application(
self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float
) -> None:
# offset: 3
<s>():
# STREAM
if not stream.is_blocked and not stream.send_buffer_is_empty:
self._remote_max_data_used += write_stream_frame(
builder=builder,
space=space,
stream=stream,
max_offset=min(
stream._send_highest
+ self._remote_max_data
- self._remote_max_data_used,
stream.max_stream_data_remote,
),
)
if not builder.end_packet():
break
===========unchanged ref 0===========
at: aioquic._buffer.Buffer
push_bytes(value: bytes) -> None
push_uint_var(value: int) -> None
at: aioquic.quic.connection.QuicConnection
_on_ack_delivery(self, delivery: QuicDeliveryState, space: QuicPacketSpace, highest_acked: int) -> None
_on_ack_delivery(delivery: QuicDeliveryState, space: QuicPacketSpace, highest_acked: int) -> None
_on_new_connection_id_delivery(delivery: QuicDeliveryState, connection_id: QuicConnectionId) -> None
_on_retire_connection_id_delivery(delivery: QuicDeliveryState, sequence_number: int) -> None
_write_connection_limits(self, builder: QuicPacketBuilder, space: QuicPacketSpace) -> None
_write_connection_limits(builder: QuicPacketBuilder, space: QuicPacketSpace) -> None
_write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None
_write_crypto_frame(self, builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None
_write_ping_frame(builder: QuicPacketBuilder, uids: List[int]=[])
_write_stream_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream, max_offset: int) -> int
_write_stream_limits(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None
at: aioquic.quic.connection.QuicConnection.__init__
self._is_client = configuration.is_client
self._cryptos: Dict[tls.Epoch, CryptoPair] = {}
self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}
self._events: Deque[events.QuicEvent] = deque()
|
aioquic.quic.connection/QuicConnection._write_handshake
|
Modified
|
aiortc~aioquic
|
79f631193bdf5bc82ef88f9032a6f3b474d73bc1
|
[qlog] log more frames, set vantage point
|
<17>:<del> builder.start_frame(QuicFrameType.ACK)
<18>:<del> push_ack_frame(buf, space.ack_queue, 0)
<19>:<del> space.ack_at = None
<20>:<del>
<21>:<del> # log frame
<22>:<del> if self._quic_logger is not None:
<23>:<del> builder._packet.quic_logger_frames.append(
<24>:<del> self._quic_logger.encode_ack_frame(space.ack_queue, 0.0)
<25>:<del> )
<26>:<add> self._write_ack_frame(builder=builder, space=space)
<29>:<add> self._write_crypto_frame(
<add> builder=builder, space=space, stream=crypto_stream
<del> write_crypto_frame(builder=builder, space=space, stream=crypto_stream)
<30>:<add> )
|
# module: aioquic.quic.connection
class QuicConnection:
def _write_handshake(self, builder: QuicPacketBuilder, epoch: tls.Epoch) -> None:
<0> crypto = self._cryptos[epoch]
<1> if not crypto.send.is_valid():
<2> return
<3>
<4> buf = builder.buffer
<5> crypto_stream = self._crypto_streams[epoch]
<6> space = self._spaces[epoch]
<7>
<8> while True:
<9> if epoch == tls.Epoch.INITIAL:
<10> packet_type = PACKET_TYPE_INITIAL
<11> else:
<12> packet_type = PACKET_TYPE_HANDSHAKE
<13> builder.start_packet(packet_type, crypto)
<14>
<15> # ACK
<16> if space.ack_at is not None:
<17> builder.start_frame(QuicFrameType.ACK)
<18> push_ack_frame(buf, space.ack_queue, 0)
<19> space.ack_at = None
<20>
<21> # log frame
<22> if self._quic_logger is not None:
<23> builder._packet.quic_logger_frames.append(
<24> self._quic_logger.encode_ack_frame(space.ack_queue, 0.0)
<25> )
<26>
<27> # CRYPTO
<28> if not crypto_stream.send_buffer_is_empty:
<29> write_crypto_frame(builder=builder, space=space, stream=crypto_stream)
<30>
<31> # PADDING (anti-deadlock packet)
<32> if self._probe_pending and self._is_client and epoch == tls.Epoch.HANDSHAKE:
<33> buf.push_bytes(bytes(builder.remaining_space))
<34> self._probe_pending = False
<35>
<36> if not builder.end_packet():
<37> break
<38>
|
===========unchanged ref 0===========
at: aioquic._buffer.Buffer
push_bytes(value: bytes) -> None
push_uint16(value: int) -> None
push_uint_var(value: int) -> None
at: aioquic.buffer
size_uint_var(value: int) -> int
at: aioquic.quic.connection.QuicConnection
_on_max_data_delivery(delivery: QuicDeliveryState) -> None
at: aioquic.quic.connection.QuicConnection.__init__
self._quic_logger = configuration.quic_logger
self._local_max_data = MAX_DATA_WINDOW
self._local_max_data_sent = MAX_DATA_WINDOW
self._local_max_data_used = 0
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
at: aioquic.quic.connection.QuicConnection._handle_stream_frame
self._local_max_data_used += newly_received
at: aioquic.quic.connection.QuicConnection._on_max_data_delivery
self._local_max_data_sent = 0
at: aioquic.quic.logger.QuicLogger
encode_ack_frame(rangeset: RangeSet, delay: float)
at: aioquic.quic.packet
QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)
QuicFrameType(x: Union[str, bytes, bytearray], base: int)
at: aioquic.quic.packet.QuicStreamFrame
data: bytes = b""
fin: bool = False
offset: int = 0
at: aioquic.quic.packet_builder
QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b"", spin_bit: bool=False)
===========unchanged ref 1===========
at: aioquic.quic.packet_builder.QuicPacketBuilder
start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None
at: aioquic.quic.packet_builder.QuicPacketBuilder.__init__
self._packet: Optional[QuicSentPacket] = None
self.buffer = Buffer(PACKET_MAX_SIZE)
at: aioquic.quic.packet_builder.QuicPacketBuilder.end_packet
self._packet = None
at: aioquic.quic.packet_builder.QuicPacketBuilder.start_packet
self._packet = QuicSentPacket(
epoch=epoch,
in_flight=False,
is_ack_eliciting=False,
is_crypto_packet=False,
packet_number=self._packet_number,
packet_type=packet_type,
)
at: aioquic.quic.packet_builder.QuicSentPacket
epoch: Epoch
in_flight: bool
is_ack_eliciting: bool
is_crypto_packet: bool
packet_number: int
packet_type: int
sent_time: Optional[float] = None
sent_bytes: int = 0
delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(
default_factory=list
)
quic_logger_frames: List[Dict] = field(default_factory=list)
at: aioquic.quic.recovery
QuicPacketSpace()
at: aioquic.quic.recovery.QuicPacketSpace.__init__
self.ack_at: Optional[float] = None
self.ack_queue = RangeSet()
at: aioquic.quic.stream
QuicStream(stream_id: Optional[int]=None, connection: Optional[Any]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0)
===========unchanged ref 2===========
at: aioquic.quic.stream.QuicStream
get_frame(max_size: int, max_offset: Optional[int]=None) -> Optional[QuicStreamFrame]
on_data_delivery(delivery: QuicDeliveryState, start: int, stop: int) -> None
===========changed ref 0===========
# module: aioquic.quic.connection
class QuicConnection:
+ def _write_ack_frame(self, builder: QuicPacketBuilder, space: QuicPacketSpace):
+ builder.start_frame(
+ QuicFrameType.ACK,
+ self._on_ack_delivery,
+ (space, space.largest_received_packet),
+ )
+ push_ack_frame(builder.buffer, space.ack_queue, 0)
+ space.ack_at = None
+
+ # log frame
+ if self._quic_logger is not None:
+ builder._packet.quic_logger_frames.append(
+ self._quic_logger.encode_ack_frame(space.ack_queue, 0.0)
+ )
+
===========changed ref 1===========
# module: aioquic.quic.connection
class QuicConnection:
def _handle_padding_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
+ Handle a PADDING frame.
- Handle a PADDING or PING frame.
"""
+ buf.seek(buf.capacity)
- pass
===========changed ref 2===========
# module: aioquic.quic.connection
class QuicConnection:
+ def _handle_ping_frame(
+ self, context: QuicReceiveContext, frame_type: int, buf: Buffer
+ ) -> None:
+ """
+ Handle a PING frame.
+ """
+ # log frame
+ if self._quic_logger is not None:
+ context.quic_logger_frames.append(self._quic_logger.encode_ping_frame())
+
|
aioquic.quic.packet/pull_new_connection_id_frame
|
Modified
|
aiortc~aioquic
|
5df513ec4d4581d072fb2b3d09d4f23c5a88a1b4
|
[qlog] log more frames
|
<5>:<add> return QuicNewConnectionIdFrame(
<add> sequence_number=sequence_number,
<add> retire_prior_to=retire_prior_to,
<add> connection_id=connection_id,
<add> stateless_reset_token=stateless_reset_token,
<add> )
<del> return (sequence_number, retire_prior_to, connection_id, stateless_reset_token)
|
# module: aioquic.quic.packet
+ def pull_new_connection_id_frame(buf: Buffer) -> QuicNewConnectionIdFrame:
- def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]:
<0> sequence_number = buf.pull_uint_var()
<1> retire_prior_to = buf.pull_uint_var()
<2> length = buf.pull_uint8()
<3> connection_id = buf.pull_bytes(length)
<4> stateless_reset_token = buf.pull_bytes(16)
<5> return (sequence_number, retire_prior_to, connection_id, stateless_reset_token)
<6>
|
===========unchanged ref 0===========
at: aioquic._buffer
Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)
at: aioquic._buffer.Buffer
pull_bytes(length: int) -> bytes
push_bytes(value: bytes) -> None
push_uint_var(value: int) -> None
at: aioquic.quic.packet.pull_new_token_frame
length = buf.pull_uint_var()
===========changed ref 0===========
# module: aioquic.quic.packet
+ @dataclass
+ class QuicNewConnectionIdFrame:
+ sequence_number: int
+ retire_prior_to: int
+ connection_id: bytes
+ stateless_reset_token: bytes
+
|
aioquic.quic.packet/push_new_connection_id_frame
|
Modified
|
aiortc~aioquic
|
5df513ec4d4581d072fb2b3d09d4f23c5a88a1b4
|
[qlog] log more frames
|
<0>:<add> assert len(frame.stateless_reset_token) == 16
<del> assert len(stateless_reset_token) == 16
<1>:<add> buf.push_uint_var(frame.sequence_number)
<del> buf.push_uint_var(sequence_number)
<2>:<add> buf.push_uint_var(frame.retire_prior_to)
<del> buf.push_uint_var(retire_prior_to)
<3>:<add> buf.push_uint8(len(frame.connection_id))
<del> buf.push_uint8(len(connection_id))
<4>:<add> buf.push_bytes(frame.connection_id)
<del> buf.push_bytes(connection_id)
<5>:<add> buf.push_bytes(frame.stateless_reset_token)
<del> buf.push_bytes(stateless_reset_token)
|
# module: aioquic.quic.packet
- def push_new_connection_id_frame(
- buf: Buffer,
- sequence_number: int,
- retire_prior_to: int,
- connection_id: bytes,
- stateless_reset_token: bytes,
- ) -> None:
+ def push_new_connection_id_frame(buf: Buffer, frame: QuicNewConnectionIdFrame) -> None:
<0> assert len(stateless_reset_token) == 16
<1> buf.push_uint_var(sequence_number)
<2> buf.push_uint_var(retire_prior_to)
<3> buf.push_uint8(len(connection_id))
<4> buf.push_bytes(connection_id)
<5> buf.push_bytes(stateless_reset_token)
<6>
|
===========unchanged ref 0===========
at: aioquic._buffer.Buffer
pull_bytes(length: int) -> bytes
pull_uint8() -> int
pull_uint_var() -> int
at: aioquic.quic.packet
QuicNewConnectionIdFrame(sequence_number: int, retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes)
at: aioquic.quic.packet.QuicNewConnectionIdFrame
sequence_number: int
retire_prior_to: int
connection_id: bytes
stateless_reset_token: bytes
===========changed ref 0===========
# module: aioquic.quic.packet
+ @dataclass
+ class QuicNewConnectionIdFrame:
+ sequence_number: int
+ retire_prior_to: int
+ connection_id: bytes
+ stateless_reset_token: bytes
+
===========changed ref 1===========
# module: aioquic.quic.packet
+ def pull_new_connection_id_frame(buf: Buffer) -> QuicNewConnectionIdFrame:
- def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]:
sequence_number = buf.pull_uint_var()
retire_prior_to = buf.pull_uint_var()
length = buf.pull_uint8()
connection_id = buf.pull_bytes(length)
stateless_reset_token = buf.pull_bytes(16)
+ return QuicNewConnectionIdFrame(
+ sequence_number=sequence_number,
+ retire_prior_to=retire_prior_to,
+ connection_id=connection_id,
+ stateless_reset_token=stateless_reset_token,
+ )
- return (sequence_number, retire_prior_to, connection_id, stateless_reset_token)
|
aioquic.quic.logger/QuicLogger.encode_ack_frame
|
Modified
|
aiortc~aioquic
|
5df513ec4d4581d072fb2b3d09d4f23c5a88a1b4
|
[qlog] log more frames
|
<2>:<add> "acked_ranges": [[str(x.start), str(x.stop - 1)] for x in ranges],
<del> "acked_ranges": [[str(x.start), str(x.stop - 1)] for x in rangeset],
|
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_ack_frame(self, ranges: RangeSet, delay: float) -> Dict:
- def encode_ack_frame(self, rangeset: RangeSet, delay: float) -> Dict:
<0> return {
<1> "ack_delay": str(int(delay * 1000)), # convert to ms
<2> "acked_ranges": [[str(x.start), str(x.stop - 1)] for x in rangeset],
<3> "frame_type": "ACK",
<4> }
<5>
|
===========unchanged ref 0===========
at: aioquic.quic.rangeset
RangeSet(ranges: Iterable[range]=[])
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: aioquic.quic.logger
+ def hexdump(data: bytes) -> str:
+ return binascii.hexlify(data).decode("ascii")
+
===========changed ref 1===========
# module: aioquic.quic.packet
+ @dataclass
+ class QuicNewConnectionIdFrame:
+ sequence_number: int
+ retire_prior_to: int
+ connection_id: bytes
+ stateless_reset_token: bytes
+
===========changed ref 2===========
# module: aioquic.quic.packet
+ def pull_new_connection_id_frame(buf: Buffer) -> QuicNewConnectionIdFrame:
- def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]:
sequence_number = buf.pull_uint_var()
retire_prior_to = buf.pull_uint_var()
length = buf.pull_uint8()
connection_id = buf.pull_bytes(length)
stateless_reset_token = buf.pull_bytes(16)
+ return QuicNewConnectionIdFrame(
+ sequence_number=sequence_number,
+ retire_prior_to=retire_prior_to,
+ connection_id=connection_id,
+ stateless_reset_token=stateless_reset_token,
+ )
- return (sequence_number, retire_prior_to, connection_id, stateless_reset_token)
===========changed ref 3===========
# module: aioquic.quic.packet
- def push_new_connection_id_frame(
- buf: Buffer,
- sequence_number: int,
- retire_prior_to: int,
- connection_id: bytes,
- stateless_reset_token: bytes,
- ) -> None:
+ def push_new_connection_id_frame(buf: Buffer, frame: QuicNewConnectionIdFrame) -> None:
+ assert len(frame.stateless_reset_token) == 16
- assert len(stateless_reset_token) == 16
+ buf.push_uint_var(frame.sequence_number)
- buf.push_uint_var(sequence_number)
+ buf.push_uint_var(frame.retire_prior_to)
- buf.push_uint_var(retire_prior_to)
+ buf.push_uint8(len(frame.connection_id))
- buf.push_uint8(len(connection_id))
+ buf.push_bytes(frame.connection_id)
- buf.push_bytes(connection_id)
+ buf.push_bytes(frame.stateless_reset_token)
- buf.push_bytes(stateless_reset_token)
|
aioquic.quic.packet_builder/QuicPacketBuilder.__init__
|
Modified
|
aiortc~aioquic
|
5df513ec4d4581d072fb2b3d09d4f23c5a88a1b4
|
[qlog] log more frames
|
<7>:<add> self._quic_logger = quic_logger
|
# module: aioquic.quic.packet_builder
class QuicPacketBuilder:
def __init__(
self,
*,
host_cid: bytes,
peer_cid: bytes,
version: int,
pad_first_datagram: bool = False,
packet_number: int = 0,
peer_token: bytes = b"",
+ quic_logger: Optional[QuicLogger] = None,
spin_bit: bool = False,
):
<0> self.max_flight_bytes: Optional[int] = None
<1> self.max_total_bytes: Optional[int] = None
<2>
<3> self._host_cid = host_cid
<4> self._pad_first_datagram = pad_first_datagram
<5> self._peer_cid = peer_cid
<6> self._peer_token = peer_token
<7> self._spin_bit = spin_bit
<8> self._version = version
<9>
<10> # assembled datagrams and packets
<11> self._ack_eliciting = False
<12> self._datagrams: List[bytes] = []
<13> self._datagram_init = True
<14> self._packets: List[QuicSentPacket] = []
<15> self._flight_bytes = 0
<16> self._total_bytes = 0
<17>
<18> # current packet
<19> self._header_size = 0
<20> self._packet: Optional[QuicSentPacket] = None
<21> self._packet_crypto: Optional[CryptoPair] = None
<22> self._packet_long_header = False
<23> self._packet_number = packet_number
<24> self._packet_start = 0
<25> self._packet_type = 0
<26>
<27> self.buffer = Buffer(PACKET_MAX_SIZE)
<28> self._buffer_capacity = PACKET_MAX_SIZE
<29>
|
===========unchanged ref 0===========
at: aioquic.quic.crypto
CryptoPair()
at: aioquic.quic.logger
QuicLogger()
at: aioquic.quic.packet_builder
QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, packet_type: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field(
default_factory=list
), quic_logger_frames: List[Dict]=field(default_factory=list))
at: aioquic.quic.packet_builder.QuicPacketBuilder._flush_current_datagram
self._datagram_init = True
self._flight_bytes += datagram_bytes
self._total_bytes += datagram_bytes
at: aioquic.quic.packet_builder.QuicPacketBuilder.end_packet
self._pad_first_datagram = False
self._packet_number += 1
self._packet = None
at: aioquic.quic.packet_builder.QuicPacketBuilder.flush
self._datagrams = []
self._packets = []
at: aioquic.quic.packet_builder.QuicPacketBuilder.start_frame
self._ack_eliciting = True
at: aioquic.quic.packet_builder.QuicPacketBuilder.start_packet
self._ack_eliciting = False
self._datagram_init = False
self._header_size = header_size
self._packet = QuicSentPacket(
epoch=epoch,
in_flight=False,
is_ack_eliciting=False,
is_crypto_packet=False,
packet_number=self._packet_number,
packet_type=packet_type,
)
self._packet_crypto = crypto
self._packet_long_header = packet_long_header
===========unchanged ref 1===========
self._packet_start = packet_start
self._packet_type = packet_type
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: aioquic.quic.logger
+ def hexdump(data: bytes) -> str:
+ return binascii.hexlify(data).decode("ascii")
+
===========changed ref 1===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_max_data_frame(self, maximum: int) -> Dict:
+ return {"frame_type": "MAX_DATA", "maximum": str(maximum)}
+
===========changed ref 2===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_max_streams_frame(self, maximum: int) -> Dict:
+ return {"frame_type": "MAX_STREAMS", "maximum": str(maximum)}
+
===========changed ref 3===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_data_blocked_frame(self, limit: int) -> Dict:
+ return {"frame_type": "DATA_BLOCKED", "limit": str(limit)}
+
===========changed ref 4===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_streams_blocked_frame(self, limit: int) -> Dict:
+ return {"frame_type": "STREAMS_BLOCKED", "limit": str(limit)}
+
===========changed ref 5===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_path_response_frame(self, data: bytes) -> Dict:
+ return {"data": hexdump(data), "frame_type": "PATH_RESPONSE"}
+
===========changed ref 6===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_path_challenge_frame(self, data: bytes) -> Dict:
+ return {"data": hexdump(data), "frame_type": "PATH_CHALLENGE"}
+
===========changed ref 7===========
# module: aioquic.quic.packet
+ @dataclass
+ class QuicNewConnectionIdFrame:
+ sequence_number: int
+ retire_prior_to: int
+ connection_id: bytes
+ stateless_reset_token: bytes
+
===========changed ref 8===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_retire_connection_id_frame(self, sequence_number: int) -> Dict:
+ return {
+ "frame_type": "RETIRE_CONNECTION_ID",
+ "sequence_number": str(sequence_number),
+ }
+
===========changed ref 9===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_new_token_frame(self, token: bytes) -> Dict:
+ return {
+ "frame_type": "NEW_TOKEN",
+ "length": str(len(token)),
+ "token": hexdump(token),
+ }
+
===========changed ref 10===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_max_stream_data_frame(self, maximum: int, stream_id: int) -> Dict:
+ return {
+ "frame_type": "MAX_STREAM_DATA",
+ "id": str(stream_id),
+ "maximum": str(maximum),
+ }
+
===========changed ref 11===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_stop_sending_frame(self, error_code: int, stream_id: int) -> Dict:
+ return {
+ "frame_type": "STOP_SENDING",
+ "id": str(stream_id),
+ "error_code": error_code,
+ }
+
===========changed ref 12===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_reset_stream_frame(
+ self, error_code: int, final_size: int, stream_id: int
+ ) -> Dict:
+ return {
+ "error_code": error_code,
+ "final_size": str(final_size),
+ "frame_type": "RESET_STREAM",
+ }
+
===========changed ref 13===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_stream_data_blocked_frame(self, limit: int, stream_id: int) -> Dict:
+ return {
+ "frame_type": "STREAM_DATA_BLOCKED",
+ "limit": str(limit),
+ "stream_id": str(stream_id),
+ }
+
===========changed ref 14===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_ack_frame(self, ranges: RangeSet, delay: float) -> Dict:
- def encode_ack_frame(self, rangeset: RangeSet, delay: float) -> Dict:
return {
"ack_delay": str(int(delay * 1000)), # convert to ms
+ "acked_ranges": [[str(x.start), str(x.stop - 1)] for x in ranges],
- "acked_ranges": [[str(x.start), str(x.stop - 1)] for x in rangeset],
"frame_type": "ACK",
}
===========changed ref 15===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_connection_close_frame(
+ self, error_code: int, frame_type: Optional[int], reason_phrase: str
+ ) -> Dict:
+ attrs = {
+ "error_code": error_code,
+ "error_space": "application" if frame_type is None else "transport",
+ "frame_type": "CONNECTION_CLOSE",
+ "raw_error_code": error_code,
+ "reason": reason_phrase,
+ }
+ if frame_type is not None:
+ attrs["trigger_frame_type"] = frame_type
+
+ return attrs
+
|
aioquic.quic.packet_builder/QuicPacketBuilder.end_packet
|
Modified
|
aiortc~aioquic
|
5df513ec4d4581d072fb2b3d09d4f23c5a88a1b4
|
[qlog] log more frames
|
<13>:<add> if self.remaining_space:
<add> buf.push_bytes(bytes(self.remaining_space))
<del> buf.push_bytes(bytes(self.remaining_space))
<14>:<add> packet_size = buf.tell() - self._packet_start
<del> packet_size = buf.tell() - self._packet_start
<15>:<add>
<add> # log frame
<add> if self._quic_logger is not None:
<add> self._packet.quic_logger_frames.append(
<add> self._quic_logger.encode_padding_frame()
<add> )
|
# module: aioquic.quic.packet_builder
class QuicPacketBuilder:
def end_packet(self) -> bool:
<0> """
<1> Ends the current packet.
<2>
<3> Returns `True` if the packet contains data, `False` otherwise.
<4> """
<5> buf = self.buffer
<6> empty = True
<7> packet_size = buf.tell() - self._packet_start
<8> if packet_size > self._header_size:
<9> empty = False
<10>
<11> # pad initial datagram
<12> if self._pad_first_datagram:
<13> buf.push_bytes(bytes(self.remaining_space))
<14> packet_size = buf.tell() - self._packet_start
<15> self._pad_first_datagram = False
<16>
<17> # write header
<18> if self._packet_long_header:
<19> length = (
<20> packet_size
<21> - self._header_size
<22> + PACKET_NUMBER_SEND_SIZE
<23> + self._packet_crypto.aead_tag_size
<24> )
<25>
<26> buf.seek(self._packet_start)
<27> buf.push_uint8(self._packet_type | (PACKET_NUMBER_SEND_SIZE - 1))
<28> buf.push_uint32(self._version)
<29> buf.push_uint8(len(self._peer_cid))
<30> buf.push_bytes(self._peer_cid)
<31> buf.push_uint8(len(self._host_cid))
<32> buf.push_bytes(self._host_cid)
<33> if (self._packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL:
<34> buf.push_uint_var(len(self._peer_token))
<35> buf.push_bytes(self._peer_token)
<36> buf.push_uint16(length | 0x4000)
<37> buf.push_uint16(self._packet_number & 0xFFFF)
<38> else:
<39> buf.seek(self._packet_start)
<40> buf.push_uint8</s>
|
===========below chunk 0===========
# module: aioquic.quic.packet_builder
class QuicPacketBuilder:
def end_packet(self) -> bool:
# offset: 1
self._packet_type
| (self._spin_bit << 5)
| (self._packet_crypto.key_phase << 2)
| (PACKET_NUMBER_SEND_SIZE - 1)
)
buf.push_bytes(self._peer_cid)
buf.push_uint16(self._packet_number & 0xFFFF)
# check whether we need padding
padding_size = (
PACKET_NUMBER_MAX_SIZE
- PACKET_NUMBER_SEND_SIZE
+ self._header_size
- packet_size
)
if padding_size > 0:
buf.seek(self._packet_start + packet_size)
buf.push_bytes(bytes(padding_size))
packet_size += padding_size
# encrypt in place
plain = buf.data_slice(self._packet_start, self._packet_start + packet_size)
buf.seek(self._packet_start)
buf.push_bytes(
self._packet_crypto.encrypt_packet(
plain[0 : self._header_size],
plain[self._header_size : packet_size],
self._packet_number,
)
)
self._packet.sent_bytes = buf.tell() - self._packet_start
self._packets.append(self._packet)
# short header packets cannot be coallesced, we need a new datagram
if not self._packet_long_header:
self._flush_current_datagram()
self._packet_number += 1
else:
# "cancel" the packet
buf.seek(self._packet_start)
self._packet = None
return not empty
===========unchanged ref 0===========
at: aioquic._buffer.Buffer
data_slice(start: int, end: int) -> bytes
seek(pos: int) -> None
tell() -> int
push_bytes(value: bytes) -> None
push_uint8(value: int) -> None
push_uint16(value: int) -> None
push_uint32(v: int) -> None
push_uint_var(value: int) -> None
at: aioquic.quic.crypto.CryptoPair
encrypt_packet(plain_header: bytes, plain_payload: bytes, packet_number: int) -> bytes
at: aioquic.quic.crypto.CryptoPair.__init__
self.aead_tag_size = 16
at: aioquic.quic.logger.QuicLogger
encode_padding_frame() -> Dict
at: aioquic.quic.packet
PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00
PACKET_TYPE_MASK = 0xF0
PACKET_NUMBER_MAX_SIZE = 4
at: aioquic.quic.packet_builder
PACKET_NUMBER_SEND_SIZE = 2
at: aioquic.quic.packet_builder.QuicPacketBuilder.__init__
self._host_cid = host_cid
self._pad_first_datagram = pad_first_datagram
self._peer_cid = peer_cid
self._peer_token = peer_token
self._quic_logger = quic_logger
self._spin_bit = spin_bit
self._version = version
self._packets: List[QuicSentPacket] = []
self._header_size = 0
self._packet: Optional[QuicSentPacket] = None
self._packet_crypto: Optional[CryptoPair] = None
self._packet_long_header = False
self._packet_number = packet_number
self._packet_start = 0
===========unchanged ref 1===========
self._packet_type = 0
self.buffer = Buffer(PACKET_MAX_SIZE)
at: aioquic.quic.packet_builder.QuicPacketBuilder.end_packet
self._packet_number += 1
self._packet = None
at: aioquic.quic.packet_builder.QuicPacketBuilder.flush
self._packets = []
at: aioquic.quic.packet_builder.QuicPacketBuilder.start_packet
buf = self.buffer
self._header_size = header_size
self._packet = QuicSentPacket(
epoch=epoch,
in_flight=False,
is_ack_eliciting=False,
is_crypto_packet=False,
packet_number=self._packet_number,
packet_type=packet_type,
)
self._packet_crypto = crypto
self._packet_long_header = packet_long_header
self._packet_start = packet_start
self._packet_type = packet_type
at: aioquic.quic.packet_builder.QuicSentPacket
epoch: Epoch
in_flight: bool
is_ack_eliciting: bool
is_crypto_packet: bool
packet_number: int
packet_type: int
sent_time: Optional[float] = None
sent_bytes: int = 0
delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(
default_factory=list
)
quic_logger_frames: List[Dict] = field(default_factory=list)
===========changed ref 0===========
# module: aioquic.quic.packet_builder
class QuicPacketBuilder:
def __init__(
self,
*,
host_cid: bytes,
peer_cid: bytes,
version: int,
pad_first_datagram: bool = False,
packet_number: int = 0,
peer_token: bytes = b"",
+ quic_logger: Optional[QuicLogger] = None,
spin_bit: bool = False,
):
self.max_flight_bytes: Optional[int] = None
self.max_total_bytes: Optional[int] = None
self._host_cid = host_cid
self._pad_first_datagram = pad_first_datagram
self._peer_cid = peer_cid
self._peer_token = peer_token
+ self._quic_logger = quic_logger
self._spin_bit = spin_bit
self._version = version
# assembled datagrams and packets
self._ack_eliciting = False
self._datagrams: List[bytes] = []
self._datagram_init = True
self._packets: List[QuicSentPacket] = []
self._flight_bytes = 0
self._total_bytes = 0
# current packet
self._header_size = 0
self._packet: Optional[QuicSentPacket] = None
self._packet_crypto: Optional[CryptoPair] = None
self._packet_long_header = False
self._packet_number = packet_number
self._packet_start = 0
self._packet_type = 0
self.buffer = Buffer(PACKET_MAX_SIZE)
self._buffer_capacity = PACKET_MAX_SIZE
===========changed ref 1===========
# module: aioquic.quic.logger
+ def hexdump(data: bytes) -> str:
+ return binascii.hexlify(data).decode("ascii")
+
===========changed ref 2===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_max_data_frame(self, maximum: int) -> Dict:
+ return {"frame_type": "MAX_DATA", "maximum": str(maximum)}
+
===========changed ref 3===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_max_streams_frame(self, maximum: int) -> Dict:
+ return {"frame_type": "MAX_STREAMS", "maximum": str(maximum)}
+
|
aioquic.quic.connection/QuicConnection.datagrams_to_send
|
Modified
|
aiortc~aioquic
|
5df513ec4d4581d072fb2b3d09d4f23c5a88a1b4
|
[qlog] log more frames
|
<20>:<add> quic_logger=self._quic_logger,
<32>:<add> self._write_close_frame(
<del> write_close_frame(
|
# module: aioquic.quic.connection
class QuicConnection:
def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]:
<0> """
<1> Return a list of `(data, addr)` tuples of datagrams which need to be
<2> sent, and the network address to which they need to be sent.
<3>
<4> :param now: The current time.
<5> """
<6> network_path = self._network_paths[0]
<7>
<8> if self._state in END_STATES:
<9> return []
<10>
<11> # build datagrams
<12> builder = QuicPacketBuilder(
<13> host_cid=self.host_cid,
<14> packet_number=self._packet_number,
<15> pad_first_datagram=(
<16> self._is_client and self._state == QuicConnectionState.FIRSTFLIGHT
<17> ),
<18> peer_cid=self._peer_cid,
<19> peer_token=self._peer_token,
<20> spin_bit=self._spin_bit,
<21> version=self._version,
<22> )
<23> if self._close_pending:
<24> for epoch, packet_type in (
<25> (tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT),
<26> (tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE),
<27> (tls.Epoch.INITIAL, PACKET_TYPE_INITIAL),
<28> ):
<29> crypto = self._cryptos[epoch]
<30> if crypto.send.is_valid():
<31> builder.start_packet(packet_type, crypto)
<32> write_close_frame(
<33> builder=builder,
<34> error_code=self._close_event.error_code,
<35> frame_type=self._close_event.frame_type,
<36> reason_phrase=self._close_event.reason_phrase,
<37> )
<38> builder.end_packet()
<39> self._close_pending = False
<40> break
<41> self._close_begin(is_initiator=True, now</s>
|
===========below chunk 0===========
# module: aioquic.quic.connection
class QuicConnection:
def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]:
# offset: 1
else:
# congestion control
builder.max_flight_bytes = (
self._loss.congestion_window - self._loss.bytes_in_flight
)
if self._probe_pending and builder.max_flight_bytes < PACKET_MAX_SIZE:
builder.max_flight_bytes = PACKET_MAX_SIZE
# limit data on un-validated network paths
if not network_path.is_validated:
builder.max_total_bytes = (
network_path.bytes_received * 3 - network_path.bytes_sent
)
try:
if not self._handshake_confirmed:
for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]:
self._write_handshake(builder, epoch)
self._write_application(builder, network_path, now)
except QuicPacketBuilderStop:
pass
datagrams, packets = builder.flush()
if datagrams:
self._packet_number = builder.packet_number
# register packets
sent_handshake = False
for packet in packets:
packet.sent_time = now
self._loss.on_packet_sent(
packet=packet, space=self._spaces[packet.epoch]
)
if packet.epoch == tls.Epoch.HANDSHAKE:
sent_handshake = True
# log packet
if self._quic_logger is not None:
self._quic_logger.log_event(
category="TRANSPORT",
event="PACKET_SENT",
data={
"packet_type": self._quic_logger.packet_type(
packet.packet_type
),
"header": {
"packet_number": str(packet.packet_number),
"packet_size": packet.sent_bytes,
"scid":</s>
===========below chunk 1===========
# module: aioquic.quic.connection
class QuicConnection:
def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]:
# offset: 2
<s>_number": str(packet.packet_number),
"packet_size": packet.sent_bytes,
"scid": dump_cid(self.host_cid)
if is_long_header(packet.packet_type)
else "",
"dcid": dump_cid(self._peer_cid),
},
"frames": packet.quic_logger_frames,
},
)
# check if we can discard initial keys
if sent_handshake and self._is_client:
self._discard_epoch(tls.Epoch.INITIAL)
# return datagrams to send and the destination network address
ret = []
for datagram in datagrams:
byte_length = len(datagram)
network_path.bytes_sent += byte_length
ret.append((datagram, network_path.addr))
if self._quic_logger is not None:
self._quic_logger.log_event(
category="TRANSPORT",
event="DATAGRAM_SENT",
data={"byte_length": byte_length, "count": 1},
)
return ret
===========unchanged ref 0===========
at: aioquic.quic.connection
dump_cid(cid: bytes) -> str
END_STATES = frozenset(
[
QuicConnectionState.CLOSING,
QuicConnectionState.DRAINING,
QuicConnectionState.TERMINATED,
]
)
at: aioquic.quic.connection.QuicConnection
_close_begin(is_initiator: bool, now: float) -> None
_write_close_frame(builder: QuicPacketBuilder, error_code: int, frame_type: Optional[int], reason_phrase: str) -> None
at: aioquic.quic.connection.QuicConnection.__init__
self._is_client = configuration.is_client
self._close_at: Optional[float] = None
self._close_event: Optional[events.ConnectionTerminated] = None
self._cryptos: Dict[tls.Epoch, CryptoPair] = {}
self._loss = QuicPacketRecovery(
is_client_without_1rtt=self._is_client,
quic_logger=self._quic_logger,
send_probe=self._send_probe,
)
self._spin_bit = False
self._state = QuicConnectionState.FIRSTFLIGHT
self._streams: Dict[int, QuicStream] = {}
self._version: Optional[int] = None
self._close_pending = False
self._probe_pending = False
at: aioquic.quic.connection.QuicConnection._close_begin
self._close_at = now + 3 * self._loss.get_probe_timeout()
at: aioquic.quic.connection.QuicConnection._close_end
self._close_at = None
at: aioquic.quic.connection.QuicConnection._connect
self._close_at = now + self._configuration.idle_timeout
===========unchanged ref 1===========
at: aioquic.quic.connection.QuicConnection._handle_connection_close_frame
self._close_event = events.ConnectionTerminated(
error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase
)
at: aioquic.quic.connection.QuicConnection._initialize
self._cryptos = {
tls.Epoch.INITIAL: CryptoPair(),
tls.Epoch.ZERO_RTT: CryptoPair(),
tls.Epoch.HANDSHAKE: CryptoPair(),
tls.Epoch.ONE_RTT: CryptoPair(),
}
at: aioquic.quic.connection.QuicConnection._send_probe
self._probe_pending = True
at: aioquic.quic.connection.QuicConnection._set_state
self._state = state
at: aioquic.quic.connection.QuicConnection._write_application
self._probe_pending = False
at: aioquic.quic.connection.QuicConnection._write_handshake
self._probe_pending = False
at: aioquic.quic.connection.QuicConnection.close
self._close_event = events.ConnectionTerminated(
error_code=error_code,
frame_type=frame_type,
reason_phrase=reason_phrase,
)
self._close_pending = True
at: aioquic.quic.connection.QuicConnection.connect
self._version = self._configuration.supported_versions[0]
at: aioquic.quic.connection.QuicConnection.datagrams_to_send
network_path = self._network_paths[0]
|
aioquic.quic.connection/QuicConnection._handle_connection_close_frame
|
Modified
|
aiortc~aioquic
|
5df513ec4d4581d072fb2b3d09d4f23c5a88a1b4
|
[qlog] log more frames
|
<8>:<add>
<add> # log frame
<add> if self._quic_logger is not None:
<add> context.quic_logger_frames.append(
<add> self._quic_logger.encode_connection_close_frame(
<add> error_code=error_code,
<add> frame_type=frame_type,
<add> reason_phrase=reason_phrase,
<add> )
<add> )
<add>
|
# module: aioquic.quic.connection
class QuicConnection:
def _handle_connection_close_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
<0> """
<1> Handle a CONNECTION_CLOSE frame.
<2> """
<3> if frame_type == QuicFrameType.TRANSPORT_CLOSE:
<4> error_code, frame_type, reason_phrase = pull_transport_close_frame(buf)
<5> else:
<6> error_code, reason_phrase = pull_application_close_frame(buf)
<7> frame_type = None
<8> self._logger.info(
<9> "Connection close code 0x%X, reason %s", error_code, reason_phrase
<10> )
<11> self._close_event = events.ConnectionTerminated(
<12> error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase
<13> )
<14> self._close_begin(is_initiator=False, now=context.time)
<15>
|
===========unchanged ref 0===========
at: aioquic._buffer
Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)
at: aioquic._buffer.Buffer
pull_bytes(length: int) -> bytes
pull_uint_var() -> int
at: aioquic.quic.connection
QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, quic_logger_frames: Optional[List[Any]], time: float)
at: aioquic.quic.connection.QuicConnection
_close_begin(is_initiator: bool, now: float) -> None
at: aioquic.quic.connection.QuicConnection.__init__
self._close_event: Optional[events.ConnectionTerminated] = None
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
at: aioquic.quic.connection.QuicConnection._handle_connection_close_frame
error_code, frame_type, reason_phrase = pull_transport_close_frame(buf)
error_code, reason_phrase = pull_application_close_frame(buf)
error_code, frame_type, reason_phrase = pull_transport_close_frame(buf)
frame_type = None
error_code, frame_type, reason_phrase = pull_transport_close_frame(buf)
error_code, reason_phrase = pull_application_close_frame(buf)
at: aioquic.quic.connection.QuicConnection.close
self._close_event = events.ConnectionTerminated(
error_code=error_code,
frame_type=frame_type,
reason_phrase=reason_phrase,
)
at: aioquic.quic.connection.QuicConnection.handle_timer
self._close_event = events.ConnectionTerminated(
error_code=QuicErrorCode.INTERNAL_ERROR,
frame_type=None,
reason_phrase="Idle timeout",
)
===========unchanged ref 1===========
at: aioquic.quic.connection.QuicConnection.receive_datagram
self._close_event = events.ConnectionTerminated(
error_code=QuicErrorCode.INTERNAL_ERROR,
frame_type=None,
reason_phrase="Could not find a common protocol version",
)
at: aioquic.quic.connection.QuicReceiveContext
epoch: tls.Epoch
host_cid: bytes
network_path: QuicNetworkPath
quic_logger_frames: Optional[List[Any]]
time: float
at: aioquic.quic.events
ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str)
at: aioquic.quic.packet
QuicStreamFrame(data: bytes=b"", fin: bool=False, offset: int=0)
at: aioquic.quic.packet.QuicStreamFrame
data: bytes = b""
fin: bool = False
offset: int = 0
at: logging.LoggerAdapter
logger: Logger
extra: Mapping[str, Any]
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
===========changed ref 0===========
# module: aioquic.quic.logger
+ def hexdump(data: bytes) -> str:
+ return binascii.hexlify(data).decode("ascii")
+
===========changed ref 1===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_max_data_frame(self, maximum: int) -> Dict:
+ return {"frame_type": "MAX_DATA", "maximum": str(maximum)}
+
===========changed ref 2===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_max_streams_frame(self, maximum: int) -> Dict:
+ return {"frame_type": "MAX_STREAMS", "maximum": str(maximum)}
+
===========changed ref 3===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_data_blocked_frame(self, limit: int) -> Dict:
+ return {"frame_type": "DATA_BLOCKED", "limit": str(limit)}
+
===========changed ref 4===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_streams_blocked_frame(self, limit: int) -> Dict:
+ return {"frame_type": "STREAMS_BLOCKED", "limit": str(limit)}
+
===========changed ref 5===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_path_response_frame(self, data: bytes) -> Dict:
+ return {"data": hexdump(data), "frame_type": "PATH_RESPONSE"}
+
===========changed ref 6===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_path_challenge_frame(self, data: bytes) -> Dict:
+ return {"data": hexdump(data), "frame_type": "PATH_CHALLENGE"}
+
===========changed ref 7===========
# module: aioquic.quic.packet
+ @dataclass
+ class QuicNewConnectionIdFrame:
+ sequence_number: int
+ retire_prior_to: int
+ connection_id: bytes
+ stateless_reset_token: bytes
+
===========changed ref 8===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_retire_connection_id_frame(self, sequence_number: int) -> Dict:
+ return {
+ "frame_type": "RETIRE_CONNECTION_ID",
+ "sequence_number": str(sequence_number),
+ }
+
===========changed ref 9===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_new_token_frame(self, token: bytes) -> Dict:
+ return {
+ "frame_type": "NEW_TOKEN",
+ "length": str(len(token)),
+ "token": hexdump(token),
+ }
+
===========changed ref 10===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_max_stream_data_frame(self, maximum: int, stream_id: int) -> Dict:
+ return {
+ "frame_type": "MAX_STREAM_DATA",
+ "id": str(stream_id),
+ "maximum": str(maximum),
+ }
+
===========changed ref 11===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_stop_sending_frame(self, error_code: int, stream_id: int) -> Dict:
+ return {
+ "frame_type": "STOP_SENDING",
+ "id": str(stream_id),
+ "error_code": error_code,
+ }
+
===========changed ref 12===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_reset_stream_frame(
+ self, error_code: int, final_size: int, stream_id: int
+ ) -> Dict:
+ return {
+ "error_code": error_code,
+ "final_size": str(final_size),
+ "frame_type": "RESET_STREAM",
+ }
+
===========changed ref 13===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_stream_data_blocked_frame(self, limit: int, stream_id: int) -> Dict:
+ return {
+ "frame_type": "STREAM_DATA_BLOCKED",
+ "limit": str(limit),
+ "stream_id": str(stream_id),
+ }
+
|
aioquic.quic.connection/QuicConnection._handle_data_blocked_frame
|
Modified
|
aiortc~aioquic
|
5df513ec4d4581d072fb2b3d09d4f23c5a88a1b4
|
[qlog] log more frames
|
<3>:<add> limit = buf.pull_uint_var()
<del> buf.pull_uint_var() # limit
|
# module: aioquic.quic.connection
class QuicConnection:
def _handle_data_blocked_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
<0> """
<1> Handle a DATA_BLOCKED frame.
<2> """
<3> buf.pull_uint_var() # limit
<4>
|
===========unchanged ref 0===========
at: aioquic._buffer
Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)
at: aioquic.quic.connection
QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, quic_logger_frames: Optional[List[Any]], time: float)
at: aioquic.quic.connection.QuicConnection.__init__
self._quic_logger = configuration.quic_logger
at: aioquic.quic.connection.QuicConnection._handle_data_blocked_frame
limit = buf.pull_uint_var()
at: aioquic.quic.connection.QuicReceiveContext
quic_logger_frames: Optional[List[Any]]
===========changed ref 0===========
# module: aioquic.quic.connection
class QuicConnection:
def _handle_connection_close_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a CONNECTION_CLOSE frame.
"""
if frame_type == QuicFrameType.TRANSPORT_CLOSE:
error_code, frame_type, reason_phrase = pull_transport_close_frame(buf)
else:
error_code, reason_phrase = pull_application_close_frame(buf)
frame_type = None
+
+ # log frame
+ if self._quic_logger is not None:
+ context.quic_logger_frames.append(
+ self._quic_logger.encode_connection_close_frame(
+ error_code=error_code,
+ frame_type=frame_type,
+ reason_phrase=reason_phrase,
+ )
+ )
+
self._logger.info(
"Connection close code 0x%X, reason %s", error_code, reason_phrase
)
self._close_event = events.ConnectionTerminated(
error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase
)
self._close_begin(is_initiator=False, now=context.time)
===========changed ref 1===========
# module: aioquic.quic.logger
+ def hexdump(data: bytes) -> str:
+ return binascii.hexlify(data).decode("ascii")
+
===========changed ref 2===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_max_data_frame(self, maximum: int) -> Dict:
+ return {"frame_type": "MAX_DATA", "maximum": str(maximum)}
+
===========changed ref 3===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_max_streams_frame(self, maximum: int) -> Dict:
+ return {"frame_type": "MAX_STREAMS", "maximum": str(maximum)}
+
===========changed ref 4===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_data_blocked_frame(self, limit: int) -> Dict:
+ return {"frame_type": "DATA_BLOCKED", "limit": str(limit)}
+
===========changed ref 5===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_streams_blocked_frame(self, limit: int) -> Dict:
+ return {"frame_type": "STREAMS_BLOCKED", "limit": str(limit)}
+
===========changed ref 6===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_path_response_frame(self, data: bytes) -> Dict:
+ return {"data": hexdump(data), "frame_type": "PATH_RESPONSE"}
+
===========changed ref 7===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_path_challenge_frame(self, data: bytes) -> Dict:
+ return {"data": hexdump(data), "frame_type": "PATH_CHALLENGE"}
+
===========changed ref 8===========
# module: aioquic.quic.packet
+ @dataclass
+ class QuicNewConnectionIdFrame:
+ sequence_number: int
+ retire_prior_to: int
+ connection_id: bytes
+ stateless_reset_token: bytes
+
===========changed ref 9===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_retire_connection_id_frame(self, sequence_number: int) -> Dict:
+ return {
+ "frame_type": "RETIRE_CONNECTION_ID",
+ "sequence_number": str(sequence_number),
+ }
+
===========changed ref 10===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_new_token_frame(self, token: bytes) -> Dict:
+ return {
+ "frame_type": "NEW_TOKEN",
+ "length": str(len(token)),
+ "token": hexdump(token),
+ }
+
===========changed ref 11===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_max_stream_data_frame(self, maximum: int, stream_id: int) -> Dict:
+ return {
+ "frame_type": "MAX_STREAM_DATA",
+ "id": str(stream_id),
+ "maximum": str(maximum),
+ }
+
===========changed ref 12===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_stop_sending_frame(self, error_code: int, stream_id: int) -> Dict:
+ return {
+ "frame_type": "STOP_SENDING",
+ "id": str(stream_id),
+ "error_code": error_code,
+ }
+
===========changed ref 13===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_reset_stream_frame(
+ self, error_code: int, final_size: int, stream_id: int
+ ) -> Dict:
+ return {
+ "error_code": error_code,
+ "final_size": str(final_size),
+ "frame_type": "RESET_STREAM",
+ }
+
===========changed ref 14===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_stream_data_blocked_frame(self, limit: int, stream_id: int) -> Dict:
+ return {
+ "frame_type": "STREAM_DATA_BLOCKED",
+ "limit": str(limit),
+ "stream_id": str(stream_id),
+ }
+
===========changed ref 15===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_ack_frame(self, ranges: RangeSet, delay: float) -> Dict:
- def encode_ack_frame(self, rangeset: RangeSet, delay: float) -> Dict:
return {
"ack_delay": str(int(delay * 1000)), # convert to ms
+ "acked_ranges": [[str(x.start), str(x.stop - 1)] for x in ranges],
- "acked_ranges": [[str(x.start), str(x.stop - 1)] for x in rangeset],
"frame_type": "ACK",
}
===========changed ref 16===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_connection_close_frame(
+ self, error_code: int, frame_type: Optional[int], reason_phrase: str
+ ) -> Dict:
+ attrs = {
+ "error_code": error_code,
+ "error_space": "application" if frame_type is None else "transport",
+ "frame_type": "CONNECTION_CLOSE",
+ "raw_error_code": error_code,
+ "reason": reason_phrase,
+ }
+ if frame_type is not None:
+ attrs["trigger_frame_type"] = frame_type
+
+ return attrs
+
|
aioquic.quic.connection/QuicConnection._handle_max_data_frame
|
Modified
|
aiortc~aioquic
|
5df513ec4d4581d072fb2b3d09d4f23c5a88a1b4
|
[qlog] log more frames
|
<6>:<add>
<add> # log frame
<add> if self._quic_logger is not None:
<add> context.quic_logger_frames.append(
<add> self._quic_logger.encode_max_data_frame(maximum=max_data)
<add> )
<add>
|
# module: aioquic.quic.connection
class QuicConnection:
def _handle_max_data_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
<0> """
<1> Handle a MAX_DATA frame.
<2>
<3> This adjusts the total amount of we can send to the peer.
<4> """
<5> max_data = buf.pull_uint_var()
<6> if max_data > self._remote_max_data:
<7> self._logger.debug("Remote max_data raised to %d", max_data)
<8> self._remote_max_data = max_data
<9>
|
===========unchanged ref 0===========
at: aioquic._buffer.Buffer
pull_uint_var() -> int
at: aioquic.quic.connection.QuicConnection.__init__
self._quic_logger = configuration.quic_logger
at: aioquic.quic.connection.QuicReceiveContext
quic_logger_frames: Optional[List[Any]]
===========changed ref 0===========
# module: aioquic.quic.connection
class QuicConnection:
def _handle_data_blocked_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a DATA_BLOCKED frame.
"""
+ limit = buf.pull_uint_var()
- buf.pull_uint_var() # limit
===========changed ref 1===========
# module: aioquic.quic.connection
class QuicConnection:
def _handle_connection_close_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a CONNECTION_CLOSE frame.
"""
if frame_type == QuicFrameType.TRANSPORT_CLOSE:
error_code, frame_type, reason_phrase = pull_transport_close_frame(buf)
else:
error_code, reason_phrase = pull_application_close_frame(buf)
frame_type = None
+
+ # log frame
+ if self._quic_logger is not None:
+ context.quic_logger_frames.append(
+ self._quic_logger.encode_connection_close_frame(
+ error_code=error_code,
+ frame_type=frame_type,
+ reason_phrase=reason_phrase,
+ )
+ )
+
self._logger.info(
"Connection close code 0x%X, reason %s", error_code, reason_phrase
)
self._close_event = events.ConnectionTerminated(
error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase
)
self._close_begin(is_initiator=False, now=context.time)
===========changed ref 2===========
# module: aioquic.quic.logger
+ def hexdump(data: bytes) -> str:
+ return binascii.hexlify(data).decode("ascii")
+
===========changed ref 3===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_max_data_frame(self, maximum: int) -> Dict:
+ return {"frame_type": "MAX_DATA", "maximum": str(maximum)}
+
===========changed ref 4===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_max_streams_frame(self, maximum: int) -> Dict:
+ return {"frame_type": "MAX_STREAMS", "maximum": str(maximum)}
+
===========changed ref 5===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_data_blocked_frame(self, limit: int) -> Dict:
+ return {"frame_type": "DATA_BLOCKED", "limit": str(limit)}
+
===========changed ref 6===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_streams_blocked_frame(self, limit: int) -> Dict:
+ return {"frame_type": "STREAMS_BLOCKED", "limit": str(limit)}
+
===========changed ref 7===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_path_response_frame(self, data: bytes) -> Dict:
+ return {"data": hexdump(data), "frame_type": "PATH_RESPONSE"}
+
===========changed ref 8===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_path_challenge_frame(self, data: bytes) -> Dict:
+ return {"data": hexdump(data), "frame_type": "PATH_CHALLENGE"}
+
===========changed ref 9===========
# module: aioquic.quic.packet
+ @dataclass
+ class QuicNewConnectionIdFrame:
+ sequence_number: int
+ retire_prior_to: int
+ connection_id: bytes
+ stateless_reset_token: bytes
+
===========changed ref 10===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_retire_connection_id_frame(self, sequence_number: int) -> Dict:
+ return {
+ "frame_type": "RETIRE_CONNECTION_ID",
+ "sequence_number": str(sequence_number),
+ }
+
===========changed ref 11===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_new_token_frame(self, token: bytes) -> Dict:
+ return {
+ "frame_type": "NEW_TOKEN",
+ "length": str(len(token)),
+ "token": hexdump(token),
+ }
+
===========changed ref 12===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_max_stream_data_frame(self, maximum: int, stream_id: int) -> Dict:
+ return {
+ "frame_type": "MAX_STREAM_DATA",
+ "id": str(stream_id),
+ "maximum": str(maximum),
+ }
+
===========changed ref 13===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_stop_sending_frame(self, error_code: int, stream_id: int) -> Dict:
+ return {
+ "frame_type": "STOP_SENDING",
+ "id": str(stream_id),
+ "error_code": error_code,
+ }
+
===========changed ref 14===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_reset_stream_frame(
+ self, error_code: int, final_size: int, stream_id: int
+ ) -> Dict:
+ return {
+ "error_code": error_code,
+ "final_size": str(final_size),
+ "frame_type": "RESET_STREAM",
+ }
+
===========changed ref 15===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_stream_data_blocked_frame(self, limit: int, stream_id: int) -> Dict:
+ return {
+ "frame_type": "STREAM_DATA_BLOCKED",
+ "limit": str(limit),
+ "stream_id": str(stream_id),
+ }
+
===========changed ref 16===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_ack_frame(self, ranges: RangeSet, delay: float) -> Dict:
- def encode_ack_frame(self, rangeset: RangeSet, delay: float) -> Dict:
return {
"ack_delay": str(int(delay * 1000)), # convert to ms
+ "acked_ranges": [[str(x.start), str(x.stop - 1)] for x in ranges],
- "acked_ranges": [[str(x.start), str(x.stop - 1)] for x in rangeset],
"frame_type": "ACK",
}
===========changed ref 17===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_connection_close_frame(
+ self, error_code: int, frame_type: Optional[int], reason_phrase: str
+ ) -> Dict:
+ attrs = {
+ "error_code": error_code,
+ "error_space": "application" if frame_type is None else "transport",
+ "frame_type": "CONNECTION_CLOSE",
+ "raw_error_code": error_code,
+ "reason": reason_phrase,
+ }
+ if frame_type is not None:
+ attrs["trigger_frame_type"] = frame_type
+
+ return attrs
+
|
aioquic.quic.connection/QuicConnection._handle_max_stream_data_frame
|
Modified
|
aiortc~aioquic
|
5df513ec4d4581d072fb2b3d09d4f23c5a88a1b4
|
[qlog] log more frames
|
<7>:<add>
<add> # log frame
<add> if self._quic_logger is not None:
<add> context.quic_logger_frames.append(
<add> self._quic_logger.encode_max_stream_data_frame(
<add> maximum=max_stream_data, stream_id=stream_id
<add> )
<add> )
|
# module: aioquic.quic.connection
class QuicConnection:
def _handle_max_stream_data_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
<0> """
<1> Handle a MAX_STREAM_DATA frame.
<2>
<3> This adjusts the amount of data we can send on a specific stream.
<4> """
<5> stream_id = buf.pull_uint_var()
<6> max_stream_data = buf.pull_uint_var()
<7>
<8> # check stream direction
<9> self._assert_stream_can_send(frame_type, stream_id)
<10>
<11> stream = self._get_or_create_stream(frame_type, stream_id)
<12> if max_stream_data > stream.max_stream_data_remote:
<13> self._logger.debug(
<14> "Stream %d remote max_stream_data raised to %d",
<15> stream_id,
<16> max_stream_data,
<17> )
<18> stream.max_stream_data_remote = max_stream_data
<19>
|
===========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, quic_logger_frames: Optional[List[Any]], time: float)
at: aioquic.quic.connection.QuicConnection.__init__
self._quic_logger = configuration.quic_logger
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
self._remote_max_data = 0
at: aioquic.quic.connection.QuicConnection._handle_max_data_frame
max_data = buf.pull_uint_var()
at: aioquic.quic.connection.QuicReceiveContext
quic_logger_frames: Optional[List[Any]]
at: logging.LoggerAdapter
debug(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
===========changed ref 0===========
# module: aioquic.quic.connection
class QuicConnection:
def _handle_data_blocked_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a DATA_BLOCKED frame.
"""
+ limit = buf.pull_uint_var()
- buf.pull_uint_var() # limit
===========changed ref 1===========
# module: aioquic.quic.connection
class QuicConnection:
def _handle_max_data_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a MAX_DATA frame.
This adjusts the total amount of we can send to the peer.
"""
max_data = buf.pull_uint_var()
+
+ # log frame
+ if self._quic_logger is not None:
+ context.quic_logger_frames.append(
+ self._quic_logger.encode_max_data_frame(maximum=max_data)
+ )
+
if max_data > self._remote_max_data:
self._logger.debug("Remote max_data raised to %d", max_data)
self._remote_max_data = max_data
===========changed ref 2===========
# module: aioquic.quic.connection
class QuicConnection:
def _handle_connection_close_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a CONNECTION_CLOSE frame.
"""
if frame_type == QuicFrameType.TRANSPORT_CLOSE:
error_code, frame_type, reason_phrase = pull_transport_close_frame(buf)
else:
error_code, reason_phrase = pull_application_close_frame(buf)
frame_type = None
+
+ # log frame
+ if self._quic_logger is not None:
+ context.quic_logger_frames.append(
+ self._quic_logger.encode_connection_close_frame(
+ error_code=error_code,
+ frame_type=frame_type,
+ reason_phrase=reason_phrase,
+ )
+ )
+
self._logger.info(
"Connection close code 0x%X, reason %s", error_code, reason_phrase
)
self._close_event = events.ConnectionTerminated(
error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase
)
self._close_begin(is_initiator=False, now=context.time)
===========changed ref 3===========
# module: aioquic.quic.logger
+ def hexdump(data: bytes) -> str:
+ return binascii.hexlify(data).decode("ascii")
+
===========changed ref 4===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_max_data_frame(self, maximum: int) -> Dict:
+ return {"frame_type": "MAX_DATA", "maximum": str(maximum)}
+
===========changed ref 5===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_max_streams_frame(self, maximum: int) -> Dict:
+ return {"frame_type": "MAX_STREAMS", "maximum": str(maximum)}
+
===========changed ref 6===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_data_blocked_frame(self, limit: int) -> Dict:
+ return {"frame_type": "DATA_BLOCKED", "limit": str(limit)}
+
===========changed ref 7===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_streams_blocked_frame(self, limit: int) -> Dict:
+ return {"frame_type": "STREAMS_BLOCKED", "limit": str(limit)}
+
===========changed ref 8===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_path_response_frame(self, data: bytes) -> Dict:
+ return {"data": hexdump(data), "frame_type": "PATH_RESPONSE"}
+
===========changed ref 9===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_path_challenge_frame(self, data: bytes) -> Dict:
+ return {"data": hexdump(data), "frame_type": "PATH_CHALLENGE"}
+
===========changed ref 10===========
# module: aioquic.quic.packet
+ @dataclass
+ class QuicNewConnectionIdFrame:
+ sequence_number: int
+ retire_prior_to: int
+ connection_id: bytes
+ stateless_reset_token: bytes
+
===========changed ref 11===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_retire_connection_id_frame(self, sequence_number: int) -> Dict:
+ return {
+ "frame_type": "RETIRE_CONNECTION_ID",
+ "sequence_number": str(sequence_number),
+ }
+
===========changed ref 12===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_new_token_frame(self, token: bytes) -> Dict:
+ return {
+ "frame_type": "NEW_TOKEN",
+ "length": str(len(token)),
+ "token": hexdump(token),
+ }
+
===========changed ref 13===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_max_stream_data_frame(self, maximum: int, stream_id: int) -> Dict:
+ return {
+ "frame_type": "MAX_STREAM_DATA",
+ "id": str(stream_id),
+ "maximum": str(maximum),
+ }
+
===========changed ref 14===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_stop_sending_frame(self, error_code: int, stream_id: int) -> Dict:
+ return {
+ "frame_type": "STOP_SENDING",
+ "id": str(stream_id),
+ "error_code": error_code,
+ }
+
===========changed ref 15===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_reset_stream_frame(
+ self, error_code: int, final_size: int, stream_id: int
+ ) -> Dict:
+ return {
+ "error_code": error_code,
+ "final_size": str(final_size),
+ "frame_type": "RESET_STREAM",
+ }
+
|
aioquic.quic.connection/QuicConnection._handle_max_streams_bidi_frame
|
Modified
|
aiortc~aioquic
|
5df513ec4d4581d072fb2b3d09d4f23c5a88a1b4
|
[qlog] log more frames
|
<6>:<add>
<add> # log frame
<add> if self._quic_logger is not None:
<add> context.quic_logger_frames.append(
<add> self._quic_logger.encode_max_streams_frame(maximum=max_streams)
<add> )
<add>
|
# module: aioquic.quic.connection
class QuicConnection:
def _handle_max_streams_bidi_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
<0> """
<1> Handle a MAX_STREAMS_BIDI frame.
<2>
<3> This raises number of bidirectional streams we can initiate to the peer.
<4> """
<5> max_streams = buf.pull_uint_var()
<6> if max_streams > self._remote_max_streams_bidi:
<7> self._logger.debug("Remote max_streams_bidi raised to %d", max_streams)
<8> self._remote_max_streams_bidi = max_streams
<9> self._unblock_streams(is_unidirectional=False)
<10>
|
===========unchanged ref 0===========
at: aioquic._buffer
Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)
at: aioquic.quic.connection
QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, quic_logger_frames: Optional[List[Any]], time: float)
at: aioquic.quic.connection.QuicConnection
_assert_stream_can_send(frame_type: int, stream_id: int) -> None
_get_or_create_stream(frame_type: int, stream_id: int) -> QuicStream
at: aioquic.quic.connection.QuicConnection.__init__
self._logger = QuicConnectionAdapter(
logger, {"host_cid": dump_cid(self.host_cid)}
)
at: aioquic.quic.connection.QuicConnection._handle_max_stream_data_frame
stream_id = buf.pull_uint_var()
max_stream_data = buf.pull_uint_var()
at: aioquic.quic.stream.QuicStream.__init__
self.max_stream_data_remote = max_stream_data_remote
===========changed ref 0===========
# module: aioquic.quic.connection
class QuicConnection:
def _handle_data_blocked_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a DATA_BLOCKED frame.
"""
+ limit = buf.pull_uint_var()
- buf.pull_uint_var() # limit
===========changed ref 1===========
# module: aioquic.quic.connection
class QuicConnection:
def _handle_max_data_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a MAX_DATA frame.
This adjusts the total amount of we can send to the peer.
"""
max_data = buf.pull_uint_var()
+
+ # log frame
+ if self._quic_logger is not None:
+ context.quic_logger_frames.append(
+ self._quic_logger.encode_max_data_frame(maximum=max_data)
+ )
+
if max_data > self._remote_max_data:
self._logger.debug("Remote max_data raised to %d", max_data)
self._remote_max_data = max_data
===========changed ref 2===========
# module: aioquic.quic.connection
class QuicConnection:
def _handle_max_stream_data_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a MAX_STREAM_DATA frame.
This adjusts the amount of data we can send on a specific stream.
"""
stream_id = buf.pull_uint_var()
max_stream_data = buf.pull_uint_var()
+
+ # log frame
+ if self._quic_logger is not None:
+ context.quic_logger_frames.append(
+ self._quic_logger.encode_max_stream_data_frame(
+ maximum=max_stream_data, stream_id=stream_id
+ )
+ )
# check stream direction
self._assert_stream_can_send(frame_type, stream_id)
stream = self._get_or_create_stream(frame_type, stream_id)
if max_stream_data > stream.max_stream_data_remote:
self._logger.debug(
"Stream %d remote max_stream_data raised to %d",
stream_id,
max_stream_data,
)
stream.max_stream_data_remote = max_stream_data
===========changed ref 3===========
# module: aioquic.quic.connection
class QuicConnection:
def _handle_connection_close_frame(
self, context: QuicReceiveContext, frame_type: int, buf: Buffer
) -> None:
"""
Handle a CONNECTION_CLOSE frame.
"""
if frame_type == QuicFrameType.TRANSPORT_CLOSE:
error_code, frame_type, reason_phrase = pull_transport_close_frame(buf)
else:
error_code, reason_phrase = pull_application_close_frame(buf)
frame_type = None
+
+ # log frame
+ if self._quic_logger is not None:
+ context.quic_logger_frames.append(
+ self._quic_logger.encode_connection_close_frame(
+ error_code=error_code,
+ frame_type=frame_type,
+ reason_phrase=reason_phrase,
+ )
+ )
+
self._logger.info(
"Connection close code 0x%X, reason %s", error_code, reason_phrase
)
self._close_event = events.ConnectionTerminated(
error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase
)
self._close_begin(is_initiator=False, now=context.time)
===========changed ref 4===========
# module: aioquic.quic.logger
+ def hexdump(data: bytes) -> str:
+ return binascii.hexlify(data).decode("ascii")
+
===========changed ref 5===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_max_data_frame(self, maximum: int) -> Dict:
+ return {"frame_type": "MAX_DATA", "maximum": str(maximum)}
+
===========changed ref 6===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_max_streams_frame(self, maximum: int) -> Dict:
+ return {"frame_type": "MAX_STREAMS", "maximum": str(maximum)}
+
===========changed ref 7===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_data_blocked_frame(self, limit: int) -> Dict:
+ return {"frame_type": "DATA_BLOCKED", "limit": str(limit)}
+
===========changed ref 8===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_streams_blocked_frame(self, limit: int) -> Dict:
+ return {"frame_type": "STREAMS_BLOCKED", "limit": str(limit)}
+
===========changed ref 9===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_path_response_frame(self, data: bytes) -> Dict:
+ return {"data": hexdump(data), "frame_type": "PATH_RESPONSE"}
+
===========changed ref 10===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_path_challenge_frame(self, data: bytes) -> Dict:
+ return {"data": hexdump(data), "frame_type": "PATH_CHALLENGE"}
+
===========changed ref 11===========
# module: aioquic.quic.packet
+ @dataclass
+ class QuicNewConnectionIdFrame:
+ sequence_number: int
+ retire_prior_to: int
+ connection_id: bytes
+ stateless_reset_token: bytes
+
===========changed ref 12===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_retire_connection_id_frame(self, sequence_number: int) -> Dict:
+ return {
+ "frame_type": "RETIRE_CONNECTION_ID",
+ "sequence_number": str(sequence_number),
+ }
+
===========changed ref 13===========
# module: aioquic.quic.logger
class QuicLogger:
+ def encode_new_token_frame(self, token: bytes) -> Dict:
+ return {
+ "frame_type": "NEW_TOKEN",
+ "length": str(len(token)),
+ "token": hexdump(token),
+ }
+
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.