{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \",\n end_stream=True,\n )\n self.assertEqual(h3_server._update(), [])\n \n # receive response\n transfer(quic_server, quic_client)\n events = h3_client._update()\n self.assertEqual(len(events), 2)\n \n self.assertTrue(isinstance(events[0], ResponseReceived))\n self.assertEqual(\n events[0].headers,\n [(b\":status\", b\"200\"), (b\"content-type\", b\"text/html; charset=utf-8\")],\n )\n self.assertEqual(events[0].stream_id, stream_id)\n self.assertEqual(events[0].stream_ended, False)\n \n self.assertTrue(isinstance(events[1], DataReceived))\n self.assertEqual(events[1].data, b\"hello\")\n self.assertEqual(events[1].stream_id, stream_id)\n self.assertEqual(events[1].stream_ended, True)\n \n \n===========unchanged ref 0===========\n at: aioquic.h3.connection\n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection\n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: Headers) -> None\n \n _update() -> List[Event]\n \n at: aioquic.h3.events\n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n RequestReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: tests.test_connection\n client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={})\n \n transfer(sender, receiver)\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n _testMethodDoc: str\n \n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertTrue(expr: Any, msg: Any=...) -> None\n \n "}}},{"rowIdx":2907,"cells":{"path":{"kind":"string","value":"examples.http3/run"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"45119d225558aab3246fbe63ea46dfcd90a96074"},"commit_message":{"kind":"string","value":"[http3] use :authority pseudo-header instead of Host header"},"ground_truth":{"kind":"string","value":"<32>: (b\":scheme\", parsed.scheme.encode(\"utf8\")),\n (b\":authority\", parsed.netloc.encode(\"utf8\")),\n (b\":scheme\", b\"https\"),\n<34>: (b\"host\", server_name.encode(\"utf8\")),\n"},"main_code":{"kind":"string","value":" # module: examples.http3\n def run(url: str) -> None:\n <0> # parse URL\n <1> parsed = urlparse(url)\n <2> assert parsed.scheme == \"https\", \"Only HTTPS URLs are supported.\"\n <3> if \":\" in parsed.netloc:\n <4> server_name, port_str = parsed.netloc.split(\":\")\n <5> port = int(port_str)\n <6> else:\n <7> server_name = parsed.netloc\n <8> port = 443\n <9> \n<10> # prepare socket\n<11> server_addr = (socket.gethostbyname(server_name), port)\n<12> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n<13> \n<14> # prepare QUIC connection\n<15> quic = QuicConnection(\n<16> configuration=QuicConfiguration(\n<17> alpn_protocols=[\"h3-20\"],\n<18> is_client=True,\n<19> secrets_log_file=open(\"/tmp/ssl.log\", \"w\"),\n<20> server_name=server_name,\n<21> )\n<22> )\n<23> quic.connect(server_addr, now=time.time())\n<24> \n<25> # send request\n<26> conn = H3Connection(quic)\n<27> stream_id = quic.get_next_available_stream_id()\n<28> conn.send_headers(\n<29> stream_id=stream_id,\n<30> headers=[\n<31> (b\":method\", b\"GET\"),\n<32> (b\":scheme\", b\"https\"),\n<33> (b\":path\", parsed.path.encode(\"utf8\")),\n<34> (b\"host\", server_name.encode(\"utf8\")),\n<35> ],\n<36> )\n<37> conn.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n<38> for data, addr in quic.datagrams_to_send(now=time.time()):\n<39> sock.sendto(data, addr)\n<40> \n<41> # handle events\n<42> stream_ended = False\n<43> while not stream_ended:\n<44> data"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: examples.http3\n def run(url: str) -> None:\n # offset: 1\n for event in conn.receive_datagram(data, addr, now=time.time()):\n print(event)\n if isinstance(event, (DataReceived, ResponseReceived)):\n stream_ended = event.stream_ended\n \n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n \n===========unchanged ref 0===========\n at: aioquic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_19,\n QuicProtocolVersion.DRAFT_20,\n ]\n ))\n \n at: aioquic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n certificate: Any = None\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n private_key: Any = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[tls.SessionTicket] = None\n \n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_19,\n QuicProtocolVersion.DRAFT_20,\n ]\n )\n \n at: aioquic.connection\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.connection.QuicConnection\n connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None\n \n datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]]\n \n get_next_available_stream_id(is_unidirectional=False) -> int\n \n at: aioquic.h3.connection\n H3Connection(quic: QuicConnection)\n \n \n===========unchanged ref 1===========\n at: aioquic.h3.connection.H3Connection\n receive_datagram(data: bytes, addr: Any, now: float) -> List[Event]\n \n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: Headers) -> None\n \n at: aioquic.h3.events\n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: socket\n AF_INET: AddressFamily\n \n SOCK_DGRAM: SocketKind\n \n socket(family: int=..., type: int=..., proto: int=..., fileno: Optional[int]=...)\n \n gethostbyname(hostname: str) -> str\n \n at: socket.socket\n family: int\n \n type: int\n \n proto: int\n \n recvfrom(bufsize: int, flags: int=...) -> Tuple[bytes, _RetAddress]\n \n sendto(data: bytes, address: _Address) -> int\n sendto(data: bytes, flags: int, address: _Address) -> int\n \n at: time\n time() -> float\n \n at: urllib.parse\n urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult\n urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes\n \n \n===========changed ref 0===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_connect(self):\n with client_and_server(\n client_options={\"alpn_protocols\": [\"h3-20\"]},\n server_options={\"alpn_protocols\": [\"h3-20\"]},\n ) as (quic_client, quic_server):\n h3_client = H3Connection(quic_client)\n h3_server = H3Connection(quic_server)\n \n # send request\n stream_id = quic_client.get_next_available_stream_id()\n h3_client.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":method\", b\"GET\"),\n (b\":scheme\", b\"https\"),\n + (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/\"),\n - (b\"host\", b\"localhost\"),\n ],\n )\n h3_client.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n self.assertEqual(h3_client._update(), [])\n \n # receive request\n transfer(quic_client, quic_server)\n events = h3_server._update()\n self.assertEqual(len(events), 2)\n \n self.assertTrue(isinstance(events[0], RequestReceived))\n self.assertEqual(\n events[0].headers,\n [\n (b\":method\", b\"GET\"),\n (b\":scheme\", b\"https\"),\n + (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/\"),\n - (b\"host\", b\"localhost\"),\n ],\n )\n self.assertEqual(events[0].stream_id, stream_id)\n self.assertEqual(events[0].stream_ended, False)\n \n self.assertTrue(isinstance(events[1], DataReceived))\n self.assertEqual(events[1].data, b\"\")\n self.assert\n===========changed ref 1===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_connect(self):\n # offset: 1\n instance(events[1], DataReceived))\n self.assertEqual(events[1].data, b\"\")\n self.assertEqual(events[1].stream_id, stream_id)\n self.assertEqual(events[1].stream_ended, True)\n \n # send response\n h3_server.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":status\", b\"200\"),\n (b\"content-type\", b\"text/html; charset=utf-8\"),\n ],\n )\n h3_server.send_data(\n stream_id=stream_id,\n data=b\"hello\",\n end_stream=True,\n )\n self.assertEqual(h3_server._update(), [])\n \n # receive response\n transfer(quic_server, quic_client)\n events = h3_client._update()\n self.assertEqual(len(events), 2)\n \n self.assertTrue(isinstance(events[0], ResponseReceived))\n self.assertEqual(\n events[0].headers,\n [(b\":status\", b\"200\"), (b\"content-type\", b\"text/html; charset=utf-8\")],\n )\n self.assertEqual(events[0].stream_id, stream_id)\n self.assertEqual(events[0].stream_ended, False)\n \n self.assertTrue(isinstance(events[1], DataReceived))\n self.assertEqual(events[1].data, b\"hello\")\n self.assertEqual(events[1].stream_id, stream_id)\n self.assertEqual(events[1].stream_ended, True)\n "}}},{"rowIdx":2908,"cells":{"path":{"kind":"string","value":"aioquic.asyncio.compat/_AsyncGeneratorContextManager.__aexit__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"7e32246f1b5d7512b3e87487a873417ae4b39537"},"commit_message":{"kind":"string","value":"[asyncio] drop some unused Python 3.6 compatibility code"},"ground_truth":{"kind":"string","value":" <1>: if value is None:\n <2>: value = typ()\n"},"main_code":{"kind":"string","value":" # module: aioquic.asyncio.compat\n class _AsyncGeneratorContextManager(ContextDecorator):\n def __aexit__(self, typ, value, traceback):\n <0> if typ is not None:\n <1> if value is None:\n <2> value = typ()\n <3> await self.gen.athrow(typ, value, traceback)\n <4> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.asyncio.compat._AsyncGeneratorContextManager.__init__\n self.gen = func(*args, **kwds)\n \n "}}},{"rowIdx":2909,"cells":{"path":{"kind":"string","value":"tests.test_tls/ContextTest.test_handshake_with_x25519"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"c8c63e2a9b57451c7fcb1a9fc707300f3c710145"},"commit_message":{"kind":"string","value":"[travis] restore X25519 test"},"ground_truth":{"kind":"string","value":" <4>: try:\n self._handshake(client, server)\n self._handshake(client, server)\n <5>: except UnsupportedAlgorithm as exc:\n self.skipTest(str(exc))\n"},"main_code":{"kind":"string","value":" # module: tests.test_tls\n class ContextTest(TestCase):\n - @skipIf(os.environ.get(\"TRAVIS\") == \"true\", \"travis lacks a modern OpenSSL\")\n def test_handshake_with_x25519(self):\n <0> client = self.create_client()\n <1> client._supported_groups = [tls.Group.X25519]\n <2> server = self.create_server()\n <3> \n <4> self._handshake(client, server)\n <5> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.tls\n Group(x: Union[str, bytes, bytearray], base: int)\n Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n at: aioquic.tls.Context.__init__\n self._supported_groups = [Group.SECP256R1]\n \n at: tests.test_tls.ContextTest\n create_client()\n \n create_server()\n \n "}}},{"rowIdx":2910,"cells":{"path":{"kind":"string","value":"aioquic.tls/Context.handle_message"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"6039421f44fac3f2d5916b461b10fa6cac727867"},"commit_message":{"kind":"string","value":"[tls] remove an impossible code branch"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: aioquic.tls\n class Context:\n def handle_message(\n self, input_data: bytes, output_buf: Dict[Epoch, Buffer]\n ) -> None:\n <0> if self.state == State.CLIENT_HANDSHAKE_START:\n <1> self._client_send_hello(output_buf[Epoch.INITIAL])\n <2> return\n <3> \n <4> self._receive_buffer += input_data\n <5> while len(self._receive_buffer) >= 4:\n <6> # determine message length\n <7> message_type = self._receive_buffer[0]\n <8> message_length = 0\n <9> for b in self._receive_buffer[1:4]:\n<10> message_length = (message_length << 8) | b\n<11> message_length += 4\n<12> \n<13> # check message is complete\n<14> if len(self._receive_buffer) < message_length:\n<15> break\n<16> message = self._receive_buffer[:message_length]\n<17> self._receive_buffer = self._receive_buffer[message_length:]\n<18> \n<19> input_buf = Buffer(data=message)\n<20> \n<21> # client states\n<22> \n<23> if self.state == State.CLIENT_EXPECT_SERVER_HELLO:\n<24> if message_type == HandshakeType.SERVER_HELLO:\n<25> self._client_handle_hello(input_buf, output_buf[Epoch.INITIAL])\n<26> else:\n<27> raise AlertUnexpectedMessage\n<28> elif self.state == State.CLIENT_EXPECT_ENCRYPTED_EXTENSIONS:\n<29> if message_type == HandshakeType.ENCRYPTED_EXTENSIONS:\n<30> self._client_handle_encrypted_extensions(input_buf)\n<31> else:\n<32> raise AlertUnexpectedMessage\n<33> elif self.state == State.CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE:\n<34> if message_type == HandshakeType.CERTIFICATE:\n<35> self._client_handle_certificate(input_buf)\n<36> else:\n<37> # FIXME: handle certificate request\n<38> raise AlertUnexpectedMessage\n<39> elif self.state == State.CLIENT_EXPECT_CERTIFICATE"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.tls\n class Context:\n def handle_message(\n self, input_data: bytes, output_buf: Dict[Epoch, Buffer]\n ) -> None:\n # offset: 1\n if message_type == HandshakeType.CERTIFICATE_VERIFY:\n self._client_handle_certificate_verify(input_buf)\n else:\n raise AlertUnexpectedMessage\n elif self.state == State.CLIENT_EXPECT_FINISHED:\n if message_type == HandshakeType.FINISHED:\n self._client_handle_finished(input_buf, output_buf[Epoch.HANDSHAKE])\n else:\n raise AlertUnexpectedMessage\n elif self.state == State.CLIENT_POST_HANDSHAKE:\n if message_type == HandshakeType.NEW_SESSION_TICKET:\n self._client_handle_new_session_ticket(input_buf)\n else:\n raise AlertUnexpectedMessage\n \n # server states\n \n elif self.state == State.SERVER_EXPECT_CLIENT_HELLO:\n if message_type == HandshakeType.CLIENT_HELLO:\n self._server_handle_hello(\n input_buf,\n output_buf[Epoch.INITIAL],\n output_buf[Epoch.HANDSHAKE],\n output_buf[Epoch.ONE_RTT],\n )\n else:\n raise AlertUnexpectedMessage\n elif self.state == State.SERVER_EXPECT_FINISHED:\n if message_type == HandshakeType.FINISHED:\n self._server_handle_finished(input_buf, output_buf[Epoch.ONE_RTT])\n else:\n raise AlertUnexpectedMessage\n elif self.state == State.SERVER_POST_HANDSHAKE:\n raise AlertUnexpectedMessage\n \n # should not happen\n \n else:\n raise Exception(\"unhandled state\")\n \n assert input_buf.eof()\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n eof() -> bool\n \n at: aioquic.tls\n AlertUnexpectedMessage(*args: object)\n \n Epoch()\n \n State()\n \n HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n HandshakeType(x: Union[str, bytes, bytearray], base: int)\n \n NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b\"\", ticket: bytes=b\"\", max_early_data_size: Optional[int]=None)\n \n SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list))\n \n at: aioquic.tls.Context\n _client_send_hello(output_buf: Buffer) -> None\n \n _client_handle_hello(input_buf: Buffer, output_buf: Buffer) -> None\n \n _client_handle_encrypted_extensions(input_buf: Buffer) -> None\n \n _client_handle_certificate(input_buf: Buffer) -> None\n \n _client_handle_certificate_verify(input_buf: Buffer) -> None\n \n _client_handle_finished(input_buf: Buffer, output_buf: Buffer) -> None\n \n _client_handle_new_session_ticket(input_buf: Buffer) -> None\n \n _server_handle_hello(input_buf: Buffer, initial_buf: Buffer, handshake_buf: Buffer, onertt_buf: Buffer) -> None\n \n _server_handle_finished(input_buf: Buffer, output_buf: Buffer) -> None\n \n \n===========unchanged ref 1===========\n at: aioquic.tls.Context.__init__\n self.key_schedule: Optional[KeySchedule] = None\n \n self._receive_buffer = b\"\"\n \n self.state = State.CLIENT_HANDSHAKE_START\n self.state = State.SERVER_EXPECT_CLIENT_HELLO\n \n at: aioquic.tls.Context._client_handle_hello\n self.key_schedule = self._key_schedule_psk\n self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite)\n \n at: aioquic.tls.Context._server_handle_hello\n self.key_schedule = KeySchedule(cipher_suite)\n \n at: aioquic.tls.Context._set_state\n self.state = state\n \n at: aioquic.tls.KeySchedule\n derive_secret(label: bytes) -> bytes\n \n at: typing\n Dict = _alias(dict, 2, inst=False, name='Dict')\n \n "}}},{"rowIdx":2911,"cells":{"path":{"kind":"string","value":"aioquic.tls/pull_server_hello"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"19b152cf33473ab435c21fc09d4980e7b490bb41"},"commit_message":{"kind":"string","value":"[tls] test NewSessionTicket and ServerHello with unknown extension"},"ground_truth":{"kind":"string","value":"<23>: hello.other_extensions.append(\n (extension_type, buf.pull_bytes(extension_length))\n buf.pull_bytes(extension_length)\n<24>: )\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n def pull_server_hello(buf: Buffer) -> ServerHello:\n <0> assert buf.pull_uint8() == HandshakeType.SERVER_HELLO\n <1> with pull_block(buf, 3):\n <2> assert buf.pull_uint16() == TLS_VERSION_1_2\n <3> server_random = buf.pull_bytes(32)\n <4> \n <5> hello = ServerHello(\n <6> random=server_random,\n <7> session_id=pull_opaque(buf, 1),\n <8> cipher_suite=pull_cipher_suite(buf),\n <9> compression_method=pull_compression_method(buf),\n<10> )\n<11> \n<12> # extensions\n<13> def pull_extension() -> None:\n<14> extension_type = buf.pull_uint16()\n<15> extension_length = buf.pull_uint16()\n<16> if extension_type == ExtensionType.SUPPORTED_VERSIONS:\n<17> hello.supported_version = buf.pull_uint16()\n<18> elif extension_type == ExtensionType.KEY_SHARE:\n<19> hello.key_share = pull_key_share(buf)\n<20> elif extension_type == ExtensionType.PRE_SHARED_KEY:\n<21> hello.pre_shared_key = buf.pull_uint16()\n<22> else:\n<23> buf.pull_bytes(extension_length)\n<24> \n<25> pull_list(buf, 2, pull_extension)\n<26> \n<27> return hello\n<28> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n pull_bytes(length: int) -> bytes\n \n pull_uint8() -> int\n \n pull_uint16() -> int\n \n at: aioquic.tls\n TLS_VERSION_1_2 = 0x0303\n \n ExtensionType(x: Union[str, bytes, bytearray], base: int)\n ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n HandshakeType(x: Union[str, bytes, bytearray], base: int)\n \n pull_cipher_suite(buf: Buffer) -> CipherSuite\n \n pull_compression_method(buf: Buffer) -> CompressionMethod\n \n pull_block(buf: Buffer, capacity: int) -> Generator\n \n pull_opaque(buf: Buffer, capacity: int) -> bytes\n \n pull_key_share(buf: Buffer) -> KeyShareEntry\n \n ServerHello(random: bytes, session_id: bytes, cipher_suite: CipherSuite, compression_method: CompressionMethod, key_share: Optional[KeyShareEntry]=None, pre_shared_key: Optional[int]=None, supported_version: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list))\n \n at: aioquic.tls.ServerHello\n random: bytes\n \n session_id: bytes\n \n cipher_suite: CipherSuite\n \n compression_method: CompressionMethod\n \n key_share: Optional[KeyShareEntry] = None\n \n pre_shared_key: Optional[int] = None\n \n supported_version: Optional[int] = None\n \n other_extensions: List[Tuple[int, bytes]] = field(default_factory=list)\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n @dataclass\n class ServerHello:\n random: bytes\n session_id: bytes\n cipher_suite: CipherSuite\n compression_method: CompressionMethod\n \n # extensions\n key_share: Optional[KeyShareEntry] = None\n pre_shared_key: Optional[int] = None\n supported_version: Optional[int] = None\n + other_extensions: List[Tuple[int, bytes]] = field(default_factory=list)\n "}}},{"rowIdx":2912,"cells":{"path":{"kind":"string","value":"aioquic.tls/pull_new_session_ticket"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"19b152cf33473ab435c21fc09d4980e7b490bb41"},"commit_message":{"kind":"string","value":"[tls] test NewSessionTicket and ServerHello with unknown extension"},"ground_truth":{"kind":"string","value":"<15>: new_session_ticket.other_extensions.append(\n (extension_type, buf.pull_bytes(extension_length))\n buf.pull_bytes(extension_length)\n<16>: )\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n def pull_new_session_ticket(buf: Buffer) -> NewSessionTicket:\n <0> new_session_ticket = NewSessionTicket()\n <1> \n <2> assert buf.pull_uint8() == HandshakeType.NEW_SESSION_TICKET\n <3> with pull_block(buf, 3):\n <4> new_session_ticket.ticket_lifetime = buf.pull_uint32()\n <5> new_session_ticket.ticket_age_add = buf.pull_uint32()\n <6> new_session_ticket.ticket_nonce = pull_opaque(buf, 1)\n <7> new_session_ticket.ticket = pull_opaque(buf, 2)\n <8> \n <9> def pull_extension() -> None:\n<10> extension_type = buf.pull_uint16()\n<11> extension_length = buf.pull_uint16()\n<12> if extension_type == ExtensionType.EARLY_DATA:\n<13> new_session_ticket.max_early_data_size = buf.pull_uint32()\n<14> else:\n<15> buf.pull_bytes(extension_length)\n<16> \n<17> pull_list(buf, 2, pull_extension)\n<18> \n<19> return new_session_ticket\n<20> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n pull_uint8() -> int\n \n pull_uint16() -> int\n \n pull_uint32() -> int\n \n at: aioquic.tls\n HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n HandshakeType(x: Union[str, bytes, bytearray], base: int)\n \n pull_block(buf: Buffer, capacity: int) -> Generator\n \n pull_opaque(buf: Buffer, capacity: int) -> bytes\n \n NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b\"\", ticket: bytes=b\"\", max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list))\n \n at: aioquic.tls.NewSessionTicket\n ticket_lifetime: int = 0\n \n ticket_age_add: int = 0\n \n at: dataclasses\n field(*, default_factory: Callable[[], _T], init: bool=..., repr: bool=..., hash: Optional[bool]=..., compare: bool=..., metadata: Optional[Mapping[str, Any]]=...) -> _T\n field(*, init: bool=..., repr: bool=..., hash: Optional[bool]=..., compare: bool=..., metadata: Optional[Mapping[str, Any]]=...) -> Any\n field(*, default: _T, init: bool=..., repr: bool=..., hash: Optional[bool]=..., compare: bool=..., metadata: Optional[Mapping[str, Any]]=...) -> _T\n \n at: typing\n Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')\n \n List = _alias(list, 1, inst=False, name='List')\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n @dataclass\n class NewSessionTicket:\n ticket_lifetime: int = 0\n ticket_age_add: int = 0\n ticket_nonce: bytes = b\"\"\n ticket: bytes = b\"\"\n \n # extensions\n max_early_data_size: Optional[int] = None\n + other_extensions: List[Tuple[int, bytes]] = field(default_factory=list)\n \n===========changed ref 1===========\n # module: aioquic.tls\n @dataclass\n class ServerHello:\n random: bytes\n session_id: bytes\n cipher_suite: CipherSuite\n compression_method: CompressionMethod\n \n # extensions\n key_share: Optional[KeyShareEntry] = None\n pre_shared_key: Optional[int] = None\n supported_version: Optional[int] = None\n + other_extensions: List[Tuple[int, bytes]] = field(default_factory=list)\n \n===========changed ref 2===========\n # module: aioquic.tls\n def pull_server_hello(buf: Buffer) -> ServerHello:\n assert buf.pull_uint8() == HandshakeType.SERVER_HELLO\n with pull_block(buf, 3):\n assert buf.pull_uint16() == TLS_VERSION_1_2\n server_random = buf.pull_bytes(32)\n \n hello = ServerHello(\n random=server_random,\n session_id=pull_opaque(buf, 1),\n cipher_suite=pull_cipher_suite(buf),\n compression_method=pull_compression_method(buf),\n )\n \n # extensions\n def pull_extension() -> None:\n extension_type = buf.pull_uint16()\n extension_length = buf.pull_uint16()\n if extension_type == ExtensionType.SUPPORTED_VERSIONS:\n hello.supported_version = buf.pull_uint16()\n elif extension_type == ExtensionType.KEY_SHARE:\n hello.key_share = pull_key_share(buf)\n elif extension_type == ExtensionType.PRE_SHARED_KEY:\n hello.pre_shared_key = buf.pull_uint16()\n else:\n + hello.other_extensions.append(\n + (extension_type, buf.pull_bytes(extension_length))\n - buf.pull_bytes(extension_length)\n + )\n \n pull_list(buf, 2, pull_extension)\n \n return hello\n "}}},{"rowIdx":2913,"cells":{"path":{"kind":"string","value":"tests.test_tls/ContextTest.test_server_unsupported_signature_algorithm"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"12350d38b9cdd4dcb161b70f9da74ca64b88563e"},"commit_message":{"kind":"string","value":"[tls] fix server-side support for EC certificate signatures"},"ground_truth":{"kind":"string","value":" <1>: client._signature_algorithms = [tls.SignatureAlgorithm.ED448]\n client._signature_algorithms = [tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA256]\n <4>: server._signature_algorithms = [tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA512]\n"},"main_code":{"kind":"string","value":" # module: tests.test_tls\n class ContextTest(TestCase):\n def test_server_unsupported_signature_algorithm(self):\n <0> client = self.create_client()\n <1> client._signature_algorithms = [tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA256]\n <2> \n <3> server = self.create_server()\n <4> server._signature_algorithms = [tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA512]\n <5> \n <6> with self.assertRaises(tls.AlertHandshakeFailure) as cm:\n <7> self._server_fail_hello(client, server)\n <8> self.assertEqual(str(cm.exception), \"No supported signature algorithm\")\n <9> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.tls\n State()\n \n at: aioquic.tls.Context\n handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None\n \n at: aioquic.tls.Context.__init__\n self.state = State.CLIENT_HANDSHAKE_START\n self.state = State.SERVER_EXPECT_CLIENT_HELLO\n \n at: aioquic.tls.Context._set_state\n self.state = state\n \n at: tests.test_tls\n create_buffers()\n \n merge_buffers(buffers)\n \n reset_buffers(buffers)\n \n at: tests.test_tls.ContextTest.test_server_unexpected_message\n server = self.create_server()\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n _testMethodDoc: str\n \n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_tls\n + def generate_ec_certificate(curve):\n + key = ec.generate_private_key(backend=default_backend(), curve=curve)\n + \n + subject = issuer = x509.Name(\n + [x509.NameAttribute(x509.NameOID.COMMON_NAME, \"example.com\")]\n + )\n + \n + cert = (\n + x509.CertificateBuilder()\n + .subject_name(subject)\n + .issuer_name(issuer)\n + .public_key(key.public_key())\n + .serial_number(x509.random_serial_number())\n + .not_valid_before(datetime.datetime.utcnow())\n + .not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=10))\n + .sign(key, hashes.SHA256(), default_backend())\n + )\n + return cert, key\n + \n===========changed ref 1===========\n # module: aioquic.tls\n class Context:\n def _server_handle_hello(\n self,\n input_buf: Buffer,\n initial_buf: Buffer,\n handshake_buf: Buffer,\n onertt_buf: Buffer,\n ) -> None:\n peer_hello = pull_client_hello(input_buf)\n + \n + # determine applicable signature algorithms\n + signature_algorithms: List[SignatureAlgorithm] = []\n + if isinstance(self.certificate_private_key, rsa.RSAPrivateKey):\n + signature_algorithms = [\n + SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n + SignatureAlgorithm.RSA_PKCS1_SHA256,\n + SignatureAlgorithm.RSA_PKCS1_SHA1,\n + ]\n + elif isinstance(\n + self.certificate_private_key, ec.EllipticCurvePrivateKey\n + ) and isinstance(self.certificate_private_key.curve, ec.SECP256R1):\n + signature_algorithms = [SignatureAlgorithm.ECDSA_SECP256R1_SHA256]\n \n # negotiate parameters\n cipher_suite = negotiate(\n self._cipher_suites,\n peer_hello.cipher_suites,\n AlertHandshakeFailure(\"No supported cipher suite\"),\n )\n compression_method = negotiate(\n self._compression_methods,\n peer_hello.compression_methods,\n AlertHandshakeFailure(\"No supported compression method\"),\n )\n negotiate(\n self._key_exchange_modes,\n peer_hello.key_exchange_modes,\n AlertHandshakeFailure(\"No supported key exchange mode\"),\n )\n signature_algorithm = negotiate(\n + signature_algorithms,\n - self._signature_algorithms,\n peer_hello.signature_algorithms,\n AlertHandshakeFailure(\"No supported signature algorithm\"),\n )\n supported_version = negotiate(\n self._supported_versions,\n peer_hello.supported_versions,\n AlertProtocolVersion(\"No supported protocol version\"),\n )\n \n # negotiate ALPN\n if self.alpn_protocols is not None:\n self\n===========changed ref 2===========\n # module: aioquic.tls\n class Context:\n def _server_handle_hello(\n self,\n input_buf: Buffer,\n initial_buf: Buffer,\n handshake_buf: Buffer,\n onertt_buf: Buffer,\n ) -> None:\n # offset: 1\n version\"),\n )\n \n # negotiate ALPN\n if self.alpn_protocols is not None:\n self.alpn_negotiated = negotiate(\n self.alpn_protocols,\n peer_hello.alpn_protocols,\n AlertHandshakeFailure(\"No common ALPN protocols\"),\n )\n \n self.client_random = peer_hello.random\n self.server_random = os.urandom(32)\n self.session_id = peer_hello.session_id\n self.received_extensions = peer_hello.other_extensions\n \n # select key schedule\n pre_shared_key = None\n if (\n self.get_session_ticket_cb is not None\n and peer_hello.pre_shared_key is not None\n and len(peer_hello.pre_shared_key.identities) == 1\n and len(peer_hello.pre_shared_key.binders) == 1\n ):\n # ask application to find session ticket\n identity = peer_hello.pre_shared_key.identities[0]\n session_ticket = self.get_session_ticket_cb(identity[0])\n \n # validate session ticket\n if (\n session_ticket is not None\n and session_ticket.is_valid\n and session_ticket.cipher_suite == cipher_suite\n ):\n self.key_schedule = KeySchedule(cipher_suite)\n self.key_schedule.extract(session_ticket.resumption_secret)\n \n binder_key = self.key_schedule.derive_secret(b\"res binder\")\n binder_length = self.key_schedule.algorithm.digest_size\n \n hash_offset =\n===========changed ref 3===========\n # module: aioquic.tls\n class Context:\n def _server_handle_hello(\n self,\n input_buf: Buffer,\n initial_buf: Buffer,\n handshake_buf: Buffer,\n onertt_buf: Buffer,\n ) -> None:\n # offset: 2\n buf.tell() - binder_length - 3\n binder = input_buf.data_slice(\n hash_offset + 3, hash_offset + 3 + binder_length\n )\n \n self.key_schedule.update_hash(input_buf.data_slice(0, hash_offset))\n expected_binder = self.key_schedule.finished_verify_data(binder_key)\n \n if binder != expected_binder:\n raise AlertHandshakeFailure(\"PSK validation failed\")\n \n self.key_schedule.update_hash(\n input_buf.data_slice(hash_offset, hash_offset + 3 + binder_length)\n )\n self._session_resumed = True\n \n # calculate early data key\n if peer_hello.early_data:\n early_key = self.key_schedule.derive_secret(b\"c e traffic\")\n self.early_data_accepted = True\n self.update_traffic_key_cb(\n Direction.DECRYPT,\n Epoch.ZERO_RTT,\n self.key_schedule.cipher_suite,\n early_key,\n )\n \n pre_shared_key = 0\n \n # if PSK is not used, initialize key schedule\n if pre_shared_key is None:\n self.key_schedule = KeySchedule(cipher_suite)\n self.key_schedule.extract(None)\n self.key_schedule.update_hash(input_buf.data)\n \n # perform key exchange\n public_key: Union[ec.EllipticCurvePublicKey, x25519.X25519PublicKey]\n shared_key: Optional[bytes] = None\n for key_share in peer_hello."}}},{"rowIdx":2914,"cells":{"path":{"kind":"string","value":"tests.test_tls/ContextTest._handshake"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"12350d38b9cdd4dcb161b70f9da74ca64b88563e"},"commit_message":{"kind":"string","value":"[tls] fix server-side support for EC certificate signatures"},"ground_truth":{"kind":"string","value":"<15>: self.assertGreaterEqual(len(client_input), 600)\n self.assertGreaterEqual(len(client_input), 2194)\n"},"main_code":{"kind":"string","value":" # module: tests.test_tls\n class ContextTest(TestCase):\n def _handshake(self, client, server):\n <0> # send client hello\n <1> client_buf = create_buffers()\n <2> client.handle_message(b\"\", client_buf)\n <3> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO)\n <4> server_input = merge_buffers(client_buf)\n <5> self.assertGreaterEqual(len(server_input), 219)\n <6> self.assertLessEqual(len(server_input), 264)\n <7> reset_buffers(client_buf)\n <8> \n <9> # handle client hello\n<10> # send server hello, encrypted extensions, certificate, certificate verify, finished, (session ticket)\n<11> server_buf = create_buffers()\n<12> server.handle_message(server_input, server_buf)\n<13> self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED)\n<14> client_input = merge_buffers(server_buf)\n<15> self.assertGreaterEqual(len(client_input), 2194)\n<16> self.assertLessEqual(len(client_input), 2316)\n<17> \n<18> reset_buffers(server_buf)\n<19> \n<20> # handle server hello, encrypted extensions, certificate, certificate verify, finished, (session ticket)\n<21> # send finished\n<22> client.handle_message(client_input, client_buf)\n<23> self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE)\n<24> server_input = merge_buffers(client_buf)\n<25> self.assertEqual(len(server_input), 52)\n<26> reset_buffers(client_buf)\n<27> \n<28> # handle finished\n<29> server.handle_message(server_input, server_buf)\n<30> self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE)\n<31> client_input = merge_buffers(server_buf)\n<32> self.assertEqual(len(client_input), 0)\n<33> \n<34> # check keys match\n<35> self.assertEqual(client._dec_key, server._enc"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_tls\n class ContextTest(TestCase):\n def _handshake(self, client, server):\n # offset: 1\n self.assertEqual(client._enc_key, server._dec_key)\n \n # check cipher suite\n self.assertEqual(\n client.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384\n )\n self.assertEqual(\n server.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384\n )\n \n \n===========unchanged ref 0===========\n at: aioquic.tls\n AlertDecryptError(*args: object)\n \n State()\n \n at: aioquic.tls.Context\n handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None\n \n at: aioquic.tls.Context.__init__\n self.state = State.CLIENT_HANDSHAKE_START\n self.state = State.SERVER_EXPECT_CLIENT_HELLO\n \n at: aioquic.tls.Context._set_state\n self.state = state\n \n at: tests.test_tls\n create_buffers()\n \n merge_buffers(buffers)\n \n reset_buffers(buffers)\n \n at: tests.test_tls.ContextTest.test_server_bad_finished_verify_data\n client = self.create_client()\n \n server = self.create_server()\n \n client_buf = create_buffers()\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertGreaterEqual(a: Any, b: Any, msg: Any=...) -> None\n \n assertLessEqual(a: Any, b: Any, msg: Any=...) -> None\n \n assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E]\n assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_tls\n class ContextTest(TestCase):\n def test_server_unsupported_signature_algorithm(self):\n client = self.create_client()\n + client._signature_algorithms = [tls.SignatureAlgorithm.ED448]\n - client._signature_algorithms = [tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA256]\n \n server = self.create_server()\n - server._signature_algorithms = [tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA512]\n \n with self.assertRaises(tls.AlertHandshakeFailure) as cm:\n self._server_fail_hello(client, server)\n self.assertEqual(str(cm.exception), \"No supported signature algorithm\")\n \n===========changed ref 1===========\n # module: tests.test_tls\n + def generate_ec_certificate(curve):\n + key = ec.generate_private_key(backend=default_backend(), curve=curve)\n + \n + subject = issuer = x509.Name(\n + [x509.NameAttribute(x509.NameOID.COMMON_NAME, \"example.com\")]\n + )\n + \n + cert = (\n + x509.CertificateBuilder()\n + .subject_name(subject)\n + .issuer_name(issuer)\n + .public_key(key.public_key())\n + .serial_number(x509.random_serial_number())\n + .not_valid_before(datetime.datetime.utcnow())\n + .not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=10))\n + .sign(key, hashes.SHA256(), default_backend())\n + )\n + return cert, key\n + \n===========changed ref 2===========\n # module: aioquic.tls\n class Context:\n def _server_handle_hello(\n self,\n input_buf: Buffer,\n initial_buf: Buffer,\n handshake_buf: Buffer,\n onertt_buf: Buffer,\n ) -> None:\n peer_hello = pull_client_hello(input_buf)\n + \n + # determine applicable signature algorithms\n + signature_algorithms: List[SignatureAlgorithm] = []\n + if isinstance(self.certificate_private_key, rsa.RSAPrivateKey):\n + signature_algorithms = [\n + SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n + SignatureAlgorithm.RSA_PKCS1_SHA256,\n + SignatureAlgorithm.RSA_PKCS1_SHA1,\n + ]\n + elif isinstance(\n + self.certificate_private_key, ec.EllipticCurvePrivateKey\n + ) and isinstance(self.certificate_private_key.curve, ec.SECP256R1):\n + signature_algorithms = [SignatureAlgorithm.ECDSA_SECP256R1_SHA256]\n \n # negotiate parameters\n cipher_suite = negotiate(\n self._cipher_suites,\n peer_hello.cipher_suites,\n AlertHandshakeFailure(\"No supported cipher suite\"),\n )\n compression_method = negotiate(\n self._compression_methods,\n peer_hello.compression_methods,\n AlertHandshakeFailure(\"No supported compression method\"),\n )\n negotiate(\n self._key_exchange_modes,\n peer_hello.key_exchange_modes,\n AlertHandshakeFailure(\"No supported key exchange mode\"),\n )\n signature_algorithm = negotiate(\n + signature_algorithms,\n - self._signature_algorithms,\n peer_hello.signature_algorithms,\n AlertHandshakeFailure(\"No supported signature algorithm\"),\n )\n supported_version = negotiate(\n self._supported_versions,\n peer_hello.supported_versions,\n AlertProtocolVersion(\"No supported protocol version\"),\n )\n \n # negotiate ALPN\n if self.alpn_protocols is not None:\n self\n===========changed ref 3===========\n # module: aioquic.tls\n class Context:\n def _server_handle_hello(\n self,\n input_buf: Buffer,\n initial_buf: Buffer,\n handshake_buf: Buffer,\n onertt_buf: Buffer,\n ) -> None:\n # offset: 1\n version\"),\n )\n \n # negotiate ALPN\n if self.alpn_protocols is not None:\n self.alpn_negotiated = negotiate(\n self.alpn_protocols,\n peer_hello.alpn_protocols,\n AlertHandshakeFailure(\"No common ALPN protocols\"),\n )\n \n self.client_random = peer_hello.random\n self.server_random = os.urandom(32)\n self.session_id = peer_hello.session_id\n self.received_extensions = peer_hello.other_extensions\n \n # select key schedule\n pre_shared_key = None\n if (\n self.get_session_ticket_cb is not None\n and peer_hello.pre_shared_key is not None\n and len(peer_hello.pre_shared_key.identities) == 1\n and len(peer_hello.pre_shared_key.binders) == 1\n ):\n # ask application to find session ticket\n identity = peer_hello.pre_shared_key.identities[0]\n session_ticket = self.get_session_ticket_cb(identity[0])\n \n # validate session ticket\n if (\n session_ticket is not None\n and session_ticket.is_valid\n and session_ticket.cipher_suite == cipher_suite\n ):\n self.key_schedule = KeySchedule(cipher_suite)\n self.key_schedule.extract(session_ticket.resumption_secret)\n \n binder_key = self.key_schedule.derive_secret(b\"res binder\")\n binder_length = self.key_schedule.algorithm.digest_size\n \n hash_offset ="}}},{"rowIdx":2915,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection.send_stream_data"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"44eb23c0f36f402b68bd4d7d9fe549146d697db9"},"commit_message":{"kind":"string","value":"[connection] check send_stream_data is called on valid streams"},"ground_truth":{"kind":"string","value":" <6>: if stream_is_client_initiated(stream_id) != self._is_client:\n if stream_id not in self._streams:\n raise ValueError(\"Cannot send data on unknown peer-initiated stream\")\n if stream_is_unidirectional(stream_id):\n raise ValueError(\n \"Cannot send data on peer-initiated unidirectional stream\"\n )\n \n"},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def send_stream_data(\n self, stream_id: int, data: bytes, end_stream: bool = False\n ) -> None:\n <0> \"\"\"\n <1> Send data on the specific stream.\n <2> \n <3> :param data: The data to be sent.\n <4> :param end_stream: If set to `True`, the FIN bit will be set.\n <5> \"\"\"\n <6> try:\n <7> stream = self._streams[stream_id]\n <8> except KeyError:\n <9> self._create_stream(stream_id=stream_id)\n<10> stream = self._streams[stream_id]\n<11> stream.write(data, end_stream=end_stream)\n<12> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.connection\n stream_is_client_initiated(stream_id: int) -> bool\n \n stream_is_unidirectional(stream_id: int) -> bool\n \n at: aioquic.connection.QuicConnection.__init__\n self._is_client = configuration.is_client\n \n self._streams: Dict[int, QuicStream] = {}\n \n "}}},{"rowIdx":2916,"cells":{"path":{"kind":"string","value":"aioquic.stream/QuicStream.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1f48726433a6b5d4abc34758228516aaa2432269"},"commit_message":{"kind":"string","value":"[streams] send STREAMS_BLOCKED if stream limit is exceeded"},"ground_truth":{"kind":"string","value":" <1>: self.is_blocked = False\n"},"main_code":{"kind":"string","value":" # module: aioquic.stream\n class QuicStream:\n def __init__(\n self,\n stream_id: Optional[int] = None,\n connection: Optional[Any] = None,\n max_stream_data_local: int = 0,\n max_stream_data_remote: int = 0,\n ) -> None:\n <0> self._connection = connection\n <1> self.max_stream_data_local = max_stream_data_local\n <2> self.max_stream_data_local_sent = max_stream_data_local\n <3> self.max_stream_data_remote = max_stream_data_remote\n <4> self.send_buffer_is_empty = True\n <5> \n <6> self._recv_buffer = bytearray()\n <7> self._recv_buffer_fin: Optional[int] = None\n <8> self._recv_buffer_start = 0 # the offset for the start of the buffer\n <9> self._recv_highest = 0 # the highest offset ever seen\n<10> self._recv_ranges = RangeSet()\n<11> \n<12> self._send_acked = RangeSet()\n<13> self._send_buffer = bytearray()\n<14> self._send_buffer_fin: Optional[int] = None\n<15> self._send_buffer_start = 0 # the offset for the start of the buffer\n<16> self._send_buffer_stop = 0 # the offset for the stop of the buffer\n<17> self._send_highest = 0\n<18> self._send_pending = RangeSet()\n<19> self._send_pending_eof = False\n<20> \n<21> self.__stream_id = stream_id\n<22> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.rangeset\n RangeSet(ranges: Iterable[range]=[])\n \n at: aioquic.stream.QuicStream.add_frame\n self._recv_highest = frame_end\n \n self._recv_buffer += bytearray(gap)\n \n self._recv_buffer_fin = frame_end\n \n at: aioquic.stream.QuicStream.get_frame\n self._send_pending_eof = False\n \n self.send_buffer_is_empty = True\n \n self._send_highest = stop\n \n at: aioquic.stream.QuicStream.on_data_delivery\n self.send_buffer_is_empty = False\n \n self._send_buffer_start += size\n \n self._send_pending_eof = True\n \n at: aioquic.stream.QuicStream.pull_data\n self._recv_buffer_start = r.stop\n \n at: aioquic.stream.QuicStream.write\n self.send_buffer_is_empty = False\n \n self._send_buffer += data\n \n self._send_buffer_stop += size\n \n self._send_buffer_fin = self._send_buffer_stop\n \n self._send_pending_eof = True\n \n "}}},{"rowIdx":2917,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1f48726433a6b5d4abc34758228516aaa2432269"},"commit_message":{"kind":"string","value":"[streams] send STREAMS_BLOCKED if stream limit is exceeded"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n original_connection_id: Optional[bytes] = None,\n session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,\n session_ticket_handler: Optional[tls.SessionTicketHandler] = None,\n ) -> None:\n <0> if configuration.is_client:\n <1> assert (\n <2> original_connection_id is None\n <3> ), \"Cannot set original_connection_id for a client\"\n <4> else:\n <5> assert (\n <6> configuration.certificate is not None\n <7> ), \"SSL certificate is required for a server\"\n <8> assert (\n <9> configuration.private_key is not None\n<10> ), \"SSL private key is required for a server\"\n<11> \n<12> # counters for debugging\n<13> self._stateless_retry_count = 0\n<14> self._version_negotiation_count = 0\n<15> \n<16> # configuration\n<17> self._configuration = configuration\n<18> self._is_client = configuration.is_client\n<19> \n<20> self._ack_delay = K_GRANULARITY\n<21> self._close_at: Optional[float] = None\n<22> self._close_event: Optional[events.ConnectionTerminated] = None\n<23> self._connect_called = False\n<24> self._cryptos: Dict[tls.Epoch, CryptoPair] = {}\n<25> self._crypto_buffers: Dict[tls.Epoch, Buffer] = {}\n<26> self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}\n<27> self._events: Deque[events.Event] = deque()\n<28> self._handshake_complete = False\n<29> self._handshake_confirmed = False\n<30> self._host_cids = [\n<31> QuicConnectionId(\n<32> cid=os.urandom(8),\n<33> sequence_number=0,\n<34> stateless_reset_token=os.urandom(16),\n<35> was_sent=True,\n<36> )\n<37> ]\n<38> self.host_cid = self._"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.connection\n class QuicConnection:\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n original_connection_id: Optional[bytes] = None,\n session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,\n session_ticket_handler: Optional[tls.SessionTicketHandler] = None,\n ) -> None:\n # offset: 1\n self._host_cid_seq = 1\n self._local_max_data = MAX_DATA_WINDOW\n self._local_max_data_sent = MAX_DATA_WINDOW\n self._local_max_data_used = 0\n self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW\n self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW\n self._local_max_stream_data_uni = MAX_DATA_WINDOW\n self._local_max_streams_bidi = 128\n self._local_max_streams_uni = 128\n self._logger = QuicConnectionAdapter(\n logger, {\"host_cid\": dump_cid(self.host_cid)}\n )\n self._loss = QuicPacketRecovery(send_probe=self._send_probe)\n self._loss_at: Optional[float] = None\n self._network_paths: List[QuicNetworkPath] = []\n self._original_connection_id = original_connection_id\n self._packet_number = 0\n self._parameters_received = False\n self._peer_cid = os.urandom(8)\n self._peer_cid_seq: Optional[int] = None\n self._peer_cid_available: List[QuicConnectionId] = []\n self._peer_token = b\"\"\n self._remote_idle_timeout = 0.0 # seconds\n self._remote_max_data = 0\n self._remote_max_data_used = 0\n self._remote_max_stream_data_bidi_local = 0\n self._remote_max_stream_data_bidi_remote = 0\n self._remote_max\n===========below chunk 1===========\n # module: aioquic.connection\n class QuicConnection:\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n original_connection_id: Optional[bytes] = None,\n session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,\n session_ticket_handler: Optional[tls.SessionTicketHandler] = None,\n ) -> None:\n # offset: 2\n i_local = 0\n self._remote_max_stream_data_bidi_remote = 0\n self._remote_max_stream_data_uni = 0\n self._remote_max_streams_bidi = 0\n self._remote_max_streams_uni = 0\n self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}\n self._spin_bit = False\n self._spin_bit_peer = False\n self._spin_highest_pn = 0\n self._state = QuicConnectionState.FIRSTFLIGHT\n self._streams: Dict[int, QuicStream] = {}\n self._version: Optional[int] = None\n \n # things to send\n self._close_pending = False\n self._ping_pending: List[int] = []\n self._probe_pending = False\n self._retire_connection_ids: List[int] = []\n \n # callbacks\n self._session_ticket_fetcher = session_ticket_fetcher\n self._session_ticket_handler = session_ticket_handler\n \n # frame handlers\n self.__frame_handlers = [\n (self._handle_padding_frame, EPOCHS(\"IZHO\")),\n (self._handle_padding_frame, EPOCHS(\"ZO\")),\n (self._handle_ack_frame, EPOCHS(\"IHO\")),\n (self._handle_ack_frame, EPOCHS(\"IHO\")),\n (self._handle_reset_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stop_s\n===========below chunk 2===========\n # module: aioquic.connection\n class QuicConnection:\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n original_connection_id: Optional[bytes] = None,\n session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,\n session_ticket_handler: Optional[tls.SessionTicketHandler] = None,\n ) -> None:\n # offset: 3\n frame, EPOCHS(\"ZO\")),\n (self._handle_crypto_frame, EPOCHS(\"IHO\")),\n (self._handle_new_token_frame, EPOCHS(\"O\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_max_data_frame, EPOCHS(\"ZO\")),\n (self._handle_max_stream_data_frame, EPOCHS(\"ZO\")),\n (self._handle_max_streams_bidi_frame, EPOCHS(\"ZO\")),\n (self._handle_max_streams_uni_frame, EPOCHS(\"ZO\")),\n (self._handle_data_blocked_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_data_blocked_frame, EPOCHS(\"ZO\")),\n (self._handle_streams_blocked_frame, EPOCHS(\"ZO\")),\n (self._handle_streams_blocked_frame, EPOCHS(\"\n===========below chunk 3===========\n # module: aioquic.connection\n class QuicConnection:\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n original_connection_id: Optional[bytes] = None,\n session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,\n session_ticket_handler: Optional[tls.SessionTicketHandler] = None,\n ) -> None:\n # offset: 4\n \")),\n (self._handle_new_connection_id_frame, EPOCHS(\"ZO\")),\n (self._handle_retire_connection_id_frame, EPOCHS(\"O\")),\n (self._handle_path_challenge_frame, EPOCHS(\"ZO\")),\n (self._handle_path_response_frame, EPOCHS(\"O\")),\n (self._handle_connection_close_frame, EPOCHS(\"IZHO\")),\n (self._handle_connection_close_frame, EPOCHS(\"ZO\")),\n ]\n \n "}}},{"rowIdx":2918,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection._create_stream"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1f48726433a6b5d4abc34758228516aaa2432269"},"commit_message":{"kind":"string","value":"[streams] send STREAMS_BLOCKED if stream limit is exceeded"},"ground_truth":{"kind":"string","value":" <8>: streams_blocked = self._streams_blocked_uni\n<12>: \n<13>: # check max streams\n<14>: if stream_id // 4 >= max_streams:\n<15>: raise ValueError(\"Too many streams open\")\n<16>: streams_blocked = self._streams_blocked_bidi\n<24>: \n # mark stream as blocked if needed\n if stream_id // 4 >= max_streams:\n stream.is_blocked = True\n streams_blocked.append(stream)\n self._streams_blocked_pending = True\n \n"},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def _create_stream(self, stream_id: int) -> QuicStream:\n <0> \"\"\"\n <1> Create a QUIC stream in order to send data to the peer.\n <2> \"\"\"\n <3> # determine limits\n <4> if stream_is_unidirectional(stream_id):\n <5> max_stream_data_local = 0\n <6> max_stream_data_remote = self._remote_max_stream_data_uni\n <7> max_streams = self._remote_max_streams_uni\n <8> else:\n <9> max_stream_data_local = self._local_max_stream_data_bidi_local\n<10> max_stream_data_remote = self._remote_max_stream_data_bidi_remote\n<11> max_streams = self._remote_max_streams_bidi\n<12> \n<13> # check max streams\n<14> if stream_id // 4 >= max_streams:\n<15> raise ValueError(\"Too many streams open\")\n<16> \n<17> # create stream\n<18> stream = self._streams[stream_id] = QuicStream(\n<19> connection=self,\n<20> stream_id=stream_id,\n<21> max_stream_data_local=max_stream_data_local,\n<22> max_stream_data_remote=max_stream_data_remote,\n<23> )\n<24> return stream\n<25> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.connection\n stream_is_unidirectional(stream_id: int) -> bool\n \n at: aioquic.connection.QuicConnection\n _push_crypto_data() -> None\n \n at: aioquic.connection.QuicConnection.__init__\n self._crypto_buffers: Dict[tls.Epoch, Buffer] = {}\n \n self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW\n \n self._remote_max_stream_data_bidi_remote = 0\n \n self._remote_max_stream_data_uni = 0\n \n self._remote_max_streams_bidi = 0\n \n self._remote_max_streams_uni = 0\n \n self._streams: Dict[int, QuicStream] = {}\n \n self._streams_blocked_bidi: List[QuicStream] = []\n \n self._streams_blocked_uni: List[QuicStream] = []\n \n at: aioquic.connection.QuicConnection._handle_max_streams_bidi_frame\n self._remote_max_streams_bidi = max_streams\n \n at: aioquic.connection.QuicConnection._handle_max_streams_uni_frame\n self._remote_max_streams_uni = max_streams\n \n at: aioquic.connection.QuicConnection._initialize\n self.tls = tls.Context(is_client=self._is_client, logger=self._logger)\n \n self._crypto_buffers = {\n tls.Epoch.INITIAL: Buffer(capacity=4096),\n tls.Epoch.HANDSHAKE: Buffer(capacity=4096),\n tls.Epoch.ONE_RTT: Buffer(capacity=4096),\n }\n \n at: aioquic.stream\n QuicStream(stream_id: Optional[int]=None, connection: Optional[Any]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0)\n \n at: aioquic.tls.Context\n handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.stream\n class QuicStream:\n def __init__(\n self,\n stream_id: Optional[int] = None,\n connection: Optional[Any] = None,\n max_stream_data_local: int = 0,\n max_stream_data_remote: int = 0,\n ) -> None:\n self._connection = connection\n + self.is_blocked = False\n self.max_stream_data_local = max_stream_data_local\n self.max_stream_data_local_sent = max_stream_data_local\n self.max_stream_data_remote = max_stream_data_remote\n self.send_buffer_is_empty = True\n \n self._recv_buffer = bytearray()\n self._recv_buffer_fin: Optional[int] = None\n self._recv_buffer_start = 0 # the offset for the start of the buffer\n self._recv_highest = 0 # the highest offset ever seen\n self._recv_ranges = RangeSet()\n \n self._send_acked = RangeSet()\n self._send_buffer = bytearray()\n self._send_buffer_fin: Optional[int] = None\n self._send_buffer_start = 0 # the offset for the start of the buffer\n self._send_buffer_stop = 0 # the offset for the stop of the buffer\n self._send_highest = 0\n self._send_pending = RangeSet()\n self._send_pending_eof = False\n \n self.__stream_id = stream_id\n \n===========changed ref 1===========\n # module: aioquic.connection\n class QuicConnection:\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n original_connection_id: Optional[bytes] = None,\n session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,\n session_ticket_handler: Optional[tls.SessionTicketHandler] = None,\n ) -> None:\n if configuration.is_client:\n assert (\n original_connection_id is None\n ), \"Cannot set original_connection_id for a client\"\n else:\n assert (\n configuration.certificate is not None\n ), \"SSL certificate is required for a server\"\n assert (\n configuration.private_key is not None\n ), \"SSL private key is required for a server\"\n \n # counters for debugging\n self._stateless_retry_count = 0\n self._version_negotiation_count = 0\n \n # configuration\n self._configuration = configuration\n self._is_client = configuration.is_client\n \n self._ack_delay = K_GRANULARITY\n self._close_at: Optional[float] = None\n self._close_event: Optional[events.ConnectionTerminated] = None\n self._connect_called = False\n self._cryptos: Dict[tls.Epoch, CryptoPair] = {}\n self._crypto_buffers: Dict[tls.Epoch, Buffer] = {}\n self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}\n self._events: Deque[events.Event] = deque()\n self._handshake_complete = False\n self._handshake_confirmed = False\n self._host_cids = [\n QuicConnectionId(\n cid=os.urandom(8),\n sequence_number=0,\n stateless_reset_token=os.urandom(16),\n was_sent=True,\n )\n ]\n self.host_cid = self._host_cids[0].cid\n self._host_cid_seq = 1\n self._local_max_data = MAX_DATA_WINDOW\n self._local\n===========changed ref 2===========\n # module: aioquic.connection\n class QuicConnection:\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n original_connection_id: Optional[bytes] = None,\n session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,\n session_ticket_handler: Optional[tls.SessionTicketHandler] = None,\n ) -> None:\n # offset: 1\n self._host_cid_seq = 1\n self._local_max_data = MAX_DATA_WINDOW\n self._local_max_data_sent = MAX_DATA_WINDOW\n self._local_max_data_used = 0\n self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW\n self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW\n self._local_max_stream_data_uni = MAX_DATA_WINDOW\n self._local_max_streams_bidi = 128\n self._local_max_streams_uni = 128\n self._logger = QuicConnectionAdapter(\n logger, {\"host_cid\": dump_cid(self.host_cid)}\n )\n self._loss = QuicPacketRecovery(send_probe=self._send_probe)\n self._loss_at: Optional[float] = None\n self._network_paths: List[QuicNetworkPath] = []\n self._original_connection_id = original_connection_id\n self._packet_number = 0\n self._parameters_received = False\n self._peer_cid = os.urandom(8)\n self._peer_cid_seq: Optional[int] = None\n self._peer_cid_available: List[QuicConnectionId] = []\n self._peer_token = b\"\"\n self._remote_idle_timeout = 0.0 # seconds\n self._remote_max_data = 0\n self._remote_max_data_used = 0\n self._remote_max_stream_"}}},{"rowIdx":2919,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection._handle_crypto_frame"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1f48726433a6b5d4abc34758228516aaa2432269"},"commit_message":{"kind":"string","value":"[streams] send STREAMS_BLOCKED if stream limit is exceeded"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def _handle_crypto_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n <0> \"\"\"\n <1> Handle a CRYPTO frame.\n <2> \"\"\"\n <3> stream = self._crypto_streams[context.epoch]\n <4> stream.add_frame(pull_crypto_frame(buf))\n <5> data = stream.pull_data()\n <6> if data:\n <7> # pass data to TLS layer\n <8> try:\n <9> self.tls.handle_message(data, self._crypto_buffers)\n<10> self._push_crypto_data()\n<11> except tls.Alert as exc:\n<12> raise QuicConnectionError(\n<13> error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description),\n<14> frame_type=QuicFrameType.CRYPTO,\n<15> reason_phrase=str(exc),\n<16> )\n<17> \n<18> # parse transport parameters\n<19> if (\n<20> not self._parameters_received\n<21> and self.tls.received_extensions is not None\n<22> ):\n<23> for ext_type, ext_data in self.tls.received_extensions:\n<24> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:\n<25> self._parse_transport_parameters(ext_data)\n<26> self._parameters_received = True\n<27> break\n<28> assert (\n<29> self._parameters_received\n<30> ), \"No QUIC transport parameters received\"\n<31> \n<32> # update current epoch\n<33> if not self._handshake_complete and self.tls.state in [\n<34> tls.State.CLIENT_POST_HANDSHAKE,\n<35> tls.State.SERVER_POST_HANDSHAKE,\n<36> ]:\n<37> self._handshake_complete = True\n<38> self._replenish_connection_ids()\n<39> self._events.append(\n<40> events.HandshakeCompleted(\n<41> alpn_protocol=self.tls.alpn_negotiated,\n<42> early_data_accepted=self.tls.early_data_accepted,"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_crypto_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n # offset: 1\n )\n )\n self._logger.info(\n \"ALPN negotiated protocol %s\", self.tls.alpn_negotiated\n )\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic.connection\n QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str)\n \n QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, time: float)\n \n at: aioquic.connection.QuicConnection\n _close_begin(is_initiator: bool, now: float) -> None\n \n _replenish_connection_ids() -> None\n \n _push_crypto_data() -> None\n \n _parse_transport_parameters(data: bytes, from_session_ticket: bool=False) -> None\n \n at: aioquic.connection.QuicConnection.__init__\n self._close_event: Optional[events.ConnectionTerminated] = None\n \n self._crypto_buffers: Dict[tls.Epoch, Buffer] = {}\n \n self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}\n \n self._events: Deque[events.Event] = deque()\n \n self._handshake_complete = False\n \n self._logger = QuicConnectionAdapter(\n logger, {\"host_cid\": dump_cid(self.host_cid)}\n )\n \n self._parameters_received = False\n \n at: aioquic.connection.QuicConnection._handle_connection_close_frame\n error_code, frame_type, reason_phrase = pull_transport_close_frame(buf)\n error_code, reason_phrase = pull_application_close_frame(buf)\n \n error_code, frame_type, reason_phrase = pull_transport_close_frame(buf)\n frame_type = None\n \n error_code, frame_type, reason_phrase = pull_transport_close_frame(buf)\n error_code, reason_phrase = pull_application_close_frame(buf)\n \n at: aioquic.connection.QuicConnection._initialize\n self.tls = tls.Context(is_client=self._is_client, logger=self._logger)\n \n \n===========unchanged ref 1===========\n self._crypto_buffers = {\n tls.Epoch.INITIAL: Buffer(capacity=4096),\n tls.Epoch.HANDSHAKE: Buffer(capacity=4096),\n tls.Epoch.ONE_RTT: Buffer(capacity=4096),\n }\n \n self._crypto_streams = {\n tls.Epoch.INITIAL: QuicStream(),\n tls.Epoch.HANDSHAKE: QuicStream(),\n tls.Epoch.ONE_RTT: QuicStream(),\n }\n \n at: aioquic.connection.QuicConnection.close\n self._close_event = events.ConnectionTerminated(\n error_code=error_code,\n frame_type=frame_type,\n reason_phrase=reason_phrase,\n )\n \n at: aioquic.connection.QuicConnection.handle_timer\n self._close_event = events.ConnectionTerminated(\n error_code=QuicErrorCode.INTERNAL_ERROR,\n frame_type=None,\n reason_phrase=\"Idle timeout\",\n )\n \n at: aioquic.connection.QuicConnection.receive_datagram\n self._close_event = events.ConnectionTerminated(\n error_code=QuicErrorCode.INTERNAL_ERROR,\n frame_type=None,\n reason_phrase=\"Could not find a common protocol version\",\n )\n \n at: aioquic.connection.QuicReceiveContext\n epoch: tls.Epoch\n \n host_cid: bytes\n \n network_path: QuicNetworkPath\n \n time: float\n \n at: aioquic.events\n ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str)\n \n HandshakeCompleted(alpn_protocol: Optional[str], early_data_accepted: bool, session_resumed: bool)\n \n at: aioquic.events.ConnectionTerminated\n error_code: int\n \n frame_type: Optional[int]\n \n reason_phrase: str\n \n \n===========unchanged ref 2===========\n at: aioquic.packet\n QuicErrorCode(x: Union[str, bytes, bytearray], base: int)\n QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n QuicFrameType(x: Union[str, bytes, bytearray], base: int)\n \n pull_crypto_frame(buf: Buffer) -> QuicStreamFrame\n \n at: aioquic.stream.QuicStream\n add_frame(frame: QuicStreamFrame) -> None\n \n pull_data() -> bytes\n \n at: aioquic.tls\n Alert(*args: object)\n \n State()\n \n ExtensionType(x: Union[str, bytes, bytearray], base: int)\n ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n at: aioquic.tls.Alert\n description: AlertDescription\n \n at: aioquic.tls.Context\n handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None\n \n at: aioquic.tls.Context.__init__\n self.received_extensions: Optional[List[Extension]] = None\n \n self.state = State.CLIENT_HANDSHAKE_START\n self.state = State.SERVER_EXPECT_CLIENT_HELLO\n \n at: aioquic.tls.Context._client_handle_encrypted_extensions\n self.received_extensions = encrypted_extensions.other_extensions\n \n at: aioquic.tls.Context._server_handle_hello\n self.received_extensions = peer_hello.other_extensions\n \n at: aioquic.tls.Context._set_state\n self.state = state\n \n at: collections.deque\n append(x: _T) -> None\n \n at: logging.LoggerAdapter\n logger: Logger\n \n extra: Mapping[str, Any]\n \n \n===========unchanged ref 3===========\n info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.connection\n class QuicConnection:\n def _create_stream(self, stream_id: int) -> QuicStream:\n \"\"\"\n Create a QUIC stream in order to send data to the peer.\n \"\"\"\n # determine limits\n if stream_is_unidirectional(stream_id):\n max_stream_data_local = 0\n max_stream_data_remote = self._remote_max_stream_data_uni\n max_streams = self._remote_max_streams_uni\n + streams_blocked = self._streams_blocked_uni\n else:\n max_stream_data_local = self._local_max_stream_data_bidi_local\n max_stream_data_remote = self._remote_max_stream_data_bidi_remote\n max_streams = self._remote_max_streams_bidi\n - \n - # check max streams\n - if stream_id // 4 >= max_streams:\n - raise ValueError(\"Too many streams open\")\n + streams_blocked = self._streams_blocked_bidi\n \n # create stream\n stream = self._streams[stream_id] = QuicStream(\n connection=self,\n stream_id=stream_id,\n max_stream_data_local=max_stream_data_local,\n max_stream_data_remote=max_stream_data_remote,\n )\n + \n + # mark stream as blocked if needed\n + if stream_id // 4 >= max_streams:\n + stream.is_blocked = True\n + streams_blocked.append(stream)\n + self._streams_blocked_pending = True\n + \n return stream\n "}}},{"rowIdx":2920,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection._handle_max_streams_bidi_frame"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1f48726433a6b5d4abc34758228516aaa2432269"},"commit_message":{"kind":"string","value":"[streams] send STREAMS_BLOCKED if stream limit is exceeded"},"ground_truth":{"kind":"string","value":" <9>: self._unblock_streams(is_unidirectional=False)\n"},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def _handle_max_streams_bidi_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n <0> \"\"\"\n <1> Handle a MAX_STREAMS_BIDI frame.\n <2> \n <3> This raises number of bidirectional streams we can initiate to the peer.\n <4> \"\"\"\n <5> max_streams = buf.pull_uint_var()\n <6> if max_streams > self._remote_max_streams_bidi:\n <7> self._logger.debug(\"Remote max_streams_bidi raised to %d\", max_streams)\n <8> self._remote_max_streams_bidi = max_streams\n <9> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic.connection\n QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, time: float)\n \n at: aioquic.connection.QuicConnection\n _get_or_create_stream(frame_type: int, stream_id: int) -> QuicStream\n \n at: aioquic.connection.QuicConnection.__init__\n self._logger = QuicConnectionAdapter(\n logger, {\"host_cid\": dump_cid(self.host_cid)}\n )\n \n at: aioquic.connection.QuicConnection._handle_max_stream_data_frame\n stream_id = buf.pull_uint_var()\n \n max_stream_data = buf.pull_uint_var()\n \n at: aioquic.stream.QuicStream.__init__\n self.max_stream_data_remote = max_stream_data_remote\n \n at: logging.LoggerAdapter\n debug(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_crypto_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n \"\"\"\n Handle a CRYPTO frame.\n \"\"\"\n stream = self._crypto_streams[context.epoch]\n stream.add_frame(pull_crypto_frame(buf))\n data = stream.pull_data()\n if data:\n # pass data to TLS layer\n try:\n self.tls.handle_message(data, self._crypto_buffers)\n self._push_crypto_data()\n except tls.Alert as exc:\n raise QuicConnectionError(\n error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description),\n frame_type=QuicFrameType.CRYPTO,\n reason_phrase=str(exc),\n )\n \n # parse transport parameters\n if (\n not self._parameters_received\n and self.tls.received_extensions is not None\n ):\n for ext_type, ext_data in self.tls.received_extensions:\n if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:\n self._parse_transport_parameters(ext_data)\n self._parameters_received = True\n break\n assert (\n self._parameters_received\n ), \"No QUIC transport parameters received\"\n \n # update current epoch\n if not self._handshake_complete and self.tls.state in [\n tls.State.CLIENT_POST_HANDSHAKE,\n tls.State.SERVER_POST_HANDSHAKE,\n ]:\n self._handshake_complete = True\n self._replenish_connection_ids()\n self._events.append(\n events.HandshakeCompleted(\n alpn_protocol=self.tls.alpn_negotiated,\n early_data_accepted=self.tls.early_data_accepted,\n session_resumed=self.tls.session_resumed,\n )\n )\n + self._unblock_streams(is_unidirectional=False)\n \n===========changed ref 1===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_crypto_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n # offset: 1\n _resumed,\n )\n )\n + self._unblock_streams(is_unidirectional=False)\n + self._unblock_streams(is_unidirectional=True)\n self._logger.info(\n \"ALPN negotiated protocol %s\", self.tls.alpn_negotiated\n )\n \n===========changed ref 2===========\n # module: aioquic.connection\n class QuicConnection:\n def _create_stream(self, stream_id: int) -> QuicStream:\n \"\"\"\n Create a QUIC stream in order to send data to the peer.\n \"\"\"\n # determine limits\n if stream_is_unidirectional(stream_id):\n max_stream_data_local = 0\n max_stream_data_remote = self._remote_max_stream_data_uni\n max_streams = self._remote_max_streams_uni\n + streams_blocked = self._streams_blocked_uni\n else:\n max_stream_data_local = self._local_max_stream_data_bidi_local\n max_stream_data_remote = self._remote_max_stream_data_bidi_remote\n max_streams = self._remote_max_streams_bidi\n - \n - # check max streams\n - if stream_id // 4 >= max_streams:\n - raise ValueError(\"Too many streams open\")\n + streams_blocked = self._streams_blocked_bidi\n \n # create stream\n stream = self._streams[stream_id] = QuicStream(\n connection=self,\n stream_id=stream_id,\n max_stream_data_local=max_stream_data_local,\n max_stream_data_remote=max_stream_data_remote,\n )\n + \n + # mark stream as blocked if needed\n + if stream_id // 4 >= max_streams:\n + stream.is_blocked = True\n + streams_blocked.append(stream)\n + self._streams_blocked_pending = True\n + \n return stream\n \n===========changed ref 3===========\n # module: aioquic.stream\n class QuicStream:\n def __init__(\n self,\n stream_id: Optional[int] = None,\n connection: Optional[Any] = None,\n max_stream_data_local: int = 0,\n max_stream_data_remote: int = 0,\n ) -> None:\n self._connection = connection\n + self.is_blocked = False\n self.max_stream_data_local = max_stream_data_local\n self.max_stream_data_local_sent = max_stream_data_local\n self.max_stream_data_remote = max_stream_data_remote\n self.send_buffer_is_empty = True\n \n self._recv_buffer = bytearray()\n self._recv_buffer_fin: Optional[int] = None\n self._recv_buffer_start = 0 # the offset for the start of the buffer\n self._recv_highest = 0 # the highest offset ever seen\n self._recv_ranges = RangeSet()\n \n self._send_acked = RangeSet()\n self._send_buffer = bytearray()\n self._send_buffer_fin: Optional[int] = None\n self._send_buffer_start = 0 # the offset for the start of the buffer\n self._send_buffer_stop = 0 # the offset for the stop of the buffer\n self._send_highest = 0\n self._send_pending = RangeSet()\n self._send_pending_eof = False\n \n self.__stream_id = stream_id\n "}}},{"rowIdx":2921,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection._handle_max_streams_uni_frame"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1f48726433a6b5d4abc34758228516aaa2432269"},"commit_message":{"kind":"string","value":"[streams] send STREAMS_BLOCKED if stream limit is exceeded"},"ground_truth":{"kind":"string","value":" <9>: self._unblock_streams(is_unidirectional=True)\n"},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def _handle_max_streams_uni_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n <0> \"\"\"\n <1> Handle a MAX_STREAMS_UNI frame.\n <2> \n <3> This raises number of unidirectional streams we can initiate to the peer.\n <4> \"\"\"\n <5> max_streams = buf.pull_uint_var()\n <6> if max_streams > self._remote_max_streams_uni:\n <7> self._logger.debug(\"Remote max_streams_uni raised to %d\", max_streams)\n <8> self._remote_max_streams_uni = max_streams\n <9> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer.Buffer\n pull_uint_var() -> int\n \n at: aioquic.connection.QuicConnection\n _unblock_streams(is_unidirectional: bool) -> None\n \n at: aioquic.connection.QuicConnection.__init__\n self._logger = QuicConnectionAdapter(\n logger, {\"host_cid\": dump_cid(self.host_cid)}\n )\n \n self._remote_max_streams_bidi = 0\n \n at: logging.LoggerAdapter\n debug(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_max_streams_bidi_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n \"\"\"\n Handle a MAX_STREAMS_BIDI frame.\n \n This raises number of bidirectional streams we can initiate to the peer.\n \"\"\"\n max_streams = buf.pull_uint_var()\n if max_streams > self._remote_max_streams_bidi:\n self._logger.debug(\"Remote max_streams_bidi raised to %d\", max_streams)\n self._remote_max_streams_bidi = max_streams\n + self._unblock_streams(is_unidirectional=False)\n \n===========changed ref 1===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_crypto_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n \"\"\"\n Handle a CRYPTO frame.\n \"\"\"\n stream = self._crypto_streams[context.epoch]\n stream.add_frame(pull_crypto_frame(buf))\n data = stream.pull_data()\n if data:\n # pass data to TLS layer\n try:\n self.tls.handle_message(data, self._crypto_buffers)\n self._push_crypto_data()\n except tls.Alert as exc:\n raise QuicConnectionError(\n error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description),\n frame_type=QuicFrameType.CRYPTO,\n reason_phrase=str(exc),\n )\n \n # parse transport parameters\n if (\n not self._parameters_received\n and self.tls.received_extensions is not None\n ):\n for ext_type, ext_data in self.tls.received_extensions:\n if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:\n self._parse_transport_parameters(ext_data)\n self._parameters_received = True\n break\n assert (\n self._parameters_received\n ), \"No QUIC transport parameters received\"\n \n # update current epoch\n if not self._handshake_complete and self.tls.state in [\n tls.State.CLIENT_POST_HANDSHAKE,\n tls.State.SERVER_POST_HANDSHAKE,\n ]:\n self._handshake_complete = True\n self._replenish_connection_ids()\n self._events.append(\n events.HandshakeCompleted(\n alpn_protocol=self.tls.alpn_negotiated,\n early_data_accepted=self.tls.early_data_accepted,\n session_resumed=self.tls.session_resumed,\n )\n )\n + self._unblock_streams(is_unidirectional=False)\n \n===========changed ref 2===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_crypto_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n # offset: 1\n _resumed,\n )\n )\n + self._unblock_streams(is_unidirectional=False)\n + self._unblock_streams(is_unidirectional=True)\n self._logger.info(\n \"ALPN negotiated protocol %s\", self.tls.alpn_negotiated\n )\n \n===========changed ref 3===========\n # module: aioquic.connection\n class QuicConnection:\n def _create_stream(self, stream_id: int) -> QuicStream:\n \"\"\"\n Create a QUIC stream in order to send data to the peer.\n \"\"\"\n # determine limits\n if stream_is_unidirectional(stream_id):\n max_stream_data_local = 0\n max_stream_data_remote = self._remote_max_stream_data_uni\n max_streams = self._remote_max_streams_uni\n + streams_blocked = self._streams_blocked_uni\n else:\n max_stream_data_local = self._local_max_stream_data_bidi_local\n max_stream_data_remote = self._remote_max_stream_data_bidi_remote\n max_streams = self._remote_max_streams_bidi\n - \n - # check max streams\n - if stream_id // 4 >= max_streams:\n - raise ValueError(\"Too many streams open\")\n + streams_blocked = self._streams_blocked_bidi\n \n # create stream\n stream = self._streams[stream_id] = QuicStream(\n connection=self,\n stream_id=stream_id,\n max_stream_data_local=max_stream_data_local,\n max_stream_data_remote=max_stream_data_remote,\n )\n + \n + # mark stream as blocked if needed\n + if stream_id // 4 >= max_streams:\n + stream.is_blocked = True\n + streams_blocked.append(stream)\n + self._streams_blocked_pending = True\n + \n return stream\n \n===========changed ref 4===========\n # module: aioquic.stream\n class QuicStream:\n def __init__(\n self,\n stream_id: Optional[int] = None,\n connection: Optional[Any] = None,\n max_stream_data_local: int = 0,\n max_stream_data_remote: int = 0,\n ) -> None:\n self._connection = connection\n + self.is_blocked = False\n self.max_stream_data_local = max_stream_data_local\n self.max_stream_data_local_sent = max_stream_data_local\n self.max_stream_data_remote = max_stream_data_remote\n self.send_buffer_is_empty = True\n \n self._recv_buffer = bytearray()\n self._recv_buffer_fin: Optional[int] = None\n self._recv_buffer_start = 0 # the offset for the start of the buffer\n self._recv_highest = 0 # the highest offset ever seen\n self._recv_ranges = RangeSet()\n \n self._send_acked = RangeSet()\n self._send_buffer = bytearray()\n self._send_buffer_fin: Optional[int] = None\n self._send_buffer_start = 0 # the offset for the start of the buffer\n self._send_buffer_stop = 0 # the offset for the stop of the buffer\n self._send_highest = 0\n self._send_pending = RangeSet()\n self._send_pending_eof = False\n \n self.__stream_id = stream_id\n "}}},{"rowIdx":2922,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection._write_application"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1f48726433a6b5d4abc34758228516aaa2432269"},"commit_message":{"kind":"string","value":"[streams] send STREAMS_BLOCKED if stream limit is exceeded"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def _write_application(\n self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float\n ) -> None:\n <0> crypto_stream: Optional[QuicStream] = None\n <1> if self._cryptos[tls.Epoch.ONE_RTT].send.is_valid():\n <2> crypto = self._cryptos[tls.Epoch.ONE_RTT]\n <3> crypto_stream = self._crypto_streams[tls.Epoch.ONE_RTT]\n <4> packet_type = PACKET_TYPE_ONE_RTT\n <5> elif self._cryptos[tls.Epoch.ZERO_RTT].send.is_valid():\n <6> crypto = self._cryptos[tls.Epoch.ZERO_RTT]\n <7> packet_type = PACKET_TYPE_ZERO_RTT\n <8> else:\n <9> return\n<10> space = self._spaces[tls.Epoch.ONE_RTT]\n<11> \n<12> buf = builder.buffer\n<13> \n<14> while True:\n<15> # write header\n<16> builder.start_packet(packet_type, crypto, is_probe=self._probe_pending)\n<17> \n<18> if self._handshake_complete:\n<19> # ACK\n<20> if space.ack_at is not None and space.ack_at <= now:\n<21> builder.start_frame(\n<22> QuicFrameType.ACK,\n<23> self._on_ack_delivery,\n<24> (space, space.largest_received_packet),\n<25> )\n<26> push_ack_frame(buf, space.ack_queue, 0)\n<27> space.ack_at = None\n<28> \n<29> # PATH CHALLENGE\n<30> if (\n<31> not network_path.is_validated\n<32> and network_path.local_challenge is None\n<33> ):\n<34> self._logger.info(\n<35> \"Network path %s sending challenge\", network_path.addr\n<36> )\n<37> network_path.local_challenge = os.urandom(8)\n<38> builder.start_frame(QuicFrameType.PATH_CHALLENG"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.connection\n class QuicConnection:\n def _write_application(\n self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float\n ) -> None:\n # offset: 1\n buf.push_bytes(network_path.local_challenge)\n \n # PATH RESPONSE\n if network_path.remote_challenge is not None:\n builder.start_frame(QuicFrameType.PATH_RESPONSE)\n buf.push_bytes(network_path.remote_challenge)\n network_path.remote_challenge = None\n \n # NEW_CONNECTION_ID\n for connection_id in self._host_cids:\n if not connection_id.was_sent:\n builder.start_frame(\n QuicFrameType.NEW_CONNECTION_ID,\n self._on_new_connection_id_delivery,\n (connection_id,),\n )\n push_new_connection_id_frame(\n buf,\n connection_id.sequence_number,\n connection_id.cid,\n connection_id.stateless_reset_token,\n )\n connection_id.was_sent = True\n self._events.append(\n events.ConnectionIdIssued(connection_id=connection_id.cid)\n )\n \n # RETIRE_CONNECTION_ID\n while self._retire_connection_ids:\n sequence_number = self._retire_connection_ids.pop(0)\n builder.start_frame(\n QuicFrameType.RETIRE_CONNECTION_ID,\n self._on_retire_connection_id_delivery,\n (sequence_number,),\n )\n buf.push_uint_var(sequence_number)\n \n # connection-level limits\n self._write_connection_limits(builder=builder, space=space)\n \n # stream-level limits\n for stream in self._streams.values():\n self._write_stream_limits(builder=builder, space=space, stream=stream)\n \n # PING (user-request)\n if self._ping_pending:\n self._logger.info(\"Sending PING\n===========below chunk 1===========\n # module: aioquic.connection\n class QuicConnection:\n def _write_application(\n self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float\n ) -> None:\n # offset: 2\n \n # PING (user-request)\n if self._ping_pending:\n self._logger.info(\"Sending PING in packet %d\", builder.packet_number)\n builder.start_frame(\n QuicFrameType.PING,\n self._on_ping_delivery,\n (tuple(self._ping_pending),),\n )\n self._ping_pending.clear()\n \n # PING (probe)\n if self._probe_pending:\n self._logger.info(\"Sending probe\")\n builder.start_frame(QuicFrameType.PING)\n self._probe_pending = False\n \n # CRYPTO\n if crypto_stream is not None and not crypto_stream.send_buffer_is_empty:\n write_crypto_frame(builder=builder, space=space, stream=crypto_stream)\n \n for stream in self._streams.values():\n # STREAM\n if not stream.send_buffer_is_empty:\n self._remote_max_data_used += write_stream_frame(\n builder=builder,\n space=space,\n stream=stream,\n max_offset=min(\n stream._send_highest\n + self._remote_max_data\n - self._remote_max_data_used,\n stream.max_stream_data_remote,\n ),\n )\n \n if not builder.end_packet():\n break\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer.Buffer\n push_bytes(value: bytes) -> None\n \n push_uint_var(value: int) -> None\n \n at: aioquic.configuration.QuicConfiguration\n secrets_log_file: TextIO = None\n \n at: aioquic.connection\n SECRETS_LABELS = [\n [\n None,\n \"QUIC_CLIENT_EARLY_TRAFFIC_SECRET\",\n \"QUIC_CLIENT_HANDSHAKE_TRAFFIC_SECRET\",\n \"QUIC_CLIENT_TRAFFIC_SECRET_0\",\n ],\n [\n None,\n None,\n \"QUIC_SERVER_HANDSHAKE_TRAFFIC_SECRET\",\n \"QUIC_SERVER_TRAFFIC_SECRET_0\",\n ],\n ]\n \n QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None)\n \n at: aioquic.connection.QuicConnection\n _on_ack_delivery(delivery: QuicDeliveryState, space: QuicPacketSpace, highest_acked: int) -> None\n \n _on_new_connection_id_delivery(delivery: QuicDeliveryState, connection_id: QuicConnectionId) -> None\n \n _on_retire_connection_id_delivery(delivery: QuicDeliveryState, sequence_number: int) -> None\n \n _write_connection_limits(builder: QuicPacketBuilder, space: QuicPacketSpace) -> None\n \n at: aioquic.connection.QuicConnection.__init__\n self._configuration = configuration\n \n self._is_client = configuration.is_client\n \n self._cryptos: Dict[tls.Epoch, CryptoPair] = {}\n \n self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}\n \n self._events: Deque[events.Event] = deque()\n \n self._handshake_complete = False\n \n \n===========unchanged ref 1===========\n self._host_cids = [\n QuicConnectionId(\n cid=os.urandom(8),\n sequence_number=0,\n stateless_reset_token=os.urandom(16),\n was_sent=True,\n )\n ]\n \n self._logger = QuicConnectionAdapter(\n logger, {\"host_cid\": dump_cid(self.host_cid)}\n )\n \n self._remote_max_streams_bidi = 0\n \n self._remote_max_streams_uni = 0\n \n self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}\n \n self._streams_blocked_bidi: List[QuicStream] = []\n \n self._streams_blocked_uni: List[QuicStream] = []\n \n self._probe_pending = False\n \n self._retire_connection_ids: List[int] = []\n \n self._streams_blocked_pending = False\n \n at: aioquic.connection.QuicConnection._create_stream\n self._streams_blocked_pending = True\n \n at: aioquic.connection.QuicConnection._handle_crypto_frame\n self._handshake_complete = True\n \n at: aioquic.connection.QuicConnection._handle_max_streams_bidi_frame\n self._remote_max_streams_bidi = max_streams\n \n at: aioquic.connection.QuicConnection._handle_max_streams_uni_frame\n self._remote_max_streams_uni = max_streams\n \n at: aioquic.connection.QuicConnection._initialize\n self.tls = tls.Context(is_client=self._is_client, logger=self._logger)\n \n self._cryptos = {\n tls.Epoch.INITIAL: CryptoPair(),\n tls.Epoch.ZERO_RTT: CryptoPair(),\n tls.Epoch.HANDSHAKE: CryptoPair(),\n tls.Epoch.ONE_RTT: CryptoPair(),\n }\n \n "}}},{"rowIdx":2923,"cells":{"path":{"kind":"string","value":"aioquic.h3.connection/H3Connection.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"fb53b77f38b7a1448b11f94d1bb0a37fae3b1e08"},"commit_message":{"kind":"string","value":"[http3] don't buffer data, pass it to the QUIC layer"},"ground_truth":{"kind":"string","value":" <3>: self._handshake_completed = False\n <8>: self._pending: List[Tuple[int, bytes, bool]] = []\n"},"main_code":{"kind":"string","value":" # module: aioquic.h3.connection\n class H3Connection:\n def __init__(self, quic: QuicConnection):\n <0> self._max_table_capacity = 0x100\n <1> self._blocked_streams = 0x10\n <2> \n <3> self._handshake_completed = False\n <4> self._is_client = quic.configuration.is_client\n <5> self._quic = quic\n <6> self._decoder = Decoder(self._max_table_capacity, self._blocked_streams)\n <7> self._encoder = Encoder()\n <8> self._pending: List[Tuple[int, bytes, bool]] = []\n <9> self._stream_buffers: Dict[int, bytes] = {}\n<10> self._stream_types: Dict[int, int] = {}\n<11> \n<12> self._local_control_stream_id: Optional[int] = None\n<13> self._local_decoder_stream_id: Optional[int] = None\n<14> self._local_encoder_stream_id: Optional[int] = None\n<15> \n<16> self._peer_control_stream_id: Optional[int] = None\n<17> self._peer_decoder_stream_id: Optional[int] = None\n<18> self._peer_encoder_stream_id: Optional[int] = None\n<19> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n certificate: Any = None\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n private_key: Any = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[tls.SessionTicket] = None\n \n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_19,\n QuicProtocolVersion.DRAFT_20,\n ]\n )\n \n at: aioquic.connection\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.h3.connection.H3Connection._receive_stream_data\n self._peer_control_stream_id = stream_id\n \n self._peer_decoder_stream_id = stream_id\n \n self._peer_encoder_stream_id = stream_id\n \n at: aioquic.h3.connection.H3Connection._update\n self._local_control_stream_id = self._create_uni_stream(\n StreamType.CONTROL\n )\n \n self._local_encoder_stream_id = self._create_uni_stream(\n StreamType.QPACK_ENCODER\n )\n \n self._local_decoder_stream_id = self._create_uni_stream(\n StreamType.QPACK_DECODER\n )\n \n at: aioquic.h3.events\n Event()\n \n at: typing\n List = _alias(list, 1, inst=False, name='List')\n \n Dict = _alias(dict, 2, inst=False, name='Dict')\n \n "}}},{"rowIdx":2924,"cells":{"path":{"kind":"string","value":"aioquic.h3.connection/H3Connection.send_data"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"fb53b77f38b7a1448b11f94d1bb0a37fae3b1e08"},"commit_message":{"kind":"string","value":"[http3] don't buffer data, pass it to the QUIC layer"},"ground_truth":{"kind":"string","value":" <7>: self._quic.send_stream_data(\n self._send_stream_data(\n"},"main_code":{"kind":"string","value":" # module: aioquic.h3.connection\n class H3Connection:\n def send_data(self, stream_id: int, data: bytes, end_stream: bool) -> None:\n <0> \"\"\"\n <1> Send data on the given stream.\n <2> \n <3> To retrieve datagram which need to be sent over the network call the QUIC\n <4> connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send`\n <5> method.\n <6> \"\"\"\n <7> self._send_stream_data(\n <8> stream_id, encode_frame(FrameType.DATA, data), end_stream\n <9> )\n<10> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.connection.QuicConnection\n send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None\n \n at: aioquic.h3.connection\n FrameType(x: Union[str, bytes, bytearray], base: int)\n FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n encode_frame(frame_type: int, frame_data: bytes) -> bytes\n \n at: aioquic.h3.connection.H3Connection.__init__\n self._quic = quic\n \n at: aioquic.h3.events\n Headers = List[Tuple[bytes, bytes]]\n \n \n===========changed ref 0===========\n # module: aioquic.h3.connection\n class H3Connection:\n def __init__(self, quic: QuicConnection):\n self._max_table_capacity = 0x100\n self._blocked_streams = 0x10\n \n - self._handshake_completed = False\n self._is_client = quic.configuration.is_client\n self._quic = quic\n self._decoder = Decoder(self._max_table_capacity, self._blocked_streams)\n self._encoder = Encoder()\n - self._pending: List[Tuple[int, bytes, bool]] = []\n self._stream_buffers: Dict[int, bytes] = {}\n self._stream_types: Dict[int, int] = {}\n \n self._local_control_stream_id: Optional[int] = None\n self._local_decoder_stream_id: Optional[int] = None\n self._local_encoder_stream_id: Optional[int] = None\n \n self._peer_control_stream_id: Optional[int] = None\n self._peer_decoder_stream_id: Optional[int] = None\n self._peer_encoder_stream_id: Optional[int] = None\n "}}},{"rowIdx":2925,"cells":{"path":{"kind":"string","value":"aioquic.h3.connection/H3Connection.send_headers"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"fb53b77f38b7a1448b11f94d1bb0a37fae3b1e08"},"commit_message":{"kind":"string","value":"[http3] don't buffer data, pass it to the QUIC layer"},"ground_truth":{"kind":"string","value":" <8>: self._quic.send_stream_data(\n self._send_stream_data(\n"},"main_code":{"kind":"string","value":" # module: aioquic.h3.connection\n class H3Connection:\n def send_headers(self, stream_id: int, headers: Headers) -> None:\n <0> \"\"\"\n <1> Send headers on the given stream.\n <2> \n <3> To retrieve datagram which need to be sent over the network call the QUIC\n <4> connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send`\n <5> method.\n <6> \"\"\"\n <7> control, header = self._encoder.encode(stream_id, 0, headers)\n <8> self._send_stream_data(\n <9> stream_id, encode_frame(FrameType.HEADERS, header), False\n<10> )\n<11> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.connection.QuicConnection\n send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None\n \n at: aioquic.h3.connection\n FrameType(x: Union[str, bytes, bytearray], base: int)\n FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n encode_frame(frame_type: int, frame_data: bytes) -> bytes\n \n at: aioquic.h3.connection.H3Connection.__init__\n self._quic = quic\n \n self._encoder = Encoder()\n \n \n===========changed ref 0===========\n # module: aioquic.h3.connection\n class H3Connection:\n def send_data(self, stream_id: int, data: bytes, end_stream: bool) -> None:\n \"\"\"\n Send data on the given stream.\n \n To retrieve datagram which need to be sent over the network call the QUIC\n connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send`\n method.\n \"\"\"\n + self._quic.send_stream_data(\n - self._send_stream_data(\n stream_id, encode_frame(FrameType.DATA, data), end_stream\n )\n \n===========changed ref 1===========\n # module: aioquic.h3.connection\n class H3Connection:\n def __init__(self, quic: QuicConnection):\n self._max_table_capacity = 0x100\n self._blocked_streams = 0x10\n \n - self._handshake_completed = False\n self._is_client = quic.configuration.is_client\n self._quic = quic\n self._decoder = Decoder(self._max_table_capacity, self._blocked_streams)\n self._encoder = Encoder()\n - self._pending: List[Tuple[int, bytes, bool]] = []\n self._stream_buffers: Dict[int, bytes] = {}\n self._stream_types: Dict[int, int] = {}\n \n self._local_control_stream_id: Optional[int] = None\n self._local_decoder_stream_id: Optional[int] = None\n self._local_encoder_stream_id: Optional[int] = None\n \n self._peer_control_stream_id: Optional[int] = None\n self._peer_decoder_stream_id: Optional[int] = None\n self._peer_encoder_stream_id: Optional[int] = None\n "}}},{"rowIdx":2926,"cells":{"path":{"kind":"string","value":"aioquic.h3.connection/H3Connection._update"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"fb53b77f38b7a1448b11f94d1bb0a37fae3b1e08"},"commit_message":{"kind":"string","value":"[http3] don't buffer data, pass it to the QUIC layer"},"ground_truth":{"kind":"string","value":" <6>: self._handshake_completed = True\n <7>: \n<32>: \n<33>: # send pending data\n<34>: for args in self._pending:\n<35>: self._quic.send_stream_data(*args)\n<36>: self._pending.clear()\n"},"main_code":{"kind":"string","value":" # module: aioquic.h3.connection\n class H3Connection:\n def _update(self) -> List[Event]:\n <0> http_events: List[Event] = []\n <1> \n <2> # process QUIC events\n <3> event = self._quic.next_event()\n <4> while event is not None:\n <5> if isinstance(event, aioquic.events.HandshakeCompleted):\n <6> self._handshake_completed = True\n <7> \n <8> # send our settings\n <9> self._local_control_stream_id = self._create_uni_stream(\n<10> StreamType.CONTROL\n<11> )\n<12> self._quic.send_stream_data(\n<13> self._local_control_stream_id,\n<14> encode_frame(\n<15> FrameType.SETTINGS,\n<16> encode_settings(\n<17> {\n<18> Setting.QPACK_MAX_TABLE_CAPACITY: self._max_table_capacity,\n<19> Setting.QPACK_BLOCKED_STREAMS: self._blocked_streams,\n<20> }\n<21> ),\n<22> ),\n<23> )\n<24> \n<25> # create encoder and decoder streams\n<26> self._local_encoder_stream_id = self._create_uni_stream(\n<27> StreamType.QPACK_ENCODER\n<28> )\n<29> self._local_decoder_stream_id = self._create_uni_stream(\n<30> StreamType.QPACK_DECODER\n<31> )\n<32> \n<33> # send pending data\n<34> for args in self._pending:\n<35> self._quic.send_stream_data(*args)\n<36> self._pending.clear()\n<37> elif isinstance(event, aioquic.events.StreamDataReceived):\n<38> http_events.extend(\n<39> self._receive_stream_data(\n<40> event.stream_id, event.data, event.end_stream\n<41> )\n<42> )\n<43> \n<44> event = self._quic.next_event()\n<45> \n<46> return http_events\n<47> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.connection.QuicConnection\n next_event() -> Optional[events.Event]\n \n send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None\n \n at: aioquic.events\n StreamDataReceived(data: bytes, end_stream: bool, stream_id: int)\n \n at: aioquic.h3.connection\n FrameType(x: Union[str, bytes, bytearray], base: int)\n FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n Setting(x: Union[str, bytes, bytearray], base: int)\n Setting(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n StreamType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n StreamType(x: Union[str, bytes, bytearray], base: int)\n \n encode_frame(frame_type: int, frame_data: bytes) -> bytes\n \n encode_settings(settings: Dict[int, int]) -> bytes\n \n at: aioquic.h3.connection.H3Connection\n _create_uni_stream(stream_type: int) -> int\n _create_uni_stream(self, stream_type: int) -> int\n \n _receive_stream_data(stream_id: int, data: bytes, stream_ended: bool) -> List[Event]\n \n at: aioquic.h3.connection.H3Connection.__init__\n self._max_table_capacity = 0x100\n \n self._blocked_streams = 0x10\n \n self._quic = quic\n \n self._local_control_stream_id: Optional[int] = None\n \n self._local_decoder_stream_id: Optional[int] = None\n \n self._local_encoder_stream_id: Optional[int] = None\n \n at: aioquic.h3.connection.H3Connection._update\n http_events: List[Event] = []\n \n \n===========changed ref 0===========\n # module: aioquic.h3.connection\n class H3Connection:\n - def _send_stream_data(self, stream_id: int, data: bytes, end_stream: bool) -> None:\n - if self._handshake_completed:\n - self._quic.send_stream_data(stream_id, data, end_stream)\n - else:\n - self._pending.append((stream_id, data, end_stream))\n - \n===========changed ref 1===========\n # module: aioquic.h3.connection\n class H3Connection:\n def send_data(self, stream_id: int, data: bytes, end_stream: bool) -> None:\n \"\"\"\n Send data on the given stream.\n \n To retrieve datagram which need to be sent over the network call the QUIC\n connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send`\n method.\n \"\"\"\n + self._quic.send_stream_data(\n - self._send_stream_data(\n stream_id, encode_frame(FrameType.DATA, data), end_stream\n )\n \n===========changed ref 2===========\n # module: aioquic.h3.connection\n class H3Connection:\n def send_headers(self, stream_id: int, headers: Headers) -> None:\n \"\"\"\n Send headers on the given stream.\n \n To retrieve datagram which need to be sent over the network call the QUIC\n connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send`\n method.\n \"\"\"\n control, header = self._encoder.encode(stream_id, 0, headers)\n + self._quic.send_stream_data(\n - self._send_stream_data(\n stream_id, encode_frame(FrameType.HEADERS, header), False\n )\n \n===========changed ref 3===========\n # module: aioquic.h3.connection\n class H3Connection:\n def __init__(self, quic: QuicConnection):\n self._max_table_capacity = 0x100\n self._blocked_streams = 0x10\n \n - self._handshake_completed = False\n self._is_client = quic.configuration.is_client\n self._quic = quic\n self._decoder = Decoder(self._max_table_capacity, self._blocked_streams)\n self._encoder = Encoder()\n - self._pending: List[Tuple[int, bytes, bool]] = []\n self._stream_buffers: Dict[int, bytes] = {}\n self._stream_types: Dict[int, int] = {}\n \n self._local_control_stream_id: Optional[int] = None\n self._local_decoder_stream_id: Optional[int] = None\n self._local_encoder_stream_id: Optional[int] = None\n \n self._peer_control_stream_id: Optional[int] = None\n self._peer_decoder_stream_id: Optional[int] = None\n self._peer_encoder_stream_id: Optional[int] = None\n "}}},{"rowIdx":2927,"cells":{"path":{"kind":"string","value":"tests.test_h3/H3ConnectionTest.test_connect"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"07df8b382bd5ea1f34f109a06374b52852cf4b88"},"commit_message":{"kind":"string","value":"[tests] rework HTTP/3 tests"},"ground_truth":{"kind":"string","value":"<19>: self.assertEqual(h3_client._update(), [])\n<22>: events = h3_transfer(quic_client, h3_server)\n transfer(quic_client, quic_server)\n<23>: events = h3_server._update()\n"},"main_code":{"kind":"string","value":" # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_connect(self):\n <0> with client_and_server(\n <1> client_options={\"alpn_protocols\": [\"h3-20\"]},\n <2> server_options={\"alpn_protocols\": [\"h3-20\"]},\n <3> ) as (quic_client, quic_server):\n <4> h3_client = H3Connection(quic_client)\n <5> h3_server = H3Connection(quic_server)\n <6> \n <7> # send request\n <8> stream_id = quic_client.get_next_available_stream_id()\n <9> h3_client.send_headers(\n<10> stream_id=stream_id,\n<11> headers=[\n<12> (b\":method\", b\"GET\"),\n<13> (b\":scheme\", b\"https\"),\n<14> (b\":authority\", b\"localhost\"),\n<15> (b\":path\", b\"/\"),\n<16> ],\n<17> )\n<18> h3_client.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n<19> self.assertEqual(h3_client._update(), [])\n<20> \n<21> # receive request\n<22> transfer(quic_client, quic_server)\n<23> events = h3_server._update()\n<24> self.assertEqual(len(events), 2)\n<25> \n<26> self.assertTrue(isinstance(events[0], RequestReceived))\n<27> self.assertEqual(\n<28> events[0].headers,\n<29> [\n<30> (b\":method\", b\"GET\"),\n<31> (b\":scheme\", b\"https\"),\n<32> (b\":authority\", b\"localhost\"),\n<33> (b\":path\", b\"/\"),\n<34> ],\n<35> )\n<36> self.assertEqual(events[0].stream_id, stream_id)\n<37> self.assertEqual(events[0].stream_ended, False)\n<38> \n<39> self.assertTrue(isinstance(events[1], DataReceived))\n<40> self.assertEqual(events"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_connect(self):\n # offset: 1\n self.assertEqual(events[1].stream_id, stream_id)\n self.assertEqual(events[1].stream_ended, True)\n \n # send response\n h3_server.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":status\", b\"200\"),\n (b\"content-type\", b\"text/html; charset=utf-8\"),\n ],\n )\n h3_server.send_data(\n stream_id=stream_id,\n data=b\"hello\",\n end_stream=True,\n )\n self.assertEqual(h3_server._update(), [])\n \n # receive response\n transfer(quic_server, quic_client)\n events = h3_client._update()\n self.assertEqual(len(events), 2)\n \n self.assertTrue(isinstance(events[0], ResponseReceived))\n self.assertEqual(\n events[0].headers,\n [(b\":status\", b\"200\"), (b\"content-type\", b\"text/html; charset=utf-8\")],\n )\n self.assertEqual(events[0].stream_id, stream_id)\n self.assertEqual(events[0].stream_ended, False)\n \n self.assertTrue(isinstance(events[1], DataReceived))\n self.assertEqual(events[1].data, b\"hello\")\n self.assertEqual(events[1].stream_id, stream_id)\n self.assertEqual(events[1].stream_ended, True)\n \n \n===========unchanged ref 0===========\n at: aioquic.h3.connection\n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection\n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: Headers) -> None\n \n _update() -> List[Event]\n \n at: aioquic.h3.connection.H3Connection.__init__\n self._quic = quic\n \n at: aioquic.h3.events\n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n RequestReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: tests.test_connection\n client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={})\n \n transfer(sender, receiver)\n \n at: tests.test_h3\n h3_transfer(quic_sender, h3_receiver)\n \n at: unittest.case\n TestCase(methodName: str=...)\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n _testMethodDoc: str\n \n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertTrue(expr: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_h3\n + def h3_transfer(quic_sender, h3_receiver):\n + transfer(quic_sender, h3_receiver._quic)\n + return h3_receiver._update()\n + "}}},{"rowIdx":2928,"cells":{"path":{"kind":"string","value":"tests.test_h3/H3ConnectionTest.test_uni_stream_type"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"07df8b382bd5ea1f34f109a06374b52852cf4b88"},"commit_message":{"kind":"string","value":"[tests] rework HTTP/3 tests"},"ground_truth":{"kind":"string","value":"<10>: transfer(quic_client, quic_server)\n<11>: self.assertEqual(h3_server._update(), [])\n<12>: self.assertEqual(h3_transfer(quic_client, h3_server), [])\n<20>: transfer(quic_client, quic_server)\n<21>: self.assertEqual(h3_server._update(), [])\n<22>: self.assertEqual(h3_transfer(quic_client, h3_server), [])\n<26>: transfer(quic_client, quic_server)\n<27>: self.assertEqual(h3_server._update(), [])\n<28>: self.assertEqual(h3_transfer(quic_client, h3_server), [])\n"},"main_code":{"kind":"string","value":" # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_uni_stream_type(self):\n <0> with client_and_server(\n <1> client_options={\"alpn_protocols\": [\"h3-20\"]},\n <2> server_options={\"alpn_protocols\": [\"h3-20\"]},\n <3> ) as (quic_client, quic_server):\n <4> h3_server = H3Connection(quic_server)\n <5> \n <6> # unknown stream type 9\n <7> stream_id = quic_client.get_next_available_stream_id(is_unidirectional=True)\n <8> self.assertEqual(stream_id, 2)\n <9> quic_client.send_stream_data(stream_id, b\"\\x09\")\n<10> transfer(quic_client, quic_server)\n<11> self.assertEqual(h3_server._update(), [])\n<12> self.assertEqual(h3_server._stream_buffers, {2: b\"\"})\n<13> self.assertEqual(h3_server._stream_types, {2: 9})\n<14> \n<15> # unknown stream type 64, one byte at a time\n<16> stream_id = quic_client.get_next_available_stream_id(is_unidirectional=True)\n<17> self.assertEqual(stream_id, 6)\n<18> \n<19> quic_client.send_stream_data(stream_id, b\"\\x40\")\n<20> transfer(quic_client, quic_server)\n<21> self.assertEqual(h3_server._update(), [])\n<22> self.assertEqual(h3_server._stream_buffers, {2: b\"\", 6: b\"\\x40\"})\n<23> self.assertEqual(h3_server._stream_types, {2: 9})\n<24> \n<25> quic_client.send_stream_data(stream_id, b\"\\x40\")\n<26> transfer(quic_client, quic_server)\n<27> self.assertEqual(h3_server._update(), [])\n<28> self.assertEqual(h3_server._stream"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_uni_stream_type(self):\n # offset: 1\n self.assertEqual(h3_server._stream_types, {2: 9, 6: 64})\n \n \n===========unchanged ref 0===========\n at: aioquic.h3.connection\n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection.__init__\n self._stream_buffers: Dict[int, bytes] = {}\n \n self._stream_types: Dict[int, int] = {}\n \n at: tests.test_connection\n client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={})\n \n at: tests.test_h3\n h3_transfer(quic_sender, h3_receiver)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_h3\n + def h3_transfer(quic_sender, h3_receiver):\n + transfer(quic_sender, h3_receiver._quic)\n + return h3_receiver._update()\n + \n===========changed ref 1===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_connect(self):\n with client_and_server(\n client_options={\"alpn_protocols\": [\"h3-20\"]},\n server_options={\"alpn_protocols\": [\"h3-20\"]},\n ) as (quic_client, quic_server):\n h3_client = H3Connection(quic_client)\n h3_server = H3Connection(quic_server)\n \n # send request\n stream_id = quic_client.get_next_available_stream_id()\n h3_client.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":method\", b\"GET\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/\"),\n ],\n )\n h3_client.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n - self.assertEqual(h3_client._update(), [])\n \n # receive request\n + events = h3_transfer(quic_client, h3_server)\n - transfer(quic_client, quic_server)\n - events = h3_server._update()\n self.assertEqual(len(events), 2)\n \n self.assertTrue(isinstance(events[0], RequestReceived))\n self.assertEqual(\n events[0].headers,\n [\n (b\":method\", b\"GET\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/\"),\n ],\n )\n self.assertEqual(events[0].stream_id, stream_id)\n self.assertEqual(events[0].stream_ended, False)\n \n self.assertTrue(isinstance(events[1], DataReceived))\n self.assertEqual(events[1].data, b\"\")\n self.assertEqual(events[1\n===========changed ref 2===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_connect(self):\n # offset: 1\n ], DataReceived))\n self.assertEqual(events[1].data, b\"\")\n self.assertEqual(events[1].stream_id, stream_id)\n self.assertEqual(events[1].stream_ended, True)\n \n # send response\n h3_server.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":status\", b\"200\"),\n (b\"content-type\", b\"text/html; charset=utf-8\"),\n ],\n )\n h3_server.send_data(\n stream_id=stream_id,\n data=b\"hello\",\n end_stream=True,\n )\n - self.assertEqual(h3_server._update(), [])\n \n # receive response\n + events = h3_transfer(quic_server, h3_client)\n - transfer(quic_server, quic_client)\n - events = h3_client._update()\n self.assertEqual(len(events), 2)\n \n self.assertTrue(isinstance(events[0], ResponseReceived))\n self.assertEqual(\n events[0].headers,\n [(b\":status\", b\"200\"), (b\"content-type\", b\"text/html; charset=utf-8\")],\n )\n self.assertEqual(events[0].stream_id, stream_id)\n self.assertEqual(events[0].stream_ended, False)\n \n self.assertTrue(isinstance(events[1], DataReceived))\n self.assertEqual(events[1].data, b\"hello\")\n self.assertEqual(events[1].stream_id, stream_id)\n self.assertEqual(events[1].stream_ended,"}}},{"rowIdx":2929,"cells":{"path":{"kind":"string","value":"tests.test_h3/h3_transfer"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"79cea49297f3cc02bca640db80e037ffea5a02c2"},"commit_message":{"kind":"string","value":"[http3] rework events API"},"ground_truth":{"kind":"string","value":" <1>: return h3_receiver.handle_events()\n return h3_receiver._update()\n"},"main_code":{"kind":"string","value":" # module: tests.test_h3\n def h3_transfer(quic_sender, h3_receiver):\n <0> transfer(quic_sender, h3_receiver._quic)\n <1> return h3_receiver._update()\n <2> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.h3.connection.H3Connection\n handle_events() -> List[Event]\n \n at: aioquic.h3.connection.H3Connection.__init__\n self._quic = quic\n \n at: tests.test_connection\n transfer(sender, receiver)\n \n \n===========changed ref 0===========\n # module: aioquic.h3.connection\n class H3Connection:\n + def handle_events(self) -> List[Event]:\n + \"\"\"\n + Handle events from the QUIC connection and return HTTP events.\n + \"\"\"\n + http_events: List[Event] = []\n + \n + # process QUIC events\n + event = self._quic.next_event()\n + while event is not None:\n + if isinstance(event, aioquic.events.StreamDataReceived):\n + http_events.extend(\n + self._receive_stream_data(\n + event.stream_id, event.data, event.end_stream\n + )\n + )\n + \n + event = self._quic.next_event()\n + \n + return http_events\n + \n===========changed ref 1===========\n # module: aioquic.h3.connection\n class H3Connection:\n - def receive_datagram(self, data: bytes, addr: Any, now: float) -> List[Event]:\n - \"\"\"\n - Handle an incoming datagram and return events.\n - \"\"\"\n - self._quic.receive_datagram(data, addr, now=now)\n - return self._update()\n - \n===========changed ref 2===========\n # module: aioquic.h3.connection\n class H3Connection:\n + def _init_connection(self) -> None:\n + # send our settings\n + self._local_control_stream_id = self._create_uni_stream(StreamType.CONTROL)\n + self._quic.send_stream_data(\n + self._local_control_stream_id,\n + encode_frame(\n + FrameType.SETTINGS,\n + encode_settings(\n + {\n + Setting.QPACK_MAX_TABLE_CAPACITY: self._max_table_capacity,\n + Setting.QPACK_BLOCKED_STREAMS: self._blocked_streams,\n + }\n + ),\n + ),\n + )\n + \n + # create encoder and decoder streams\n + self._local_encoder_stream_id = self._create_uni_stream(\n + StreamType.QPACK_ENCODER\n + )\n + self._local_decoder_stream_id = self._create_uni_stream(\n + StreamType.QPACK_DECODER\n + )\n + \n===========changed ref 3===========\n # module: aioquic.h3.connection\n class H3Connection:\n - def _update(self) -> List[Event]:\n - http_events: List[Event] = []\n - \n - # process QUIC events\n - event = self._quic.next_event()\n - while event is not None:\n - if isinstance(event, aioquic.events.HandshakeCompleted):\n - # send our settings\n - self._local_control_stream_id = self._create_uni_stream(\n - StreamType.CONTROL\n - )\n - self._quic.send_stream_data(\n - self._local_control_stream_id,\n - encode_frame(\n - FrameType.SETTINGS,\n - encode_settings(\n - {\n - Setting.QPACK_MAX_TABLE_CAPACITY: self._max_table_capacity,\n - Setting.QPACK_BLOCKED_STREAMS: self._blocked_streams,\n - }\n - ),\n - ),\n - )\n - \n - # create encoder and decoder streams\n - self._local_encoder_stream_id = self._create_uni_stream(\n - StreamType.QPACK_ENCODER\n - )\n - self._local_decoder_stream_id = self._create_uni_stream(\n - StreamType.QPACK_DECODER\n - )\n - elif isinstance(event, aioquic.events.StreamDataReceived):\n - http_events.extend(\n - self._receive_stream_data(\n - event.stream_id, event.data, event.end_stream\n - )\n - )\n - \n - event = self._quic.next_event()\n - \n - return http_events\n - "}}},{"rowIdx":2930,"cells":{"path":{"kind":"string","value":"examples.http3/run"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"79cea49297f3cc02bca640db80e037ffea5a02c2"},"commit_message":{"kind":"string","value":"[http3] rework events API"},"ground_truth":{"kind":"string","value":"<26>: http = H3Connection(quic)\n conn = H3Connection(quic)\n<28>: http.send_headers(\n conn.send_headers(\n<37>: http.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n conn.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n"},"main_code":{"kind":"string","value":" # module: examples.http3\n def run(url: str) -> None:\n <0> # parse URL\n <1> parsed = urlparse(url)\n <2> assert parsed.scheme == \"https\", \"Only HTTPS URLs are supported.\"\n <3> if \":\" in parsed.netloc:\n <4> server_name, port_str = parsed.netloc.split(\":\")\n <5> port = int(port_str)\n <6> else:\n <7> server_name = parsed.netloc\n <8> port = 443\n <9> \n<10> # prepare socket\n<11> server_addr = (socket.gethostbyname(server_name), port)\n<12> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n<13> \n<14> # prepare QUIC connection\n<15> quic = QuicConnection(\n<16> configuration=QuicConfiguration(\n<17> alpn_protocols=[\"h3-20\"],\n<18> is_client=True,\n<19> secrets_log_file=open(\"/tmp/ssl.log\", \"w\"),\n<20> server_name=server_name,\n<21> )\n<22> )\n<23> quic.connect(server_addr, now=time.time())\n<24> \n<25> # send request\n<26> conn = H3Connection(quic)\n<27> stream_id = quic.get_next_available_stream_id()\n<28> conn.send_headers(\n<29> stream_id=stream_id,\n<30> headers=[\n<31> (b\":method\", b\"GET\"),\n<32> (b\":scheme\", parsed.scheme.encode(\"utf8\")),\n<33> (b\":authority\", parsed.netloc.encode(\"utf8\")),\n<34> (b\":path\", parsed.path.encode(\"utf8\")),\n<35> ],\n<36> )\n<37> conn.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n<38> for data, addr in quic.datagrams_to_send(now=time.time()):\n<39> sock.sendto(data, addr)\n<40> \n<41> # handle events\n<42> stream_ended = False\n<43> while not stream_"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: examples.http3\n def run(url: str) -> None:\n # offset: 1\n data, addr = sock.recvfrom(2048)\n for event in conn.receive_datagram(data, addr, now=time.time()):\n print(event)\n if isinstance(event, (DataReceived, ResponseReceived)):\n stream_ended = event.stream_ended\n \n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n \n===========unchanged ref 0===========\n at: aioquic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_19,\n QuicProtocolVersion.DRAFT_20,\n ]\n ))\n \n at: aioquic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n certificate: Any = None\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n private_key: Any = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[tls.SessionTicket] = None\n \n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_19,\n QuicProtocolVersion.DRAFT_20,\n ]\n )\n \n at: aioquic.connection\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.connection.QuicConnection\n connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None\n \n datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]]\n \n get_next_available_stream_id(is_unidirectional=False) -> int\n \n receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None\n \n \n===========unchanged ref 1===========\n at: aioquic.h3.connection\n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection\n handle_events() -> List[Event]\n \n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: Headers) -> None\n \n at: aioquic.h3.events\n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: socket\n AF_INET: AddressFamily\n \n SOCK_DGRAM: SocketKind\n \n socket(family: int=..., type: int=..., proto: int=..., fileno: Optional[int]=...)\n \n gethostbyname(hostname: str) -> str\n \n at: socket.socket\n family: int\n \n type: int\n \n proto: int\n \n recvfrom(bufsize: int, flags: int=...) -> Tuple[bytes, _RetAddress]\n \n sendto(data: bytes, address: _Address) -> int\n sendto(data: bytes, flags: int, address: _Address) -> int\n \n at: time\n time() -> float\n \n at: urllib.parse\n urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult\n urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes\n \n \n===========changed ref 0===========\n # module: aioquic.h3.connection\n class H3Connection:\n + def handle_events(self) -> List[Event]:\n + \"\"\"\n + Handle events from the QUIC connection and return HTTP events.\n + \"\"\"\n + http_events: List[Event] = []\n + \n + # process QUIC events\n + event = self._quic.next_event()\n + while event is not None:\n + if isinstance(event, aioquic.events.StreamDataReceived):\n + http_events.extend(\n + self._receive_stream_data(\n + event.stream_id, event.data, event.end_stream\n + )\n + )\n + \n + event = self._quic.next_event()\n + \n + return http_events\n + \n===========changed ref 1===========\n # module: tests.test_h3\n def h3_transfer(quic_sender, h3_receiver):\n transfer(quic_sender, h3_receiver._quic)\n + return h3_receiver.handle_events()\n - return h3_receiver._update()\n \n===========changed ref 2===========\n # module: aioquic.h3.connection\n class H3Connection:\n - def receive_datagram(self, data: bytes, addr: Any, now: float) -> List[Event]:\n - \"\"\"\n - Handle an incoming datagram and return events.\n - \"\"\"\n - self._quic.receive_datagram(data, addr, now=now)\n - return self._update()\n - \n===========changed ref 3===========\n # module: aioquic.h3.connection\n class H3Connection:\n + def _init_connection(self) -> None:\n + # send our settings\n + self._local_control_stream_id = self._create_uni_stream(StreamType.CONTROL)\n + self._quic.send_stream_data(\n + self._local_control_stream_id,\n + encode_frame(\n + FrameType.SETTINGS,\n + encode_settings(\n + {\n + Setting.QPACK_MAX_TABLE_CAPACITY: self._max_table_capacity,\n + Setting.QPACK_BLOCKED_STREAMS: self._blocked_streams,\n + }\n + ),\n + ),\n + )\n + \n + # create encoder and decoder streams\n + self._local_encoder_stream_id = self._create_uni_stream(\n + StreamType.QPACK_ENCODER\n + )\n + self._local_decoder_stream_id = self._create_uni_stream(\n + StreamType.QPACK_DECODER\n + )\n + "}}},{"rowIdx":2931,"cells":{"path":{"kind":"string","value":"aioquic.tls/KeyScheduleProxy.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"6bb8f015301ff3ca85daf49c2db710243a637d71"},"commit_message":{"kind":"string","value":"[tls] refactor KeyScheduleProxy"},"ground_truth":{"kind":"string","value":" <0>: self.__schedules = dict(map(lambda c: (c, KeySchedule(c)), cipher_suites))\n self.__items = list(map(KeySchedule, cipher_suites))\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n class KeyScheduleProxy:\n def __init__(self, cipher_suites: List[CipherSuite]):\n <0> self.__items = list(map(KeySchedule, cipher_suites))\n <1> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.tls\n CipherSuite(x: Union[str, bytes, bytearray], base: int)\n CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n KeySchedule(cipher_suite: CipherSuite)\n \n at: typing\n List = _alias(list, 1, inst=False, name='List')\n \n "}}},{"rowIdx":2932,"cells":{"path":{"kind":"string","value":"aioquic.tls/KeyScheduleProxy.extract"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"6bb8f015301ff3ca85daf49c2db710243a637d71"},"commit_message":{"kind":"string","value":"[tls] refactor KeyScheduleProxy"},"ground_truth":{"kind":"string","value":" <0>: for k in self.__schedules.values():\n for k in self.__items:\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n class KeyScheduleProxy:\n def extract(self, key_material: Optional[bytes] = None) -> None:\n <0> for k in self.__items:\n <1> k.extract(key_material)\n <2> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.tls.KeySchedule\n extract(key_material: Optional[bytes]=None) -> None\n \n at: aioquic.tls.KeyScheduleProxy.__init__\n self.__schedules = dict(map(lambda c: (c, KeySchedule(c)), cipher_suites))\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n class KeyScheduleProxy:\n def __init__(self, cipher_suites: List[CipherSuite]):\n + self.__schedules = dict(map(lambda c: (c, KeySchedule(c)), cipher_suites))\n - self.__items = list(map(KeySchedule, cipher_suites))\n "}}},{"rowIdx":2933,"cells":{"path":{"kind":"string","value":"aioquic.tls/KeyScheduleProxy.select"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"6bb8f015301ff3ca85daf49c2db710243a637d71"},"commit_message":{"kind":"string","value":"[tls] refactor KeyScheduleProxy"},"ground_truth":{"kind":"string","value":" <0>: for k in self.__items:\n <1>: if k.cipher_suite == cipher_suite:\n <2>: return k\n <3>: raise KeyError\n <4>: return self.__schedules[cipher_suite]\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n class KeyScheduleProxy:\n def select(self, cipher_suite: CipherSuite) -> KeySchedule:\n <0> for k in self.__items:\n <1> if k.cipher_suite == cipher_suite:\n <2> return k\n <3> raise KeyError\n <4> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.tls\n CipherSuite(x: Union[str, bytes, bytearray], base: int)\n CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n KeySchedule(cipher_suite: CipherSuite)\n \n at: aioquic.tls.KeyScheduleProxy.__init__\n self.__schedules = dict(map(lambda c: (c, KeySchedule(c)), cipher_suites))\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n class KeyScheduleProxy:\n def extract(self, key_material: Optional[bytes] = None) -> None:\n + for k in self.__schedules.values():\n - for k in self.__items:\n k.extract(key_material)\n \n===========changed ref 1===========\n # module: aioquic.tls\n class KeyScheduleProxy:\n def __init__(self, cipher_suites: List[CipherSuite]):\n + self.__schedules = dict(map(lambda c: (c, KeySchedule(c)), cipher_suites))\n - self.__items = list(map(KeySchedule, cipher_suites))\n "}}},{"rowIdx":2934,"cells":{"path":{"kind":"string","value":"aioquic.tls/KeyScheduleProxy.update_hash"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"6bb8f015301ff3ca85daf49c2db710243a637d71"},"commit_message":{"kind":"string","value":"[tls] refactor KeyScheduleProxy"},"ground_truth":{"kind":"string","value":" <0>: for k in self.__schedules.values():\n for k in self.__items:\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n class KeyScheduleProxy:\n def update_hash(self, data: bytes) -> None:\n <0> for k in self.__items:\n <1> k.update_hash(data)\n <2> \n "},"context":{"kind":"string","value":"===========changed ref 0===========\n # module: aioquic.tls\n class KeyScheduleProxy:\n def extract(self, key_material: Optional[bytes] = None) -> None:\n + for k in self.__schedules.values():\n - for k in self.__items:\n k.extract(key_material)\n \n===========changed ref 1===========\n # module: aioquic.tls\n class KeyScheduleProxy:\n def select(self, cipher_suite: CipherSuite) -> KeySchedule:\n - for k in self.__items:\n - if k.cipher_suite == cipher_suite:\n - return k\n - raise KeyError\n + return self.__schedules[cipher_suite]\n \n===========changed ref 2===========\n # module: aioquic.tls\n class KeyScheduleProxy:\n def __init__(self, cipher_suites: List[CipherSuite]):\n + self.__schedules = dict(map(lambda c: (c, KeySchedule(c)), cipher_suites))\n - self.__items = list(map(KeySchedule, cipher_suites))\n "}}},{"rowIdx":2935,"cells":{"path":{"kind":"string","value":"aioquic.asyncio.server/serve"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"d0e97265c4150342955cf98fbf453b34391aabe5"},"commit_message":{"kind":"string","value":"[tests] explicitly close server after each test"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" protocols: Optional[List[str]] = None,\n connection_handler: QuicConnectionHandler = None,\n idle_timeout: Optional[float] = None,\n stream_handler: QuicStreamHandler = None,\n secrets_log_file: Optional[TextIO] = None,\n session_ticket_fetcher: Optional[SessionTicketFetcher] = None,\n session_ticket_handler: Optional[SessionTicketHandler] = None,\n stateless_retry: bool = False,\n + ) -> QuicServer:\n - ) -> None:\n <0> \"\"\"\n <1> Start a QUIC server at the given `host` and `port`.\n <2> \n <3> :func:`serve` requires a TLS certificate and private key, which can be\n <4> specified using the following arguments:\n <5> \n <6> * ``certificate`` is the server's TLS certificate.\n <7> See :func:`cryptography.x509.load_pem_x509_certificate`.\n <8> * ``private_key`` is the server's private key.\n <9> See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`.\n<10> \n<11> :func:`serve` also accepts the following optional arguments:\n<12> \n<13> * ``connection_handler`` is a callback which is invoked whenever a\n<14> connection is created. It must be a a function accepting a single\n<15> argument: a :class:`~aioquic.asyncio.QuicConnectionProtocol`.\n<16> * ``secrets_log_file`` is a file-like object in which to log traffic\n<17> secrets. This is useful to analyze traffic captures with Wireshark.\n<18> * ``session_ticket_fetcher`` is a callback which is invoked by the TLS\n<19> engine when a session ticket is presented by the peer. It should return\n<20> the session ticket with the specified ID or `None` if it is not found.\n<21> * ``session_ticket_handler`` is a callback which is invoked by the TLS\n<22> engine when a new session ticket is issued. It should store the session\n<23> ticket for future lookup.\n<24> * ``stateless_retry`` specifies whether a stateless retry should be\n<25> performed prior to handling new connections.\n<26> "},"context":{"kind":"string","value":"===========below chunk 0===========\n [str]] = None,\n connection_handler: QuicConnectionHandler = None,\n idle_timeout: Optional[float] = None,\n stream_handler: QuicStreamHandler = None,\n secrets_log_file: Optional[TextIO] = None,\n session_ticket_fetcher: Optional[SessionTicketFetcher] = None,\n session_ticket_handler: Optional[SessionTicketHandler] = None,\n stateless_retry: bool = False,\n + ) -> QuicServer:\n - ) -> None:\n # offset: 1\n created. It must accept two arguments: a :class:`asyncio.StreamReader`\n and a :class:`asyncio.StreamWriter`.\n \"\"\"\n \n loop = asyncio.get_event_loop()\n \n configuration = QuicConfiguration(\n alpn_protocols=alpn_protocols,\n certificate=certificate,\n is_client=False,\n private_key=private_key,\n secrets_log_file=secrets_log_file,\n )\n if idle_timeout is not None:\n configuration.idle_timeout = idle_timeout\n \n _, protocol = await loop.create_datagram_endpoint(\n lambda: QuicServer(\n configuration=configuration,\n connection_handler=connection_handler,\n session_ticket_fetcher=session_ticket_fetcher,\n session_ticket_handler=session_ticket_handler,\n stateless_retry=stateless_retry,\n stream_handler=stream_handler,\n ),\n local_addr=(host, port),\n )\n \n \n===========unchanged ref 0===========\n at: _asyncio\n get_event_loop()\n \n at: aioquic.asyncio.protocol\n QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None]\n \n at: aioquic.asyncio.server\n QuicConnectionHandler = Callable[[QuicConnectionProtocol], None]\n \n encode_address(addr: NetworkAddress) -> bytes\n \n QuicServer(*, configuration: QuicConfiguration, connection_handler: Optional[QuicConnectionHandler]=None, session_ticket_fetcher: Optional[SessionTicketFetcher]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stateless_retry: bool=False, stream_handler: Optional[QuicStreamHandler]=None)\n \n at: aioquic.asyncio.server.QuicServer._validate_retry_token\n retry_message = self._retry_key.decrypt(\n token,\n padding.OAEP(\n mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None\n ),\n )\n \n at: aioquic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_19,\n QuicProtocolVersion.DRAFT_20,\n ]\n ))\n \n at: aioquic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n certificate: Any = None\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n private_key: Any = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[tls.SessionTicket] = None\n \n \n===========unchanged ref 1===========\n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_19,\n QuicProtocolVersion.DRAFT_20,\n ]\n )\n \n at: aioquic.tls\n SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]]\n \n SessionTicketHandler = Callable[[SessionTicket], None]\n \n at: asyncio.events\n get_event_loop() -> AbstractEventLoop\n \n at: asyncio.events.AbstractEventLoop\n 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\n \n at: typing\n List = _alias(list, 1, inst=False, name='List')\n \n TextIO()\n \n \n===========changed ref 0===========\n # module: aioquic.asyncio.server\n class QuicServer(asyncio.DatagramProtocol):\n + def close(self):\n + for protocol in set(self._protocols.values()):\n + protocol.close()\n + self._protocols.clear()\n + self._transport.close()\n + "}}},{"rowIdx":2936,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/run_server"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"d0e97265c4150342955cf98fbf453b34391aabe5"},"commit_message":{"kind":"string","value":"[tests] explicitly close server after each test"},"ground_truth":{"kind":"string","value":" <0>: return await serve(\n await serve(\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n def run_server(**kwargs):\n <0> await serve(\n <1> host=\"::\",\n <2> port=\"4433\",\n <3> certificate=SERVER_CERTIFICATE,\n <4> private_key=SERVER_PRIVATE_KEY,\n <5> stream_handler=handle_stream,\n <6> **kwargs\n <7> )\n <8> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.asyncio.server\n serve(host: str, port: int, *, certificate: Any, private_key: Any, alpn_protocols: Optional[List[str]]=None, connection_handler: QuicConnectionHandler=None, idle_timeout: Optional[float]=None, stream_handler: QuicStreamHandler=None, secrets_log_file: Optional[TextIO]=None, session_ticket_fetcher: Optional[SessionTicketFetcher]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stateless_retry: bool=False) -> QuicServer\n \n at: tests.test_asyncio\n handle_stream(reader, writer)\n \n at: tests.utils\n SERVER_CERTIFICATE = x509.load_pem_x509_certificate(\n load(\"ssl_cert.pem\"), backend=default_backend()\n )\n \n SERVER_PRIVATE_KEY = serialization.load_pem_private_key(\n load(\"ssl_key.pem\"), password=None, backend=default_backend()\n )\n \n \n===========changed ref 0===========\n protocols: Optional[List[str]] = None,\n connection_handler: QuicConnectionHandler = None,\n idle_timeout: Optional[float] = None,\n stream_handler: QuicStreamHandler = None,\n secrets_log_file: Optional[TextIO] = None,\n session_ticket_fetcher: Optional[SessionTicketFetcher] = None,\n session_ticket_handler: Optional[SessionTicketHandler] = None,\n stateless_retry: bool = False,\n + ) -> QuicServer:\n - ) -> None:\n \"\"\"\n Start a QUIC server at the given `host` and `port`.\n \n :func:`serve` requires a TLS certificate and private key, which can be\n specified using the following arguments:\n \n * ``certificate`` is the server's TLS certificate.\n See :func:`cryptography.x509.load_pem_x509_certificate`.\n * ``private_key`` is the server's private key.\n See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`.\n \n :func:`serve` also accepts the following optional arguments:\n \n * ``connection_handler`` is a callback which is invoked whenever a\n connection is created. It must be a a function accepting a single\n argument: a :class:`~aioquic.asyncio.QuicConnectionProtocol`.\n * ``secrets_log_file`` is a file-like object in which to log traffic\n secrets. This is useful to analyze traffic captures with Wireshark.\n * ``session_ticket_fetcher`` is a callback which is invoked by the TLS\n engine when a session ticket is presented by the peer. It should return\n the session ticket with the specified ID or `None` if it is not found.\n * ``session_ticket_handler`` is a callback which is invoked by the TLS\n engine when a new session ticket is issued. It should store the session\n ticket for future lookup.\n * ``stateless_retry`` specifies whether a stateless retry should be\n performed prior to handling new connections.\n * ``stream_handler`` is a callback which is invoked whenever a stream is\n created. It must accept two arguments:\n===========changed ref 1===========\n [str]] = None,\n connection_handler: QuicConnectionHandler = None,\n idle_timeout: Optional[float] = None,\n stream_handler: QuicStreamHandler = None,\n secrets_log_file: Optional[TextIO] = None,\n session_ticket_fetcher: Optional[SessionTicketFetcher] = None,\n session_ticket_handler: Optional[SessionTicketHandler] = None,\n stateless_retry: bool = False,\n + ) -> QuicServer:\n - ) -> None:\n # offset: 1\n connections.\n * ``stream_handler`` is a callback which is invoked whenever a stream is\n created. It must accept two arguments: a :class:`asyncio.StreamReader`\n and a :class:`asyncio.StreamWriter`.\n \"\"\"\n \n loop = asyncio.get_event_loop()\n \n configuration = QuicConfiguration(\n alpn_protocols=alpn_protocols,\n certificate=certificate,\n is_client=False,\n private_key=private_key,\n secrets_log_file=secrets_log_file,\n )\n if idle_timeout is not None:\n configuration.idle_timeout = idle_timeout\n \n _, protocol = await loop.create_datagram_endpoint(\n lambda: QuicServer(\n configuration=configuration,\n connection_handler=connection_handler,\n session_ticket_fetcher=session_ticket_fetcher,\n session_ticket_handler=session_ticket_handler,\n stateless_retry=stateless_retry,\n stream_handler=stream_handler,\n ),\n local_addr=(host, port),\n )\n + return cast(QuicServer, protocol)\n \n===========changed ref 2===========\n # module: aioquic.asyncio.server\n class QuicServer(asyncio.DatagramProtocol):\n + def close(self):\n + for protocol in set(self._protocols.values()):\n + protocol.close()\n + self._protocols.clear()\n + self._transport.close()\n + "}}},{"rowIdx":2937,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_and_serve"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"d0e97265c4150342955cf98fbf453b34391aabe5"},"commit_message":{"kind":"string","value":"[tests] explicitly close server after each test"},"ground_truth":{"kind":"string","value":" <0>: server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n _, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n <2>: server.close()\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n <0> _, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n <1> self.assertEqual(response, b\"gnip\")\n <2> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: asyncio.tasks\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[\n Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]]\n ]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]]\n gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[\n===========unchanged ref 1===========\n at: tests.test_asyncio\n run_client(host, port=4433, request=b\"ping\", *, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds)\n \n run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None)\n \n at: tests.utils\n run(coro)\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n _testMethodDoc: str\n \n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n def run_server(**kwargs):\n + return await serve(\n - await serve(\n host=\"::\",\n port=\"4433\",\n certificate=SERVER_CERTIFICATE,\n private_key=SERVER_PRIVATE_KEY,\n stream_handler=handle_stream,\n **kwargs\n )\n \n===========changed ref 1===========\n # module: aioquic.asyncio.server\n class QuicServer(asyncio.DatagramProtocol):\n + def close(self):\n + for protocol in set(self._protocols.values()):\n + protocol.close()\n + self._protocols.clear()\n + self._transport.close()\n + \n===========changed ref 2===========\n protocols: Optional[List[str]] = None,\n connection_handler: QuicConnectionHandler = None,\n idle_timeout: Optional[float] = None,\n stream_handler: QuicStreamHandler = None,\n secrets_log_file: Optional[TextIO] = None,\n session_ticket_fetcher: Optional[SessionTicketFetcher] = None,\n session_ticket_handler: Optional[SessionTicketHandler] = None,\n stateless_retry: bool = False,\n + ) -> QuicServer:\n - ) -> None:\n \"\"\"\n Start a QUIC server at the given `host` and `port`.\n \n :func:`serve` requires a TLS certificate and private key, which can be\n specified using the following arguments:\n \n * ``certificate`` is the server's TLS certificate.\n See :func:`cryptography.x509.load_pem_x509_certificate`.\n * ``private_key`` is the server's private key.\n See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`.\n \n :func:`serve` also accepts the following optional arguments:\n \n * ``connection_handler`` is a callback which is invoked whenever a\n connection is created. It must be a a function accepting a single\n argument: a :class:`~aioquic.asyncio.QuicConnectionProtocol`.\n * ``secrets_log_file`` is a file-like object in which to log traffic\n secrets. This is useful to analyze traffic captures with Wireshark.\n * ``session_ticket_fetcher`` is a callback which is invoked by the TLS\n engine when a session ticket is presented by the peer. It should return\n the session ticket with the specified ID or `None` if it is not found.\n * ``session_ticket_handler`` is a callback which is invoked by the TLS\n engine when a new session ticket is issued. It should store the session\n ticket for future lookup.\n * ``stateless_retry`` specifies whether a stateless retry should be\n performed prior to handling new connections.\n * ``stream_handler`` is a callback which is invoked whenever a stream is\n created. It must accept two arguments:\n===========changed ref 3===========\n [str]] = None,\n connection_handler: QuicConnectionHandler = None,\n idle_timeout: Optional[float] = None,\n stream_handler: QuicStreamHandler = None,\n secrets_log_file: Optional[TextIO] = None,\n session_ticket_fetcher: Optional[SessionTicketFetcher] = None,\n session_ticket_handler: Optional[SessionTicketHandler] = None,\n stateless_retry: bool = False,\n + ) -> QuicServer:\n - ) -> None:\n # offset: 1\n connections.\n * ``stream_handler`` is a callback which is invoked whenever a stream is\n created. It must accept two arguments: a :class:`asyncio.StreamReader`\n and a :class:`asyncio.StreamWriter`.\n \"\"\"\n \n loop = asyncio.get_event_loop()\n \n configuration = QuicConfiguration(\n alpn_protocols=alpn_protocols,\n certificate=certificate,\n is_client=False,\n private_key=private_key,\n secrets_log_file=secrets_log_file,\n )\n if idle_timeout is not None:\n configuration.idle_timeout = idle_timeout\n \n _, protocol = await loop.create_datagram_endpoint(\n lambda: QuicServer(\n configuration=configuration,\n connection_handler=connection_handler,\n session_ticket_fetcher=session_ticket_fetcher,\n session_ticket_handler=session_ticket_handler,\n stateless_retry=stateless_retry,\n stream_handler=stream_handler,\n ),\n local_addr=(host, port),\n )\n + return cast(QuicServer, protocol)\n "}}},{"rowIdx":2938,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_and_serve_large"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"d0e97265c4150342955cf98fbf453b34391aabe5"},"commit_message":{"kind":"string","value":"[tests] explicitly close server after each test"},"ground_truth":{"kind":"string","value":" <4>: server, response = run(\n _, response = run(\n <8>: server.close()\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_large(self):\n <0> \"\"\"\n <1> Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA.\n <2> \"\"\"\n <3> data = b\"Z\" * 2097152\n <4> _, response = run(\n <5> asyncio.gather(run_server(), run_client(\"127.0.0.1\", request=data))\n <6> )\n <7> self.assertEqual(response, data)\n <8> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: asyncio.tasks\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[\n Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]]\n ]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]]\n gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[\n===========unchanged ref 1===========\n at: tests.test_asyncio\n run_client(host, port=4433, request=b\"ping\", *, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds)\n \n run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None)\n \n at: tests.utils\n run(coro)\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n def run_server(**kwargs):\n + return await serve(\n - await serve(\n host=\"::\",\n port=\"4433\",\n certificate=SERVER_CERTIFICATE,\n private_key=SERVER_PRIVATE_KEY,\n stream_handler=handle_stream,\n **kwargs\n )\n \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n + server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n - _, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 2===========\n # module: aioquic.asyncio.server\n class QuicServer(asyncio.DatagramProtocol):\n + def close(self):\n + for protocol in set(self._protocols.values()):\n + protocol.close()\n + self._protocols.clear()\n + self._transport.close()\n + \n===========changed ref 3===========\n protocols: Optional[List[str]] = None,\n connection_handler: QuicConnectionHandler = None,\n idle_timeout: Optional[float] = None,\n stream_handler: QuicStreamHandler = None,\n secrets_log_file: Optional[TextIO] = None,\n session_ticket_fetcher: Optional[SessionTicketFetcher] = None,\n session_ticket_handler: Optional[SessionTicketHandler] = None,\n stateless_retry: bool = False,\n + ) -> QuicServer:\n - ) -> None:\n \"\"\"\n Start a QUIC server at the given `host` and `port`.\n \n :func:`serve` requires a TLS certificate and private key, which can be\n specified using the following arguments:\n \n * ``certificate`` is the server's TLS certificate.\n See :func:`cryptography.x509.load_pem_x509_certificate`.\n * ``private_key`` is the server's private key.\n See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`.\n \n :func:`serve` also accepts the following optional arguments:\n \n * ``connection_handler`` is a callback which is invoked whenever a\n connection is created. It must be a a function accepting a single\n argument: a :class:`~aioquic.asyncio.QuicConnectionProtocol`.\n * ``secrets_log_file`` is a file-like object in which to log traffic\n secrets. This is useful to analyze traffic captures with Wireshark.\n * ``session_ticket_fetcher`` is a callback which is invoked by the TLS\n engine when a session ticket is presented by the peer. It should return\n the session ticket with the specified ID or `None` if it is not found.\n * ``session_ticket_handler`` is a callback which is invoked by the TLS\n engine when a new session ticket is issued. It should store the session\n ticket for future lookup.\n * ``stateless_retry`` specifies whether a stateless retry should be\n performed prior to handling new connections.\n * ``stream_handler`` is a callback which is invoked whenever a stream is\n created. It must accept two arguments:\n===========changed ref 4===========\n [str]] = None,\n connection_handler: QuicConnectionHandler = None,\n idle_timeout: Optional[float] = None,\n stream_handler: QuicStreamHandler = None,\n secrets_log_file: Optional[TextIO] = None,\n session_ticket_fetcher: Optional[SessionTicketFetcher] = None,\n session_ticket_handler: Optional[SessionTicketHandler] = None,\n stateless_retry: bool = False,\n + ) -> QuicServer:\n - ) -> None:\n # offset: 1\n connections.\n * ``stream_handler`` is a callback which is invoked whenever a stream is\n created. It must accept two arguments: a :class:`asyncio.StreamReader`\n and a :class:`asyncio.StreamWriter`.\n \"\"\"\n \n loop = asyncio.get_event_loop()\n \n configuration = QuicConfiguration(\n alpn_protocols=alpn_protocols,\n certificate=certificate,\n is_client=False,\n private_key=private_key,\n secrets_log_file=secrets_log_file,\n )\n if idle_timeout is not None:\n configuration.idle_timeout = idle_timeout\n \n _, protocol = await loop.create_datagram_endpoint(\n lambda: QuicServer(\n configuration=configuration,\n connection_handler=connection_handler,\n session_ticket_fetcher=session_ticket_fetcher,\n session_ticket_handler=session_ticket_handler,\n stateless_retry=stateless_retry,\n stream_handler=stream_handler,\n ),\n local_addr=(host, port),\n )\n + return cast(QuicServer, protocol)\n "}}},{"rowIdx":2939,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_and_serve_writelines"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"d0e97265c4150342955cf98fbf453b34391aabe5"},"commit_message":{"kind":"string","value":"[tests] explicitly close server after each test"},"ground_truth":{"kind":"string","value":"<10>: server, response = run(\n _, response = run(\n<14>: server.close()\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_writelines(self):\n <0> async def run_client_writelines(host, port=4433, **kwargs):\n <1> async with connect(host, port, **kwargs) as client:\n <2> reader, writer = await client.create_stream()\n <3> assert writer.can_write_eof() is True\n <4> \n <5> writer.writelines([b\"01234567\", b\"89012345\"])\n <6> writer.write_eof()\n <7> \n <8> return await reader.read()\n <9> \n<10> _, response = run(\n<11> asyncio.gather(run_server(), run_client_writelines(\"127.0.0.1\"))\n<12> )\n<13> self.assertEqual(response, b\"5432109876543210\")\n<14> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.asyncio.client\n connect(*args, **kwds)\n connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None]\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol\n create_stream(is_unidirectional: bool=False) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]\n \n at: asyncio.streams.StreamWriter\n writelines(data: Iterable[bytes]) -> None\n \n can_write_eof() -> bool\n \n \n===========unchanged ref 1===========\n at: asyncio.tasks\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[\n Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]]\n ]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]]\n gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[\n===========unchanged ref 2===========\n at: tests.test_asyncio\n run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None)\n \n at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_large\n server, response = run(\n asyncio.gather(run_server(), run_client(\"127.0.0.1\", request=data))\n )\n \n at: tests.utils\n run(coro)\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n def run_server(**kwargs):\n + return await serve(\n - await serve(\n host=\"::\",\n port=\"4433\",\n certificate=SERVER_CERTIFICATE,\n private_key=SERVER_PRIVATE_KEY,\n stream_handler=handle_stream,\n **kwargs\n )\n \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n + server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n - _, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_large(self):\n \"\"\"\n Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA.\n \"\"\"\n data = b\"Z\" * 2097152\n + server, response = run(\n - _, response = run(\n asyncio.gather(run_server(), run_client(\"127.0.0.1\", request=data))\n )\n self.assertEqual(response, data)\n + server.close()\n \n===========changed ref 3===========\n # module: aioquic.asyncio.server\n class QuicServer(asyncio.DatagramProtocol):\n + def close(self):\n + for protocol in set(self._protocols.values()):\n + protocol.close()\n + self._protocols.clear()\n + self._transport.close()\n + \n===========changed ref 4===========\n protocols: Optional[List[str]] = None,\n connection_handler: QuicConnectionHandler = None,\n idle_timeout: Optional[float] = None,\n stream_handler: QuicStreamHandler = None,\n secrets_log_file: Optional[TextIO] = None,\n session_ticket_fetcher: Optional[SessionTicketFetcher] = None,\n session_ticket_handler: Optional[SessionTicketHandler] = None,\n stateless_retry: bool = False,\n + ) -> QuicServer:\n - ) -> None:\n \"\"\"\n Start a QUIC server at the given `host` and `port`.\n \n :func:`serve` requires a TLS certificate and private key, which can be\n specified using the following arguments:\n \n * ``certificate`` is the server's TLS certificate.\n See :func:`cryptography.x509.load_pem_x509_certificate`.\n * ``private_key`` is the server's private key.\n See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`.\n \n :func:`serve` also accepts the following optional arguments:\n \n * ``connection_handler`` is a callback which is invoked whenever a\n connection is created. It must be a a function accepting a single\n argument: a :class:`~aioquic.asyncio.QuicConnectionProtocol`.\n * ``secrets_log_file`` is a file-like object in which to log traffic\n secrets. This is useful to analyze traffic captures with Wireshark.\n * ``session_ticket_fetcher`` is a callback which is invoked by the TLS\n engine when a session ticket is presented by the peer. It should return\n the session ticket with the specified ID or `None` if it is not found.\n * ``session_ticket_handler`` is a callback which is invoked by the TLS\n engine when a new session ticket is issued. It should store the session\n ticket for future lookup.\n * ``stateless_retry`` specifies whether a stateless retry should be\n performed prior to handling new connections.\n * ``stream_handler`` is a callback which is invoked whenever a stream is\n created. It must accept two arguments:"}}},{"rowIdx":2940,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_connection_handler"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"d0e97265c4150342955cf98fbf453b34391aabe5"},"commit_message":{"kind":"string","value":"[tests] explicitly close server after each test"},"ground_truth":{"kind":"string","value":" <6>: server, response = run(\n _, response = run(\n<14>: server.close()\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_connection_handler(self):\n <0> server_conn = None\n <1> \n <2> def connection_handler(conn):\n <3> nonlocal server_conn\n <4> server_conn = conn\n <5> \n <6> _, response = run(\n <7> asyncio.gather(\n <8> run_server(connection_handler=connection_handler),\n <9> run_client(\"127.0.0.1\"),\n<10> )\n<11> )\n<12> self.assertEqual(response, b\"gnip\")\n<13> self.assertIsNotNone(server_conn)\n<14> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: asyncio.tasks\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[\n Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]]\n ]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]]\n gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[\n===========unchanged ref 1===========\n at: tests.test_asyncio\n run_client(host, port=4433, request=b\"ping\", *, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds)\n \n run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None)\n \n at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_writelines\n server, response = run(\n asyncio.gather(run_server(), run_client_writelines(\"127.0.0.1\"))\n )\n \n server, response = run(\n asyncio.gather(run_server(), run_client_writelines(\"127.0.0.1\"))\n )\n \n at: tests.utils\n run(coro)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n def run_server(**kwargs):\n + return await serve(\n - await serve(\n host=\"::\",\n port=\"4433\",\n certificate=SERVER_CERTIFICATE,\n private_key=SERVER_PRIVATE_KEY,\n stream_handler=handle_stream,\n **kwargs\n )\n \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n + server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n - _, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_large(self):\n \"\"\"\n Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA.\n \"\"\"\n data = b\"Z\" * 2097152\n + server, response = run(\n - _, response = run(\n asyncio.gather(run_server(), run_client(\"127.0.0.1\", request=data))\n )\n self.assertEqual(response, data)\n + server.close()\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_writelines(self):\n async def run_client_writelines(host, port=4433, **kwargs):\n async with connect(host, port, **kwargs) as client:\n reader, writer = await client.create_stream()\n assert writer.can_write_eof() is True\n \n writer.writelines([b\"01234567\", b\"89012345\"])\n writer.write_eof()\n \n return await reader.read()\n \n + server, response = run(\n - _, response = run(\n asyncio.gather(run_server(), run_client_writelines(\"127.0.0.1\"))\n )\n self.assertEqual(response, b\"5432109876543210\")\n + server.close()\n \n===========changed ref 4===========\n # module: aioquic.asyncio.server\n class QuicServer(asyncio.DatagramProtocol):\n + def close(self):\n + for protocol in set(self._protocols.values()):\n + protocol.close()\n + self._protocols.clear()\n + self._transport.close()\n + \n===========changed ref 5===========\n protocols: Optional[List[str]] = None,\n connection_handler: QuicConnectionHandler = None,\n idle_timeout: Optional[float] = None,\n stream_handler: QuicStreamHandler = None,\n secrets_log_file: Optional[TextIO] = None,\n session_ticket_fetcher: Optional[SessionTicketFetcher] = None,\n session_ticket_handler: Optional[SessionTicketHandler] = None,\n stateless_retry: bool = False,\n + ) -> QuicServer:\n - ) -> None:\n \"\"\"\n Start a QUIC server at the given `host` and `port`.\n \n :func:`serve` requires a TLS certificate and private key, which can be\n specified using the following arguments:\n \n * ``certificate`` is the server's TLS certificate.\n See :func:`cryptography.x509.load_pem_x509_certificate`.\n * ``private_key`` is the server's private key.\n See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`.\n \n :func:`serve` also accepts the following optional arguments:\n \n * ``connection_handler`` is a callback which is invoked whenever a\n connection is created. It must be a a function accepting a single\n argument: a :class:`~aioquic.asyncio.QuicConnectionProtocol`.\n * ``secrets_log_file`` is a file-like object in which to log traffic\n secrets. This is useful to analyze traffic captures with Wireshark.\n * ``session_ticket_fetcher`` is a callback which is invoked by the TLS\n engine when a session ticket is presented by the peer. It should return\n the session ticket with the specified ID or `None` if it is not found.\n * ``session_ticket_handler`` is a callback which is invoked by the TLS\n engine when a new session ticket is issued. It should store the session\n ticket for future lookup.\n * ``stateless_retry`` specifies whether a stateless retry should be\n performed prior to handling new connections.\n * ``stream_handler`` is a callback which is invoked whenever a stream is\n created. It must accept two arguments:"}}},{"rowIdx":2941,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_packet_loss"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"d0e97265c4150342955cf98fbf453b34391aabe5"},"commit_message":{"kind":"string","value":"[tests] explicitly close server after each test"},"ground_truth":{"kind":"string","value":" <5>: server, response = run(\n _, response = run(\n<12>: server.close()\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n @patch(\"socket.socket.sendto\", new_callable=lambda: sendto_with_loss)\n def test_connect_and_serve_with_packet_loss(self, mock_sendto):\n <0> \"\"\"\n <1> This test ensures handshake success and stream data is successfully sent\n <2> and received in the presence of packet loss (randomized 25% in each direction).\n <3> \"\"\"\n <4> data = b\"Z\" * 65536\n <5> _, response = run(\n <6> asyncio.gather(\n <7> run_server(idle_timeout=300.0, stateless_retry=True),\n <8> run_client(\"127.0.0.1\", idle_timeout=300.0, request=data),\n <9> )\n<10> )\n<11> self.assertEqual(response, data)\n<12> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: asyncio.tasks\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[\n Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]]\n ]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]]\n gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[\n===========unchanged ref 1===========\n at: tests.test_asyncio\n sendto_with_loss(self, data, addr=None)\n \n run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None)\n \n at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_connection_handler\n server_conn = None\n \n server, response = run(\n asyncio.gather(\n run_server(connection_handler=connection_handler),\n run_client(\"127.0.0.1\"),\n )\n )\n \n server, response = run(\n asyncio.gather(\n run_server(connection_handler=connection_handler),\n run_client(\"127.0.0.1\"),\n )\n )\n \n at: tests.utils\n run(coro)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertIsNotNone(obj: Any, msg: Any=...) -> None\n \n at: unittest.mock\n _patcher(target: Any, new: _T, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[_T]\n _patcher(target: Any, *, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[Union[MagicMock, AsyncMock]]\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n def run_server(**kwargs):\n + return await serve(\n - await serve(\n host=\"::\",\n port=\"4433\",\n certificate=SERVER_CERTIFICATE,\n private_key=SERVER_PRIVATE_KEY,\n stream_handler=handle_stream,\n **kwargs\n )\n \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_connection_handler(self):\n server_conn = None\n \n def connection_handler(conn):\n nonlocal server_conn\n server_conn = conn\n \n + server, response = run(\n - _, response = run(\n asyncio.gather(\n run_server(connection_handler=connection_handler),\n run_client(\"127.0.0.1\"),\n )\n )\n self.assertEqual(response, b\"gnip\")\n self.assertIsNotNone(server_conn)\n + server.close()\n \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n + server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n - _, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_large(self):\n \"\"\"\n Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA.\n \"\"\"\n data = b\"Z\" * 2097152\n + server, response = run(\n - _, response = run(\n asyncio.gather(run_server(), run_client(\"127.0.0.1\", request=data))\n )\n self.assertEqual(response, data)\n + server.close()\n \n===========changed ref 4===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_writelines(self):\n async def run_client_writelines(host, port=4433, **kwargs):\n async with connect(host, port, **kwargs) as client:\n reader, writer = await client.create_stream()\n assert writer.can_write_eof() is True\n \n writer.writelines([b\"01234567\", b\"89012345\"])\n writer.write_eof()\n \n return await reader.read()\n \n + server, response = run(\n - _, response = run(\n asyncio.gather(run_server(), run_client_writelines(\"127.0.0.1\"))\n )\n self.assertEqual(response, b\"5432109876543210\")\n + server.close()\n \n===========changed ref 5===========\n # module: aioquic.asyncio.server\n class QuicServer(asyncio.DatagramProtocol):\n + def close(self):\n + for protocol in set(self._protocols.values()):\n + protocol.close()\n + self._protocols.clear()\n + self._transport.close()\n + "}}},{"rowIdx":2942,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_session_ticket"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"d0e97265c4150342955cf98fbf453b34391aabe5"},"commit_message":{"kind":"string","value":"[tests] explicitly close server after each test"},"ground_truth":{"kind":"string","value":" <8>: server, response = run(\n _, response = run(\n<15>: server.close()\n<19>: server, response = run(\n _, response = run(\n<26>: server.close()\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_session_ticket(self):\n <0> client_ticket = None\n <1> store = SessionTicketStore()\n <2> \n <3> def save_ticket(t):\n <4> nonlocal client_ticket\n <5> client_ticket = t\n <6> \n <7> # first request\n <8> _, response = run(\n <9> asyncio.gather(\n<10> run_server(session_ticket_handler=store.add),\n<11> run_client(\"127.0.0.1\", session_ticket_handler=save_ticket),\n<12> )\n<13> )\n<14> self.assertEqual(response, b\"gnip\")\n<15> \n<16> self.assertIsNotNone(client_ticket)\n<17> \n<18> # second request\n<19> _, response = run(\n<20> asyncio.gather(\n<21> run_server(session_ticket_fetcher=store.pop),\n<22> run_client(\"127.0.0.1\", session_ticket=client_ticket),\n<23> )\n<24> )\n<25> self.assertEqual(response, b\"gnip\")\n<26> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: asyncio.tasks\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[\n Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]]\n ]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]]\n gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[\n===========unchanged ref 1===========\n at: tests.test_asyncio\n SessionTicketStore()\n \n run_client(host, port=4433, request=b\"ping\", *, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds)\n \n run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None)\n \n at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_packet_loss\n data = b\"Z\" * 65536\n \n server, response = run(\n asyncio.gather(\n run_server(idle_timeout=300.0, stateless_retry=True),\n run_client(\"127.0.0.1\", idle_timeout=300.0, request=data),\n )\n )\n \n server, response = run(\n asyncio.gather(\n run_server(idle_timeout=300.0, stateless_retry=True),\n run_client(\"127.0.0.1\", idle_timeout=300.0, request=data),\n )\n )\n \n at: tests.test_asyncio.SessionTicketStore\n add(ticket)\n \n at: tests.utils\n run(coro)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertIsNotNone(obj: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n def run_server(**kwargs):\n + return await serve(\n - await serve(\n host=\"::\",\n port=\"4433\",\n certificate=SERVER_CERTIFICATE,\n private_key=SERVER_PRIVATE_KEY,\n stream_handler=handle_stream,\n **kwargs\n )\n \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_connection_handler(self):\n server_conn = None\n \n def connection_handler(conn):\n nonlocal server_conn\n server_conn = conn\n \n + server, response = run(\n - _, response = run(\n asyncio.gather(\n run_server(connection_handler=connection_handler),\n run_client(\"127.0.0.1\"),\n )\n )\n self.assertEqual(response, b\"gnip\")\n self.assertIsNotNone(server_conn)\n + server.close()\n \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n + server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n - _, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n @patch(\"socket.socket.sendto\", new_callable=lambda: sendto_with_loss)\n def test_connect_and_serve_with_packet_loss(self, mock_sendto):\n \"\"\"\n This test ensures handshake success and stream data is successfully sent\n and received in the presence of packet loss (randomized 25% in each direction).\n \"\"\"\n data = b\"Z\" * 65536\n + server, response = run(\n - _, response = run(\n asyncio.gather(\n run_server(idle_timeout=300.0, stateless_retry=True),\n run_client(\"127.0.0.1\", idle_timeout=300.0, request=data),\n )\n )\n self.assertEqual(response, data)\n + server.close()\n \n===========changed ref 4===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_large(self):\n \"\"\"\n Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA.\n \"\"\"\n data = b\"Z\" * 2097152\n + server, response = run(\n - _, response = run(\n asyncio.gather(run_server(), run_client(\"127.0.0.1\", request=data))\n )\n self.assertEqual(response, data)\n + server.close()\n \n===========changed ref 5===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_writelines(self):\n async def run_client_writelines(host, port=4433, **kwargs):\n async with connect(host, port, **kwargs) as client:\n reader, writer = await client.create_stream()\n assert writer.can_write_eof() is True\n \n writer.writelines([b\"01234567\", b\"89012345\"])\n writer.write_eof()\n \n return await reader.read()\n \n + server, response = run(\n - _, response = run(\n asyncio.gather(run_server(), run_client_writelines(\"127.0.0.1\"))\n )\n self.assertEqual(response, b\"5432109876543210\")\n + server.close()\n \n===========changed ref 6===========\n # module: aioquic.asyncio.server\n class QuicServer(asyncio.DatagramProtocol):\n + def close(self):\n + for protocol in set(self._protocols.values()):\n + protocol.close()\n + self._protocols.clear()\n + self._transport.close()\n + "}}},{"rowIdx":2943,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_sni"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"d0e97265c4150342955cf98fbf453b34391aabe5"},"commit_message":{"kind":"string","value":"[tests] explicitly close server after each test"},"ground_truth":{"kind":"string","value":" <0>: server, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n _, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n <2>: server.close()\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_sni(self):\n <0> _, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n <1> self.assertEqual(response, b\"gnip\")\n <2> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: tests.test_asyncio\n run_client(host, port=4433, request=b\"ping\", *, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds)\n \n run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None)\n \n at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_session_ticket\n client_ticket = None\n \n store = SessionTicketStore()\n \n at: tests.test_asyncio.SessionTicketStore\n pop(label)\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n def run_server(**kwargs):\n + return await serve(\n - await serve(\n host=\"::\",\n port=\"4433\",\n certificate=SERVER_CERTIFICATE,\n private_key=SERVER_PRIVATE_KEY,\n stream_handler=handle_stream,\n **kwargs\n )\n \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_connection_handler(self):\n server_conn = None\n \n def connection_handler(conn):\n nonlocal server_conn\n server_conn = conn\n \n + server, response = run(\n - _, response = run(\n asyncio.gather(\n run_server(connection_handler=connection_handler),\n run_client(\"127.0.0.1\"),\n )\n )\n self.assertEqual(response, b\"gnip\")\n self.assertIsNotNone(server_conn)\n + server.close()\n \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n + server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n - _, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n @patch(\"socket.socket.sendto\", new_callable=lambda: sendto_with_loss)\n def test_connect_and_serve_with_packet_loss(self, mock_sendto):\n \"\"\"\n This test ensures handshake success and stream data is successfully sent\n and received in the presence of packet loss (randomized 25% in each direction).\n \"\"\"\n data = b\"Z\" * 65536\n + server, response = run(\n - _, response = run(\n asyncio.gather(\n run_server(idle_timeout=300.0, stateless_retry=True),\n run_client(\"127.0.0.1\", idle_timeout=300.0, request=data),\n )\n )\n self.assertEqual(response, data)\n + server.close()\n \n===========changed ref 4===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_large(self):\n \"\"\"\n Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA.\n \"\"\"\n data = b\"Z\" * 2097152\n + server, response = run(\n - _, response = run(\n asyncio.gather(run_server(), run_client(\"127.0.0.1\", request=data))\n )\n self.assertEqual(response, data)\n + server.close()\n \n===========changed ref 5===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_writelines(self):\n async def run_client_writelines(host, port=4433, **kwargs):\n async with connect(host, port, **kwargs) as client:\n reader, writer = await client.create_stream()\n assert writer.can_write_eof() is True\n \n writer.writelines([b\"01234567\", b\"89012345\"])\n writer.write_eof()\n \n return await reader.read()\n \n + server, response = run(\n - _, response = run(\n asyncio.gather(run_server(), run_client_writelines(\"127.0.0.1\"))\n )\n self.assertEqual(response, b\"5432109876543210\")\n + server.close()\n \n===========changed ref 6===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_session_ticket(self):\n client_ticket = None\n store = SessionTicketStore()\n \n def save_ticket(t):\n nonlocal client_ticket\n client_ticket = t\n \n # first request\n + server, response = run(\n - _, response = run(\n asyncio.gather(\n run_server(session_ticket_handler=store.add),\n run_client(\"127.0.0.1\", session_ticket_handler=save_ticket),\n )\n )\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n self.assertIsNotNone(client_ticket)\n \n # second request\n + server, response = run(\n - _, response = run(\n asyncio.gather(\n run_server(session_ticket_fetcher=store.pop),\n run_client(\"127.0.0.1\", session_ticket=client_ticket),\n )\n )\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 7===========\n # module: aioquic.asyncio.server\n class QuicServer(asyncio.DatagramProtocol):\n + def close(self):\n + for protocol in set(self._protocols.values()):\n + protocol.close()\n + self._protocols.clear()\n + self._transport.close()\n + \n===========changed ref 8===========\n protocols: Optional[List[str]] = None,\n connection_handler: QuicConnectionHandler = None,\n idle_timeout: Optional[float] = None,\n stream_handler: QuicStreamHandler = None,\n secrets_log_file: Optional[TextIO] = None,\n session_ticket_fetcher: Optional[SessionTicketFetcher] = None,\n session_ticket_handler: Optional[SessionTicketHandler] = None,\n stateless_retry: bool = False,\n + ) -> QuicServer:\n - ) -> None:\n \"\"\"\n Start a QUIC server at the given `host` and `port`.\n \n :func:`serve` requires a TLS certificate and private key, which can be\n specified using the following arguments:\n \n * ``certificate`` is the server's TLS certificate.\n See :func:`cryptography.x509.load_pem_x509_certificate`.\n * ``private_key`` is the server's private key.\n See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`.\n \n :func:`serve` also accepts the following optional arguments:\n \n * ``connection_handler`` is a callback which is invoked whenever a\n connection is created. It must be a a function accepting a single\n argument: a :class:`~aioquic.asyncio.QuicConnectionProtocol`.\n * ``secrets_log_file`` is a file-like object in which to log traffic\n secrets. This is useful to analyze traffic captures with Wireshark.\n * ``session_ticket_fetcher`` is a callback which is invoked by the TLS\n engine when a session ticket is presented by the peer. It should return\n the session ticket with the specified ID or `None` if it is not found.\n * ``session_ticket_handler`` is a callback which is invoked by the TLS\n engine when a new session ticket is issued. It should store the session\n ticket for future lookup.\n * ``stateless_retry`` specifies whether a stateless retry should be\n performed prior to handling new connections.\n * ``stream_handler`` is a callback which is invoked whenever a stream is\n created. It must accept two arguments:"}}},{"rowIdx":2944,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_stateless_retry"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"d0e97265c4150342955cf98fbf453b34391aabe5"},"commit_message":{"kind":"string","value":"[tests] explicitly close server after each test"},"ground_truth":{"kind":"string","value":" <0>: server, response = run(\n _, response = run(\n <4>: server.close()\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_stateless_retry(self):\n <0> _, response = run(\n <1> asyncio.gather(run_server(stateless_retry=True), run_client(\"127.0.0.1\"))\n <2> )\n <3> self.assertEqual(response, b\"gnip\")\n <4> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: asyncio.tasks\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[\n Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]]\n ]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]]\n gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[\n===========unchanged ref 1===========\n at: tests.test_asyncio\n run_client(host, port=4433, request=b\"ping\", *, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds)\n \n run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None)\n \n at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_session_ticket\n server, response = run(\n asyncio.gather(\n run_server(session_ticket_handler=store.add),\n run_client(\"127.0.0.1\", session_ticket_handler=save_ticket),\n )\n )\n server, response = run(\n asyncio.gather(\n run_server(session_ticket_fetcher=store.pop),\n run_client(\"127.0.0.1\", session_ticket=client_ticket),\n )\n )\n \n server, response = run(\n asyncio.gather(\n run_server(session_ticket_handler=store.add),\n run_client(\"127.0.0.1\", session_ticket_handler=save_ticket),\n )\n )\n server, response = run(\n asyncio.gather(\n run_server(session_ticket_fetcher=store.pop),\n run_client(\"127.0.0.1\", session_ticket=client_ticket),\n )\n )\n \n at: tests.utils\n run(coro)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n def run_server(**kwargs):\n + return await serve(\n - await serve(\n host=\"::\",\n port=\"4433\",\n certificate=SERVER_CERTIFICATE,\n private_key=SERVER_PRIVATE_KEY,\n stream_handler=handle_stream,\n **kwargs\n )\n \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_sni(self):\n + server, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n - _, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_connection_handler(self):\n server_conn = None\n \n def connection_handler(conn):\n nonlocal server_conn\n server_conn = conn\n \n + server, response = run(\n - _, response = run(\n asyncio.gather(\n run_server(connection_handler=connection_handler),\n run_client(\"127.0.0.1\"),\n )\n )\n self.assertEqual(response, b\"gnip\")\n self.assertIsNotNone(server_conn)\n + server.close()\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n + server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n - _, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 4===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n @patch(\"socket.socket.sendto\", new_callable=lambda: sendto_with_loss)\n def test_connect_and_serve_with_packet_loss(self, mock_sendto):\n \"\"\"\n This test ensures handshake success and stream data is successfully sent\n and received in the presence of packet loss (randomized 25% in each direction).\n \"\"\"\n data = b\"Z\" * 65536\n + server, response = run(\n - _, response = run(\n asyncio.gather(\n run_server(idle_timeout=300.0, stateless_retry=True),\n run_client(\"127.0.0.1\", idle_timeout=300.0, request=data),\n )\n )\n self.assertEqual(response, data)\n + server.close()\n \n===========changed ref 5===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_large(self):\n \"\"\"\n Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA.\n \"\"\"\n data = b\"Z\" * 2097152\n + server, response = run(\n - _, response = run(\n asyncio.gather(run_server(), run_client(\"127.0.0.1\", request=data))\n )\n self.assertEqual(response, data)\n + server.close()\n \n===========changed ref 6===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_writelines(self):\n async def run_client_writelines(host, port=4433, **kwargs):\n async with connect(host, port, **kwargs) as client:\n reader, writer = await client.create_stream()\n assert writer.can_write_eof() is True\n \n writer.writelines([b\"01234567\", b\"89012345\"])\n writer.write_eof()\n \n return await reader.read()\n \n + server, response = run(\n - _, response = run(\n asyncio.gather(run_server(), run_client_writelines(\"127.0.0.1\"))\n )\n self.assertEqual(response, b\"5432109876543210\")\n + server.close()\n "}}},{"rowIdx":2945,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_stateless_retry_bad"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"d0e97265c4150342955cf98fbf453b34391aabe5"},"commit_message":{"kind":"string","value":"[tests] explicitly close server after each test"},"ground_truth":{"kind":"string","value":" <2>: server = run(run_server(stateless_retry=True))\n <3>: run(\n <4>: asyncio.gather(\n <5>: run_server(stateless_retry=True),\n <6>: run(run_client(\"127.0.0.1\", idle_timeout=4.0))\n run_client(\"127.0.0.1\", idle_timeout=4.0),\n <7>: )\n <8>: )\n <9>: server.close()\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n @patch(\"aioquic.asyncio.server.QuicServer._validate_retry_token\")\n def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate):\n <0> mock_validate.side_effect = ValueError(\"Decryption failed.\")\n <1> \n <2> with self.assertRaises(ConnectionError):\n <3> run(\n <4> asyncio.gather(\n <5> run_server(stateless_retry=True),\n <6> run_client(\"127.0.0.1\", idle_timeout=4.0),\n <7> )\n <8> )\n <9> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: asyncio.tasks\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[\n Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]]\n ]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]]\n gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[\n===========unchanged ref 1===========\n at: tests.test_asyncio\n run_client(host, port=4433, request=b\"ping\", *, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds)\n \n run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None)\n \n at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_sni\n server, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n \n at: tests.utils\n run(coro)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n at: unittest.mock\n _patcher(target: Any, new: _T, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[_T]\n _patcher(target: Any, *, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[Union[MagicMock, AsyncMock]]\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n def run_server(**kwargs):\n + return await serve(\n - await serve(\n host=\"::\",\n port=\"4433\",\n certificate=SERVER_CERTIFICATE,\n private_key=SERVER_PRIVATE_KEY,\n stream_handler=handle_stream,\n **kwargs\n )\n \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_stateless_retry(self):\n + server, response = run(\n - _, response = run(\n asyncio.gather(run_server(stateless_retry=True), run_client(\"127.0.0.1\"))\n )\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_sni(self):\n + server, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n - _, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_connection_handler(self):\n server_conn = None\n \n def connection_handler(conn):\n nonlocal server_conn\n server_conn = conn\n \n + server, response = run(\n - _, response = run(\n asyncio.gather(\n run_server(connection_handler=connection_handler),\n run_client(\"127.0.0.1\"),\n )\n )\n self.assertEqual(response, b\"gnip\")\n self.assertIsNotNone(server_conn)\n + server.close()\n \n===========changed ref 4===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n + server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n - _, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 5===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n @patch(\"socket.socket.sendto\", new_callable=lambda: sendto_with_loss)\n def test_connect_and_serve_with_packet_loss(self, mock_sendto):\n \"\"\"\n This test ensures handshake success and stream data is successfully sent\n and received in the presence of packet loss (randomized 25% in each direction).\n \"\"\"\n data = b\"Z\" * 65536\n + server, response = run(\n - _, response = run(\n asyncio.gather(\n run_server(idle_timeout=300.0, stateless_retry=True),\n run_client(\"127.0.0.1\", idle_timeout=300.0, request=data),\n )\n )\n self.assertEqual(response, data)\n + server.close()\n \n===========changed ref 6===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_large(self):\n \"\"\"\n Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA.\n \"\"\"\n data = b\"Z\" * 2097152\n + server, response = run(\n - _, response = run(\n asyncio.gather(run_server(), run_client(\"127.0.0.1\", request=data))\n )\n self.assertEqual(response, data)\n + server.close()\n "}}},{"rowIdx":2946,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_version_negotiation"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"d0e97265c4150342955cf98fbf453b34391aabe5"},"commit_message":{"kind":"string","value":"[tests] explicitly close server after each test"},"ground_truth":{"kind":"string","value":" <0>: server, response = run(\n _, response = run(\n <6>: server.close()\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_version_negotiation(self):\n <0> _, response = run(\n <1> asyncio.gather(\n <2> run_server(), run_client(\"127.0.0.1\", protocol_version=0x1A2A3A4A)\n <3> )\n <4> )\n <5> self.assertEqual(response, b\"gnip\")\n <6> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: tests.test_asyncio\n run_client(host, port=4433, request=b\"ping\", *, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds)\n \n run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None)\n \n at: tests.utils\n run(coro)\n \n at: unittest.case.TestCase\n assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E]\n assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n def run_server(**kwargs):\n + return await serve(\n - await serve(\n host=\"::\",\n port=\"4433\",\n certificate=SERVER_CERTIFICATE,\n private_key=SERVER_PRIVATE_KEY,\n stream_handler=handle_stream,\n **kwargs\n )\n \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_stateless_retry(self):\n + server, response = run(\n - _, response = run(\n asyncio.gather(run_server(stateless_retry=True), run_client(\"127.0.0.1\"))\n )\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_sni(self):\n + server, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n - _, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n @patch(\"aioquic.asyncio.server.QuicServer._validate_retry_token\")\n def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate):\n mock_validate.side_effect = ValueError(\"Decryption failed.\")\n \n + server = run(run_server(stateless_retry=True))\n with self.assertRaises(ConnectionError):\n - run(\n - asyncio.gather(\n - run_server(stateless_retry=True),\n + run(run_client(\"127.0.0.1\", idle_timeout=4.0))\n - run_client(\"127.0.0.1\", idle_timeout=4.0),\n - )\n - )\n + server.close()\n \n===========changed ref 4===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_connection_handler(self):\n server_conn = None\n \n def connection_handler(conn):\n nonlocal server_conn\n server_conn = conn\n \n + server, response = run(\n - _, response = run(\n asyncio.gather(\n run_server(connection_handler=connection_handler),\n run_client(\"127.0.0.1\"),\n )\n )\n self.assertEqual(response, b\"gnip\")\n self.assertIsNotNone(server_conn)\n + server.close()\n \n===========changed ref 5===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n + server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n - _, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 6===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n @patch(\"socket.socket.sendto\", new_callable=lambda: sendto_with_loss)\n def test_connect_and_serve_with_packet_loss(self, mock_sendto):\n \"\"\"\n This test ensures handshake success and stream data is successfully sent\n and received in the presence of packet loss (randomized 25% in each direction).\n \"\"\"\n data = b\"Z\" * 65536\n + server, response = run(\n - _, response = run(\n asyncio.gather(\n run_server(idle_timeout=300.0, stateless_retry=True),\n run_client(\"127.0.0.1\", idle_timeout=300.0, request=data),\n )\n )\n self.assertEqual(response, data)\n + server.close()\n \n===========changed ref 7===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_large(self):\n \"\"\"\n Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA.\n \"\"\"\n data = b\"Z\" * 2097152\n + server, response = run(\n - _, response = run(\n asyncio.gather(run_server(), run_client(\"127.0.0.1\", request=data))\n )\n self.assertEqual(response, data)\n + server.close()\n \n===========changed ref 8===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_writelines(self):\n async def run_client_writelines(host, port=4433, **kwargs):\n async with connect(host, port, **kwargs) as client:\n reader, writer = await client.create_stream()\n assert writer.can_write_eof() is True\n \n writer.writelines([b\"01234567\", b\"89012345\"])\n writer.write_eof()\n \n return await reader.read()\n \n + server, response = run(\n - _, response = run(\n asyncio.gather(run_server(), run_client_writelines(\"127.0.0.1\"))\n )\n self.assertEqual(response, b\"5432109876543210\")\n + server.close()\n \n===========changed ref 9===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_session_ticket(self):\n client_ticket = None\n store = SessionTicketStore()\n \n def save_ticket(t):\n nonlocal client_ticket\n client_ticket = t\n \n # first request\n + server, response = run(\n - _, response = run(\n asyncio.gather(\n run_server(session_ticket_handler=store.add),\n run_client(\"127.0.0.1\", session_ticket_handler=save_ticket),\n )\n )\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n self.assertIsNotNone(client_ticket)\n \n # second request\n + server, response = run(\n - _, response = run(\n asyncio.gather(\n run_server(session_ticket_fetcher=store.pop),\n run_client(\"127.0.0.1\", session_ticket=client_ticket),\n )\n )\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 10===========\n # module: aioquic.asyncio.server\n class QuicServer(asyncio.DatagramProtocol):\n + def close(self):\n + for protocol in set(self._protocols.values()):\n + protocol.close()\n + self._protocols.clear()\n + self._transport.close()\n + "}}},{"rowIdx":2947,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_change_connection_id"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"d0e97265c4150342955cf98fbf453b34391aabe5"},"commit_message":{"kind":"string","value":"[tests] explicitly close server after each test"},"ground_truth":{"kind":"string","value":" <6>: server, _ = run(\n run(\n<11>: server.close()\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_change_connection_id(self):\n <0> async def run_client_key_update(host, **kwargs):\n <1> async with connect(host, 4433, **kwargs) as client:\n <2> await client.ping()\n <3> client.change_connection_id()\n <4> await client.ping()\n <5> \n <6> run(\n <7> asyncio.gather(\n <8> run_server(stateless_retry=False), run_client_key_update(\"127.0.0.1\")\n <9> )\n<10> )\n<11> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.asyncio.client\n connect(*args, **kwds)\n connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None]\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol\n change_connection_id() -> None\n \n ping() -> None\n \n at: tests.test_asyncio\n run_client(host, port=4433, request=b\"ping\", *, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds)\n \n at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_version_negotiation\n server, response = run(\n asyncio.gather(\n run_server(), run_client(\"127.0.0.1\", protocol_version=0x1A2A3A4A)\n )\n )\n \n server, response = run(\n asyncio.gather(\n run_server(), run_client(\"127.0.0.1\", protocol_version=0x1A2A3A4A)\n )\n )\n \n at: tests.utils\n run(coro)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========unchanged ref 1===========\n assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E]\n assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_version_negotiation(self):\n + server, response = run(\n - _, response = run(\n asyncio.gather(\n run_server(), run_client(\"127.0.0.1\", protocol_version=0x1A2A3A4A)\n )\n )\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_stateless_retry(self):\n + server, response = run(\n - _, response = run(\n asyncio.gather(run_server(stateless_retry=True), run_client(\"127.0.0.1\"))\n )\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_sni(self):\n + server, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n - _, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n @patch(\"aioquic.asyncio.server.QuicServer._validate_retry_token\")\n def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate):\n mock_validate.side_effect = ValueError(\"Decryption failed.\")\n \n + server = run(run_server(stateless_retry=True))\n with self.assertRaises(ConnectionError):\n - run(\n - asyncio.gather(\n - run_server(stateless_retry=True),\n + run(run_client(\"127.0.0.1\", idle_timeout=4.0))\n - run_client(\"127.0.0.1\", idle_timeout=4.0),\n - )\n - )\n + server.close()\n \n===========changed ref 4===========\n # module: tests.test_asyncio\n def run_server(**kwargs):\n + return await serve(\n - await serve(\n host=\"::\",\n port=\"4433\",\n certificate=SERVER_CERTIFICATE,\n private_key=SERVER_PRIVATE_KEY,\n stream_handler=handle_stream,\n **kwargs\n )\n \n===========changed ref 5===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_connection_handler(self):\n server_conn = None\n \n def connection_handler(conn):\n nonlocal server_conn\n server_conn = conn\n \n + server, response = run(\n - _, response = run(\n asyncio.gather(\n run_server(connection_handler=connection_handler),\n run_client(\"127.0.0.1\"),\n )\n )\n self.assertEqual(response, b\"gnip\")\n self.assertIsNotNone(server_conn)\n + server.close()\n \n===========changed ref 6===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n + server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n - _, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 7===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n @patch(\"socket.socket.sendto\", new_callable=lambda: sendto_with_loss)\n def test_connect_and_serve_with_packet_loss(self, mock_sendto):\n \"\"\"\n This test ensures handshake success and stream data is successfully sent\n and received in the presence of packet loss (randomized 25% in each direction).\n \"\"\"\n data = b\"Z\" * 65536\n + server, response = run(\n - _, response = run(\n asyncio.gather(\n run_server(idle_timeout=300.0, stateless_retry=True),\n run_client(\"127.0.0.1\", idle_timeout=300.0, request=data),\n )\n )\n self.assertEqual(response, data)\n + server.close()\n \n===========changed ref 8===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_large(self):\n \"\"\"\n Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA.\n \"\"\"\n data = b\"Z\" * 2097152\n + server, response = run(\n - _, response = run(\n asyncio.gather(run_server(), run_client(\"127.0.0.1\", request=data))\n )\n self.assertEqual(response, data)\n + server.close()\n \n===========changed ref 9===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_writelines(self):\n async def run_client_writelines(host, port=4433, **kwargs):\n async with connect(host, port, **kwargs) as client:\n reader, writer = await client.create_stream()\n assert writer.can_write_eof() is True\n \n writer.writelines([b\"01234567\", b\"89012345\"])\n writer.write_eof()\n \n return await reader.read()\n \n + server, response = run(\n - _, response = run(\n asyncio.gather(run_server(), run_client_writelines(\"127.0.0.1\"))\n )\n self.assertEqual(response, b\"5432109876543210\")\n + server.close()\n "}}},{"rowIdx":2948,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_key_update"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"d0e97265c4150342955cf98fbf453b34391aabe5"},"commit_message":{"kind":"string","value":"[tests] explicitly close server after each test"},"ground_truth":{"kind":"string","value":" <6>: server, _ = run(\n run(\n<11>: server.close()\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_key_update(self):\n <0> async def run_client_key_update(host, **kwargs):\n <1> async with connect(host, 4433, **kwargs) as client:\n <2> await client.ping()\n <3> client.request_key_update()\n <4> await client.ping()\n <5> \n <6> run(\n <7> asyncio.gather(\n <8> run_server(stateless_retry=False), run_client_key_update(\"127.0.0.1\")\n <9> )\n<10> )\n<11> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.asyncio.client\n connect(*args, **kwds)\n connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None]\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol\n ping() -> None\n \n \n===========unchanged ref 1===========\n at: asyncio.tasks\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[\n Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]]\n ]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]]\n gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[\n===========unchanged ref 2===========\n at: tests.test_asyncio\n run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None)\n \n at: tests.test_asyncio.HighLevelTest.test_change_connection_id\n run_client_key_update(host, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds)\n \n at: tests.utils\n run(coro)\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n def run_server(**kwargs):\n + return await serve(\n - await serve(\n host=\"::\",\n port=\"4433\",\n certificate=SERVER_CERTIFICATE,\n private_key=SERVER_PRIVATE_KEY,\n stream_handler=handle_stream,\n **kwargs\n )\n \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_version_negotiation(self):\n + server, response = run(\n - _, response = run(\n asyncio.gather(\n run_server(), run_client(\"127.0.0.1\", protocol_version=0x1A2A3A4A)\n )\n )\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_stateless_retry(self):\n + server, response = run(\n - _, response = run(\n asyncio.gather(run_server(stateless_retry=True), run_client(\"127.0.0.1\"))\n )\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_sni(self):\n + server, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n - _, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 4===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_change_connection_id(self):\n async def run_client_key_update(host, **kwargs):\n async with connect(host, 4433, **kwargs) as client:\n await client.ping()\n client.change_connection_id()\n await client.ping()\n \n + server, _ = run(\n - run(\n asyncio.gather(\n run_server(stateless_retry=False), run_client_key_update(\"127.0.0.1\")\n )\n )\n + server.close()\n \n===========changed ref 5===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n @patch(\"aioquic.asyncio.server.QuicServer._validate_retry_token\")\n def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate):\n mock_validate.side_effect = ValueError(\"Decryption failed.\")\n \n + server = run(run_server(stateless_retry=True))\n with self.assertRaises(ConnectionError):\n - run(\n - asyncio.gather(\n - run_server(stateless_retry=True),\n + run(run_client(\"127.0.0.1\", idle_timeout=4.0))\n - run_client(\"127.0.0.1\", idle_timeout=4.0),\n - )\n - )\n + server.close()\n \n===========changed ref 6===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_connection_handler(self):\n server_conn = None\n \n def connection_handler(conn):\n nonlocal server_conn\n server_conn = conn\n \n + server, response = run(\n - _, response = run(\n asyncio.gather(\n run_server(connection_handler=connection_handler),\n run_client(\"127.0.0.1\"),\n )\n )\n self.assertEqual(response, b\"gnip\")\n self.assertIsNotNone(server_conn)\n + server.close()\n \n===========changed ref 7===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n + server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n - _, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n self.assertEqual(response, b\"gnip\")\n + server.close()\n "}}},{"rowIdx":2949,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_ping"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"d0e97265c4150342955cf98fbf453b34391aabe5"},"commit_message":{"kind":"string","value":"[tests] explicitly close server after each test"},"ground_truth":{"kind":"string","value":" <5>: server, _ = run(\n run(\n<10>: server.close()\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_ping(self):\n <0> async def run_client_ping(host, **kwargs):\n <1> async with connect(host, 4433, **kwargs) as client:\n <2> await client.ping()\n <3> await client.ping()\n <4> \n <5> run(\n <6> asyncio.gather(\n <7> run_server(stateless_retry=False), run_client_ping(\"127.0.0.1\")\n <8> )\n <9> )\n<10> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.asyncio.protocol.QuicConnectionProtocol\n ping() -> None\n \n \n===========unchanged ref 1===========\n at: asyncio.tasks\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[\n Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]]\n ]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]]\n gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[\n===========unchanged ref 2===========\n at: tests.test_asyncio\n run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None)\n \n at: tests.test_asyncio.HighLevelTest.test_key_update\n run_client_key_update(host, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds)\n \n at: tests.utils\n run(coro)\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n def run_server(**kwargs):\n + return await serve(\n - await serve(\n host=\"::\",\n port=\"4433\",\n certificate=SERVER_CERTIFICATE,\n private_key=SERVER_PRIVATE_KEY,\n stream_handler=handle_stream,\n **kwargs\n )\n \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_version_negotiation(self):\n + server, response = run(\n - _, response = run(\n asyncio.gather(\n run_server(), run_client(\"127.0.0.1\", protocol_version=0x1A2A3A4A)\n )\n )\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_key_update(self):\n async def run_client_key_update(host, **kwargs):\n async with connect(host, 4433, **kwargs) as client:\n await client.ping()\n client.request_key_update()\n await client.ping()\n \n + server, _ = run(\n - run(\n asyncio.gather(\n run_server(stateless_retry=False), run_client_key_update(\"127.0.0.1\")\n )\n )\n + server.close()\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_stateless_retry(self):\n + server, response = run(\n - _, response = run(\n asyncio.gather(run_server(stateless_retry=True), run_client(\"127.0.0.1\"))\n )\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 4===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_sni(self):\n + server, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n - _, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n self.assertEqual(response, b\"gnip\")\n + server.close()\n \n===========changed ref 5===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_change_connection_id(self):\n async def run_client_key_update(host, **kwargs):\n async with connect(host, 4433, **kwargs) as client:\n await client.ping()\n client.change_connection_id()\n await client.ping()\n \n + server, _ = run(\n - run(\n asyncio.gather(\n run_server(stateless_retry=False), run_client_key_update(\"127.0.0.1\")\n )\n )\n + server.close()\n \n===========changed ref 6===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n @patch(\"aioquic.asyncio.server.QuicServer._validate_retry_token\")\n def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate):\n mock_validate.side_effect = ValueError(\"Decryption failed.\")\n \n + server = run(run_server(stateless_retry=True))\n with self.assertRaises(ConnectionError):\n - run(\n - asyncio.gather(\n - run_server(stateless_retry=True),\n + run(run_client(\"127.0.0.1\", idle_timeout=4.0))\n - run_client(\"127.0.0.1\", idle_timeout=4.0),\n - )\n - )\n + server.close()\n \n===========changed ref 7===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_connection_handler(self):\n server_conn = None\n \n def connection_handler(conn):\n nonlocal server_conn\n server_conn = conn\n \n + server, response = run(\n - _, response = run(\n asyncio.gather(\n run_server(connection_handler=connection_handler),\n run_client(\"127.0.0.1\"),\n )\n )\n self.assertEqual(response, b\"gnip\")\n self.assertIsNotNone(server_conn)\n + server.close()\n \n===========changed ref 8===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n + server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n - _, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n self.assertEqual(response, b\"gnip\")\n + server.close()\n "}}},{"rowIdx":2950,"cells":{"path":{"kind":"string","value":"aioquic.asyncio.server/QuicServer.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1554b7e67d62b9da9debf4b8e66015fb9c7e9386"},"commit_message":{"kind":"string","value":"[server] move stateless retry token handling"},"ground_truth":{"kind":"string","value":"<15>: self._retry_key = rsa.generate_private_key(\n<16>: public_exponent=65537, key_size=1024, backend=default_backend()\n<17>: )\n<18>: self._retry = QuicRetryTokenHandler()\n<19>: self._retry = None\n self._retry_key = None\n"},"main_code":{"kind":"string","value":" ic.asyncio.server\n class QuicServer(asyncio.DatagramProtocol):\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n connection_handler: Optional[QuicConnectionHandler] = None,\n session_ticket_fetcher: Optional[SessionTicketFetcher] = None,\n session_ticket_handler: Optional[SessionTicketHandler] = None,\n stateless_retry: bool = False,\n stream_handler: Optional[QuicStreamHandler] = None,\n ) -> None:\n <0> self._configuration = configuration\n <1> self._protocols: Dict[bytes, QuicConnectionProtocol] = {}\n <2> self._loop = asyncio.get_event_loop()\n <3> self._session_ticket_fetcher = session_ticket_fetcher\n <4> self._session_ticket_handler = session_ticket_handler\n <5> self._transport: Optional[asyncio.DatagramTransport] = None\n <6> \n <7> if connection_handler is not None:\n <8> self._connection_handler = connection_handler\n <9> else:\n<10> self._connection_handler = lambda c: None\n<11> \n<12> self._stream_handler = stream_handler\n<13> \n<14> if stateless_retry:\n<15> self._retry_key = rsa.generate_private_key(\n<16> public_exponent=65537, key_size=1024, backend=default_backend()\n<17> )\n<18> else:\n<19> self._retry_key = None\n<20> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: _asyncio\n get_event_loop()\n \n at: aioquic.asyncio.protocol\n QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None]\n \n QuicConnectionProtocol(connection: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None)\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol\n close() -> None\n \n at: aioquic.retry\n QuicRetryTokenHandler()\n \n at: asyncio.events\n get_event_loop() -> AbstractEventLoop\n \n at: asyncio.protocols.BaseProtocol\n __slots__ = ()\n \n connection_made(self, transport: transports.BaseTransport) -> None\n \n at: asyncio.transports\n BaseTransport(extra: Optional[Mapping[Any, Any]]=...)\n \n DatagramTransport(extra: Optional[Mapping[Any, Any]]=...)\n \n at: asyncio.transports.BaseTransport\n __slots__ = ('_extra',)\n \n close() -> None\n \n at: typing\n cast(typ: Type[_T], val: Any) -> _T\n cast(typ: str, val: Any) -> Any\n cast(typ: object, val: Any) -> Any\n \n Dict = _alias(dict, 2, inst=False, name='Dict')\n \n \n===========changed ref 0===========\n # module: aioquic.asyncio.server\n - def encode_address(addr: NetworkAddress) -> bytes:\n - return ipaddress.ip_address(addr[0]).packed + bytes([addr[1] >> 8, addr[1] & 0xFF])\n - \n===========changed ref 1===========\n + # module: aioquic.retry\n + \n + \n===========changed ref 2===========\n + # module: aioquic.retry\n + def encode_address(addr: NetworkAddress) -> bytes:\n + return ipaddress.ip_address(addr[0]).packed + bytes([addr[1] >> 8, addr[1] & 0xFF])\n + \n===========changed ref 3===========\n + # module: aioquic.retry\n + class QuicRetryTokenHandler:\n + def __init__(self) -> None:\n + self._key = rsa.generate_private_key(\n + public_exponent=65537, key_size=1024, backend=default_backend()\n + )\n + \n===========changed ref 4===========\n + # module: aioquic.retry\n + class QuicRetryTokenHandler:\n + def create_token(self, addr: NetworkAddress, destination_cid: bytes) -> bytes:\n + retry_message = encode_address(addr) + b\"|\" + destination_cid\n + return self._key.public_key().encrypt(\n + retry_message,\n + padding.OAEP(\n + mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None\n + ),\n + )\n + \n===========changed ref 5===========\n + # module: aioquic.retry\n + class QuicRetryTokenHandler:\n + def validate_token(self, addr: NetworkAddress, token: bytes) -> bytes:\n + retry_message = self._key.decrypt(\n + token,\n + padding.OAEP(\n + mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None\n + ),\n + )\n + encoded_addr, original_connection_id = retry_message.split(b\"|\", maxsplit=1)\n + if encoded_addr != encode_address(addr):\n + raise ValueError(\"Remote address does not match.\")\n + return original_connection_id\n + "}}},{"rowIdx":2951,"cells":{"path":{"kind":"string","value":"aioquic.asyncio.server/QuicServer.datagram_received"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1554b7e67d62b9da9debf4b8e66015fb9c7e9386"},"commit_message":{"kind":"string","value":"[server] move stateless retry token handling"},"ground_truth":{"kind":"string","value":"<23>: if self._retry is not None:\n if self._retry_key is not None:\n<32>: retry_token=self._retry.create_token(\n retry_token=self._create_retry_token(\n<42>: original_connection_id = self._retry.validate_token(\n original_connection_id = self._validate_retry_token(\n"},"main_code":{"kind":"string","value":" # module: aioquic.asyncio.server\n class QuicServer(asyncio.DatagramProtocol):\n def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None:\n <0> data = cast(bytes, data)\n <1> buf = Buffer(data=data)\n <2> header = pull_quic_header(buf, host_cid_length=8)\n <3> \n <4> # version negotiation\n <5> if (\n <6> header.version is not None\n <7> and header.version not in self._configuration.supported_versions\n <8> ):\n <9> self._transport.sendto(\n<10> encode_quic_version_negotiation(\n<11> source_cid=header.destination_cid,\n<12> destination_cid=header.source_cid,\n<13> supported_versions=self._configuration.supported_versions,\n<14> ),\n<15> addr,\n<16> )\n<17> return\n<18> \n<19> protocol = self._protocols.get(header.destination_cid, None)\n<20> original_connection_id: Optional[bytes] = None\n<21> if protocol is None and header.packet_type == PACKET_TYPE_INITIAL:\n<22> # stateless retry\n<23> if self._retry_key is not None:\n<24> if not header.token:\n<25> # create a retry token\n<26> self._transport.sendto(\n<27> encode_quic_retry(\n<28> version=header.version,\n<29> source_cid=os.urandom(8),\n<30> destination_cid=header.source_cid,\n<31> original_destination_cid=header.destination_cid,\n<32> retry_token=self._create_retry_token(\n<33> addr, header.destination_cid\n<34> ),\n<35> ),\n<36> addr,\n<37> )\n<38> return\n<39> else:\n<40> # validate retry token\n<41> try:\n<42> original_connection_id = self._validate_retry_token(\n<43> addr, header.token\n<44> )\n<45> except ValueError:\n<46> return\n<47> \n<48> # create new connection\n<49> connection = QuicConnection(\n<50> "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.asyncio.server\n class QuicServer(asyncio.DatagramProtocol):\n def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None:\n # offset: 1\n original_connection_id=original_connection_id,\n session_ticket_fetcher=self._session_ticket_fetcher,\n session_ticket_handler=self._session_ticket_handler,\n )\n protocol = QuicConnectionProtocol(\n connection, stream_handler=self._stream_handler\n )\n protocol._connection_id_issued_handler = partial(\n self._connection_id_issued, protocol=protocol\n )\n protocol._connection_id_retired_handler = partial(\n self._connection_id_retired, protocol=protocol\n )\n \n self._protocols[header.destination_cid] = protocol\n protocol.connection_made(self._transport)\n \n self._protocols[connection.host_cid] = protocol\n self._connection_handler(protocol)\n \n if protocol is not None:\n protocol.datagram_received(data, addr)\n \n \n===========unchanged ref 0===========\n at: aioquic.asyncio.protocol\n QuicConnectionProtocol(connection: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None)\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol\n connection_made(transport: asyncio.BaseTransport) -> None\n \n datagram_received(data: Union[bytes, Text], addr: NetworkAddress) -> None\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__\n self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None\n \n self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None\n \n at: aioquic.asyncio.server.QuicServer.__init__\n self._configuration = configuration\n \n self._protocols: Dict[bytes, QuicConnectionProtocol] = {}\n \n self._session_ticket_fetcher = session_ticket_fetcher\n \n self._session_ticket_handler = session_ticket_handler\n \n self._transport: Optional[asyncio.DatagramTransport] = None\n \n self._connection_handler = connection_handler\n self._connection_handler = lambda c: None\n \n self._stream_handler = stream_handler\n \n self._retry = QuicRetryTokenHandler()\n self._retry = None\n \n at: aioquic.asyncio.server.QuicServer.connection_made\n self._transport = cast(asyncio.DatagramTransport, transport)\n \n at: aioquic.asyncio.server.QuicServer.datagram_received\n data = cast(bytes, data)\n \n header = pull_quic_header(buf, host_cid_length=8)\n \n at: aioquic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n certificate: Any = None\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n private_key: Any = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n \n===========unchanged ref 1===========\n session_ticket: Optional[tls.SessionTicket] = None\n \n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_19,\n QuicProtocolVersion.DRAFT_20,\n ]\n )\n \n at: aioquic.connection\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.connection.QuicConnection.__init__\n self.host_cid = self._host_cids[0].cid\n \n at: aioquic.connection.QuicConnection.receive_datagram\n self.host_cid = context.host_cid\n \n at: aioquic.packet\n PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00\n \n encode_quic_retry(version: int, source_cid: bytes, destination_cid: bytes, original_destination_cid: bytes, retry_token: bytes) -> bytes\n \n encode_quic_version_negotiation(source_cid: bytes, destination_cid: bytes, supported_versions: List[QuicProtocolVersion]) -> bytes\n \n at: aioquic.packet.QuicHeader\n is_long_header: bool\n \n version: Optional[int]\n \n packet_type: int\n \n destination_cid: bytes\n \n source_cid: bytes\n \n original_destination_cid: bytes = b\"\"\n \n token: bytes = b\"\"\n \n rest_length: int = 0\n \n at: aioquic.retry.QuicRetryTokenHandler\n create_token(addr: NetworkAddress, destination_cid: bytes) -> bytes\n \n validate_token(addr: NetworkAddress, token: bytes) -> bytes\n \n at: asyncio.transports.DatagramTransport\n __slots__ = ()\n \n sendto(data: Any, addr: Optional[_Address]=...) -> None\n \n \n===========unchanged ref 2===========\n at: functools\n partial(func: Callable[..., _T], *args: Any, **kwargs: Any)\n partial(func, *args, **keywords, /) -> function with partial application()\n \n at: os\n urandom(size: int, /) -> bytes\n \n at: typing.Mapping\n get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]\n get(key: _KT) -> Optional[_VT_co]\n \n \n===========changed ref 0===========\n + # module: aioquic.retry\n + class QuicRetryTokenHandler:\n + def create_token(self, addr: NetworkAddress, destination_cid: bytes) -> bytes:\n + retry_message = encode_address(addr) + b\"|\" + destination_cid\n + return self._key.public_key().encrypt(\n + retry_message,\n + padding.OAEP(\n + mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None\n + ),\n + )\n + \n===========changed ref 1===========\n + # module: aioquic.retry\n + class QuicRetryTokenHandler:\n + def validate_token(self, addr: NetworkAddress, token: bytes) -> bytes:\n + retry_message = self._key.decrypt(\n + token,\n + padding.OAEP(\n + mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None\n + ),\n + )\n + encoded_addr, original_connection_id = retry_message.split(b\"|\", maxsplit=1)\n + if encoded_addr != encode_address(addr):\n + raise ValueError(\"Remote address does not match.\")\n + return original_connection_id\n + \n===========changed ref 2===========\n # module: aioquic.asyncio.server\n - def encode_address(addr: NetworkAddress) -> bytes:\n - return ipaddress.ip_address(addr[0]).packed + bytes([addr[1] >> 8, addr[1] & 0xFF])\n - "}}},{"rowIdx":2952,"cells":{"path":{"kind":"string","value":"aioquic.h3.connection/H3Connection.handle_events"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"4e81cee943d038678d2941fc6ff9fb1f685207f2"},"commit_message":{"kind":"string","value":"[examples] add an HTTP/3 server example"},"ground_truth":{"kind":"string","value":" <8>: if isinstance(event, aioquic.events.StreamDataReceived):\n <9>: http_events.extend(\n<10>: self._receive_stream_data(\n<11>: event.stream_id, event.data, event.end_stream\n<12>: )\n<13>: )\n<14>: \n<15>: http_events.extend(self.handle_event(event))\n"},"main_code":{"kind":"string","value":" # module: aioquic.h3.connection\n class H3Connection:\n def handle_events(self) -> List[Event]:\n <0> \"\"\"\n <1> Handle events from the QUIC connection and return HTTP events.\n <2> \"\"\"\n <3> http_events: List[Event] = []\n <4> \n <5> # process QUIC events\n <6> event = self._quic.next_event()\n <7> while event is not None:\n <8> if isinstance(event, aioquic.events.StreamDataReceived):\n <9> http_events.extend(\n<10> self._receive_stream_data(\n<11> event.stream_id, event.data, event.end_stream\n<12> )\n<13> )\n<14> \n<15> event = self._quic.next_event()\n<16> \n<17> return http_events\n<18> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.events\n Event()\n \n StreamDataReceived(data: bytes, end_stream: bool, stream_id: int)\n \n at: aioquic.h3.connection.H3Connection\n _receive_stream_data(stream_id: int, data: bytes, stream_ended: bool) -> List[Event]\n \n at: aioquic.h3.events\n Event()\n \n at: typing\n List = _alias(list, 1, inst=False, name='List')\n \n \n===========changed ref 0===========\n # module: aioquic.h3.connection\n class H3Connection:\n + def handle_event(self, event: aioquic.events.Event) -> List[Event]:\n + \"\"\"\n + Handle a QUIC event and return a list of HTTP events.\n + \"\"\"\n + http_events: List[Event] = []\n + \n + if isinstance(event, aioquic.events.StreamDataReceived):\n + http_events.extend(\n + self._receive_stream_data(event.stream_id, event.data, event.end_stream)\n + )\n + \n + return http_events\n + "}}},{"rowIdx":2953,"cells":{"path":{"kind":"string","value":"examples.http3-client/run"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"d5ea72874a9ee815f9242f193a0432d31bb92873"},"commit_message":{"kind":"string","value":"[examples] add arguments for SSL log and session ticket to H3 client"},"ground_truth":{"kind":"string","value":"<17>: alpn_protocols=[\"h3-20\"],\n<18>: is_client=True,\n<19>: secrets_log_file=open(\"/tmp/ssl.log\", \"w\"),\n<20>: server_name=server_name,\n<21>: alpn_protocols=[\"h3-20\"], is_client=True, server_name=server_name, **kwargs\n ),\n )\n<22>: session_ticket_handler=save_session_ticket,\n"},"main_code":{"kind":"string","value":" # module: examples.http3-client\n + def run(url: str, **kwargs) -> None:\n - def run(url: str) -> None:\n <0> # parse URL\n <1> parsed = urlparse(url)\n <2> assert parsed.scheme == \"https\", \"Only HTTPS URLs are supported.\"\n <3> if \":\" in parsed.netloc:\n <4> server_name, port_str = parsed.netloc.split(\":\")\n <5> port = int(port_str)\n <6> else:\n <7> server_name = parsed.netloc\n <8> port = 443\n <9> \n<10> # prepare socket\n<11> server_addr = (socket.gethostbyname(server_name), port)\n<12> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n<13> \n<14> # prepare QUIC connection\n<15> quic = QuicConnection(\n<16> configuration=QuicConfiguration(\n<17> alpn_protocols=[\"h3-20\"],\n<18> is_client=True,\n<19> secrets_log_file=open(\"/tmp/ssl.log\", \"w\"),\n<20> server_name=server_name,\n<21> )\n<22> )\n<23> quic.connect(server_addr, now=time.time())\n<24> \n<25> # send request\n<26> http = H3Connection(quic)\n<27> stream_id = quic.get_next_available_stream_id()\n<28> http.send_headers(\n<29> stream_id=stream_id,\n<30> headers=[\n<31> (b\":method\", b\"GET\"),\n<32> (b\":scheme\", parsed.scheme.encode(\"utf8\")),\n<33> (b\":authority\", parsed.netloc.encode(\"utf8\")),\n<34> (b\":path\", parsed.path.encode(\"utf8\")),\n<35> ],\n<36> )\n<37> http.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n<38> for data, addr in quic.datagrams_to_send(now=time.time()):\n<39> sock.sendto(data, addr)\n<40> \n<41> "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: examples.http3-client\n + def run(url: str, **kwargs) -> None:\n - def run(url: str) -> None:\n # offset: 1\n stream_ended = False\n while not stream_ended:\n data, addr = sock.recvfrom(2048)\n quic.receive_datagram(data, addr, now=time.time())\n for event in http.handle_events():\n print(event)\n if isinstance(event, (DataReceived, ResponseReceived)):\n stream_ended = event.stream_ended\n \n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n \n===========unchanged ref 0===========\n at: _pickle\n dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None)\n \n at: aioquic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_19,\n QuicProtocolVersion.DRAFT_20,\n ]\n ))\n \n at: aioquic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n certificate: Any = None\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n private_key: Any = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[tls.SessionTicket] = None\n \n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_19,\n QuicProtocolVersion.DRAFT_20,\n ]\n )\n \n at: aioquic.connection\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.connection.QuicConnection\n connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None\n \n datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]]\n \n get_next_available_stream_id(is_unidirectional=False) -> int\n \n \n===========unchanged ref 1===========\n at: aioquic.h3.connection\n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection\n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: Headers) -> None\n \n at: examples.http3-client\n logger = logging.getLogger(\"client\")\n \n args = parser.parse_args()\n \n at: logging.Logger\n info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None\n \n at: pickle\n dump, dumps, load, loads = _dump, _dumps, _load, _loads\n \n at: socket\n AF_INET: AddressFamily\n \n SOCK_DGRAM: SocketKind\n \n socket(family: int=..., type: int=..., proto: int=..., fileno: Optional[int]=...)\n \n gethostbyname(hostname: str) -> str\n \n at: socket.socket\n family: int\n \n type: int\n \n proto: int\n \n sendto(data: bytes, address: _Address) -> int\n sendto(data: bytes, flags: int, address: _Address) -> int\n \n at: time\n time() -> float\n \n at: urllib.parse\n urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult\n urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes\n \n \n===========changed ref 0===========\n # module: examples.http3-client\n + logger = logging.getLogger(\"client\")\n - logger = logging.getLogger(\"http3\")\n "}}},{"rowIdx":2954,"cells":{"path":{"kind":"string","value":"aioquic.recovery/QuicPacketRecovery.detect_loss"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1f5f5f510801ad377240a1508a6ef7f12fbda3da"},"commit_message":{"kind":"string","value":"[recovery] add QuicPacketRecovery.on_packet_lost"},"ground_truth":{"kind":"string","value":"<11>: lost_bytes = 0\n<28>: del space.sent_packets[packet.packet_number]\n<29>: if packet.is_ack_eliciting:\n<30>: space.ack_eliciting_in_flight -= 1\n<31>: if packet.is_crypto_packet:\n<32>: space.crypto_packet_in_flight -= 1\n<33>: self.on_packet_lost(packet, space)\n<34>: lost_bytes += packet.sent_bytes\n<37>: # trigger callbacks\n<38>: for handler, args in packet.delivery_handlers:\n<39>: handler(QuicDeliveryState.LOST, *args)\n<40>: if lost_largest_time is not None:\n self.on_packets_lost(lost_largest_time, now=now)\n<41>: if lost_bytes:\n<42>: self.\n"},"main_code":{"kind":"string","value":" # module: aioquic.recovery\n class QuicPacketRecovery:\n def detect_loss(self, space: QuicPacketSpace, now: float) -> None:\n <0> \"\"\"\n <1> Check whether any packets should be declared lost.\n <2> \"\"\"\n <3> loss_delay = K_TIME_THRESHOLD * (\n <4> max(self._rtt_latest, self._rtt_smoothed)\n <5> if self._rtt_initialized\n <6> else K_INITIAL_RTT\n <7> )\n <8> packet_threshold = space.largest_acked_packet - K_PACKET_THRESHOLD\n <9> time_threshold = now - loss_delay\n<10> \n<11> lost_bytes = 0\n<12> lost_largest_time = None\n<13> lost_packets = []\n<14> space.loss_time = None\n<15> for packet_number, packet in space.sent_packets.items():\n<16> if packet_number > space.largest_acked_packet:\n<17> break\n<18> \n<19> if packet_number <= packet_threshold or packet.sent_time <= time_threshold:\n<20> lost_packets.append(packet)\n<21> else:\n<22> packet_loss_time = packet.sent_time + loss_delay\n<23> if space.loss_time is None or space.loss_time > packet_loss_time:\n<24> space.loss_time = packet_loss_time\n<25> \n<26> for packet in lost_packets:\n<27> # remove packet and update counters\n<28> del space.sent_packets[packet.packet_number]\n<29> if packet.is_ack_eliciting:\n<30> space.ack_eliciting_in_flight -= 1\n<31> if packet.is_crypto_packet:\n<32> space.crypto_packet_in_flight -= 1\n<33> if packet.in_flight:\n<34> lost_bytes += packet.sent_bytes\n<35> lost_largest_time = packet.sent_time\n<36> \n<37> # trigger callbacks\n<38> for handler, args in packet.delivery_handlers:\n<39> handler(QuicDeliveryState.LOST, *args)\n<40> \n<41> if lost_bytes:\n<42> self."},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def detect_loss(self, space: QuicPacketSpace, now: float) -> None:\n # offset: 1\n \n \n===========unchanged ref 0===========\n at: aioquic.packet_builder.QuicSentPacket\n epoch: Epoch\n \n in_flight: bool\n \n is_ack_eliciting: bool\n \n is_crypto_packet: bool\n \n packet_number: int\n \n sent_time: Optional[float] = None\n \n sent_bytes: int = 0\n \n delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(\n default_factory=list\n )\n \n at: aioquic.recovery\n K_PACKET_THRESHOLD = 3\n \n K_INITIAL_RTT = 0.5 # seconds\n \n K_TIME_THRESHOLD = 9 / 8\n \n QuicPacketSpace()\n \n at: aioquic.recovery.QuicPacketRecovery\n on_packet_expired(packet: QuicSentPacket) -> None\n on_packet_expired(self, packet: QuicSentPacket) -> None\n \n on_packet_lost(packet: QuicSentPacket, space: QuicPacketSpace) -> None\n \n on_packets_lost(lost_largest_time: float, now: float) -> None\n \n at: aioquic.recovery.QuicPacketRecovery.__init__\n self.spaces: List[QuicPacketSpace] = []\n \n self._rtt_initialized = False\n \n self._rtt_latest = 0.0\n \n self._rtt_smoothed = 0.0\n \n at: aioquic.recovery.QuicPacketRecovery.on_ack_received\n self._rtt_latest = max(latest_rtt, 0.001)\n self._rtt_latest -= ack_delay\n \n self._rtt_initialized = True\n \n self._rtt_smoothed = latest_rtt\n self._rtt_smoothed = (\n 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest\n )\n \n at: aioquic.recovery.QuicPacketSpace.__init__\n self.ack_at: Optional[float] = None\n \n self.largest_acked_packet = 0\n \n \n===========unchanged ref 1===========\n self.loss_time: Optional[float] = None\n \n self.sent_packets: Dict[int, QuicSentPacket] = {}\n \n "}}},{"rowIdx":2955,"cells":{"path":{"kind":"string","value":"aioquic.recovery/QuicPacketRecovery.on_loss_detection_timeout"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1f5f5f510801ad377240a1508a6ef7f12fbda3da"},"commit_message":{"kind":"string","value":"[recovery] add QuicPacketRecovery.on_packet_lost"},"ground_truth":{"kind":"string","value":"<10>: del space.sent_packets[packet_number]\n<11>: space.ack_eliciting_in_flight -= 1\n<12>: space.crypto_packet_in_flight -= 1\n<13>: if packet.in_flight:\n<14>: self.bytes_in_flight -= packet.sent_bytes\n<15>: \n<16>: # trigger callbacks\n<17>: for handler, args in packet.delivery_handlers:\n<18>: handler(QuicDeliveryState.LOST, *args)\n<19>: self.on_packet_lost(packet, space)\n"},"main_code":{"kind":"string","value":" # module: aioquic.recovery\n class QuicPacketRecovery:\n def on_loss_detection_timeout(self, now: float) -> None:\n <0> loss_space = self.get_earliest_loss_time()\n <1> if loss_space is not None:\n <2> self.detect_loss(loss_space, now=now)\n <3> elif sum(space.crypto_packet_in_flight for space in self.spaces):\n <4> # reschedule crypto packets\n <5> for space in self.spaces:\n <6> for packet_number, packet in list(\n <7> filter(lambda i: i[1].is_crypto_packet, space.sent_packets.items())\n <8> ):\n <9> # remove packet and update counters\n<10> del space.sent_packets[packet_number]\n<11> space.ack_eliciting_in_flight -= 1\n<12> space.crypto_packet_in_flight -= 1\n<13> if packet.in_flight:\n<14> self.bytes_in_flight -= packet.sent_bytes\n<15> \n<16> # trigger callbacks\n<17> for handler, args in packet.delivery_handlers:\n<18> handler(QuicDeliveryState.LOST, *args)\n<19> self._crypto_count += 1\n<20> else:\n<21> self._pto_count += 1\n<22> self._send_probe()\n<23> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.packet_builder\n QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field(\n default_factory=list\n ))\n \n at: aioquic.packet_builder.QuicSentPacket\n sent_time: Optional[float] = None\n \n sent_bytes: int = 0\n \n at: aioquic.recovery\n K_MAX_DATAGRAM_SIZE = 1280\n \n at: aioquic.recovery.QuicPacketRecovery\n on_packet_lost(packet: QuicSentPacket, space: QuicPacketSpace) -> None\n \n at: aioquic.recovery.QuicPacketRecovery.__init__\n self._send_probe = send_probe\n \n self._crypto_count = 0\n \n self._pto_count = 0\n \n self.bytes_in_flight = 0\n \n self.congestion_window = K_INITIAL_WINDOW\n \n self._congestion_recovery_start_time = 0.0\n \n self._ssthresh = math.inf\n \n at: aioquic.recovery.QuicPacketRecovery.on_ack_received\n self._crypto_count = 0\n \n self._pto_count = 0\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_expired\n self.bytes_in_flight -= packet.sent_bytes\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_lost\n self.bytes_in_flight -= packet.sent_bytes\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_sent\n self.bytes_in_flight += packet.sent_bytes\n \n at: aioquic.recovery.QuicPacketRecovery.on_packets_lost\n self._congestion_recovery_start_time = now\n \n \n===========unchanged ref 1===========\n self.congestion_window = max(\n int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW\n )\n \n self._ssthresh = self.congestion_window\n \n \n===========changed ref 0===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def detect_loss(self, space: QuicPacketSpace, now: float) -> None:\n \"\"\"\n Check whether any packets should be declared lost.\n \"\"\"\n loss_delay = K_TIME_THRESHOLD * (\n max(self._rtt_latest, self._rtt_smoothed)\n if self._rtt_initialized\n else K_INITIAL_RTT\n )\n packet_threshold = space.largest_acked_packet - K_PACKET_THRESHOLD\n time_threshold = now - loss_delay\n \n - lost_bytes = 0\n lost_largest_time = None\n lost_packets = []\n space.loss_time = None\n for packet_number, packet in space.sent_packets.items():\n if packet_number > space.largest_acked_packet:\n break\n \n if packet_number <= packet_threshold or packet.sent_time <= time_threshold:\n lost_packets.append(packet)\n else:\n packet_loss_time = packet.sent_time + loss_delay\n if space.loss_time is None or space.loss_time > packet_loss_time:\n space.loss_time = packet_loss_time\n \n for packet in lost_packets:\n # remove packet and update counters\n - del space.sent_packets[packet.packet_number]\n - if packet.is_ack_eliciting:\n - space.ack_eliciting_in_flight -= 1\n - if packet.is_crypto_packet:\n - space.crypto_packet_in_flight -= 1\n + self.on_packet_lost(packet, space)\n if packet.in_flight:\n - lost_bytes += packet.sent_bytes\n lost_largest_time = packet.sent_time\n \n - # trigger callbacks\n - for handler, args in packet.delivery_handlers:\n - handler(QuicDeliveryState.LOST, *args)\n + if lost_largest_time is not None:\n + self.on_packets_lost(lost_\n===========changed ref 1===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def detect_loss(self, space: QuicPacketSpace, now: float) -> None:\n # offset: 1\n )\n + if lost_largest_time is not None:\n + self.on_packets_lost(lost_largest_time, now=now)\n \n - if lost_bytes:\n - self.on_packets_lost(lost_bytes, lost_largest_time, now=now)\n - "}}},{"rowIdx":2956,"cells":{"path":{"kind":"string","value":"aioquic.recovery/QuicPacketRecovery.on_packets_lost"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1f5f5f510801ad377240a1508a6ef7f12fbda3da"},"commit_message":{"kind":"string","value":"[recovery] add QuicPacketRecovery.on_packet_lost"},"ground_truth":{"kind":"string","value":" <0>: # remove lost packets from bytes in flight\n <1>: self.bytes_in_flight -= lost_bytes\n <2>: \n"},"main_code":{"kind":"string","value":" # module: aioquic.recovery\n class QuicPacketRecovery:\n - def on_packets_lost(\n - self, lost_bytes: int, lost_largest_time: float, now: float\n - ) -> None:\n + def on_packets_lost(self, lost_largest_time: float, now: float) -> None:\n <0> # remove lost packets from bytes in flight\n <1> self.bytes_in_flight -= lost_bytes\n <2> \n <3> # start a new congestion event if packet was sent after the\n <4> # start of the previous congestion recovery period.\n <5> if lost_largest_time > self._congestion_recovery_start_time:\n <6> self._congestion_recovery_start_time = now\n <7> self.congestion_window = max(\n <8> int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW\n <9> )\n<10> self._ssthresh = self.congestion_window\n<11> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.recovery\n K_MINIMUM_WINDOW = 2 * K_MAX_DATAGRAM_SIZE\n \n K_LOSS_REDUCTION_FACTOR = 0.5\n \n at: aioquic.recovery.QuicPacketRecovery.__init__\n self.congestion_window = K_INITIAL_WINDOW\n \n self._congestion_recovery_start_time = 0.0\n \n self._ssthresh = math.inf\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_acked\n self.congestion_window += (\n K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window\n )\n self.congestion_window += packet.sent_bytes\n \n \n===========changed ref 0===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n + def on_packet_lost(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None:\n + del space.sent_packets[packet.packet_number]\n + \n + if packet.is_ack_eliciting:\n + space.ack_eliciting_in_flight -= 1\n + if packet.is_crypto_packet:\n + space.crypto_packet_in_flight -= 1\n + if packet.in_flight:\n + self.bytes_in_flight -= packet.sent_bytes\n + \n + # trigger callbacks\n + for handler, args in packet.delivery_handlers:\n + handler(QuicDeliveryState.LOST, *args)\n + \n===========changed ref 1===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def on_loss_detection_timeout(self, now: float) -> None:\n loss_space = self.get_earliest_loss_time()\n if loss_space is not None:\n self.detect_loss(loss_space, now=now)\n elif sum(space.crypto_packet_in_flight for space in self.spaces):\n # reschedule crypto packets\n for space in self.spaces:\n for packet_number, packet in list(\n filter(lambda i: i[1].is_crypto_packet, space.sent_packets.items())\n ):\n # remove packet and update counters\n - del space.sent_packets[packet_number]\n - space.ack_eliciting_in_flight -= 1\n - space.crypto_packet_in_flight -= 1\n - if packet.in_flight:\n - self.bytes_in_flight -= packet.sent_bytes\n - \n - # trigger callbacks\n - for handler, args in packet.delivery_handlers:\n - handler(QuicDeliveryState.LOST, *args)\n + self.on_packet_lost(packet, space)\n self._crypto_count += 1\n else:\n self._pto_count += 1\n self._send_probe()\n \n===========changed ref 2===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def detect_loss(self, space: QuicPacketSpace, now: float) -> None:\n \"\"\"\n Check whether any packets should be declared lost.\n \"\"\"\n loss_delay = K_TIME_THRESHOLD * (\n max(self._rtt_latest, self._rtt_smoothed)\n if self._rtt_initialized\n else K_INITIAL_RTT\n )\n packet_threshold = space.largest_acked_packet - K_PACKET_THRESHOLD\n time_threshold = now - loss_delay\n \n - lost_bytes = 0\n lost_largest_time = None\n lost_packets = []\n space.loss_time = None\n for packet_number, packet in space.sent_packets.items():\n if packet_number > space.largest_acked_packet:\n break\n \n if packet_number <= packet_threshold or packet.sent_time <= time_threshold:\n lost_packets.append(packet)\n else:\n packet_loss_time = packet.sent_time + loss_delay\n if space.loss_time is None or space.loss_time > packet_loss_time:\n space.loss_time = packet_loss_time\n \n for packet in lost_packets:\n # remove packet and update counters\n - del space.sent_packets[packet.packet_number]\n - if packet.is_ack_eliciting:\n - space.ack_eliciting_in_flight -= 1\n - if packet.is_crypto_packet:\n - space.crypto_packet_in_flight -= 1\n + self.on_packet_lost(packet, space)\n if packet.in_flight:\n - lost_bytes += packet.sent_bytes\n lost_largest_time = packet.sent_time\n \n - # trigger callbacks\n - for handler, args in packet.delivery_handlers:\n - handler(QuicDeliveryState.LOST, *args)\n + if lost_largest_time is not None:\n + self.on_packets_lost(lost_\n===========changed ref 3===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def detect_loss(self, space: QuicPacketSpace, now: float) -> None:\n # offset: 1\n )\n + if lost_largest_time is not None:\n + self.on_packets_lost(lost_largest_time, now=now)\n \n - if lost_bytes:\n - self.on_packets_lost(lost_bytes, lost_largest_time, now=now)\n - "}}},{"rowIdx":2957,"cells":{"path":{"kind":"string","value":"aioquic.recovery/QuicPacketSpace.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"fc09c97d4543d7bc241308ff9cc9b5e88635a5eb"},"commit_message":{"kind":"string","value":"[recovery] merge crypto and pto timers"},"ground_truth":{"kind":"string","value":" <7>: self.crypto_packet_in_flight = 0\n"},"main_code":{"kind":"string","value":" # module: aioquic.recovery\n class QuicPacketSpace:\n def __init__(self) -> None:\n <0> self.ack_at: Optional[float] = None\n <1> self.ack_queue = RangeSet()\n <2> self.expected_packet_number = 0\n <3> self.largest_received_packet = 0\n <4> \n <5> # sent packets and loss\n <6> self.ack_eliciting_in_flight = 0\n <7> self.crypto_packet_in_flight = 0\n <8> self.largest_acked_packet = 0\n <9> self.loss_time: Optional[float] = None\n<10> self.sent_packets: Dict[int, QuicSentPacket] = {}\n<11> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.packet_builder\n QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field(\n default_factory=list\n ))\n \n at: aioquic.rangeset\n RangeSet(ranges: Iterable[range]=[])\n \n at: typing\n Dict = _alias(dict, 2, inst=False, name='Dict')\n \n "}}},{"rowIdx":2958,"cells":{"path":{"kind":"string","value":"aioquic.recovery/QuicPacketRecovery.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"fc09c97d4543d7bc241308ff9cc9b5e88635a5eb"},"commit_message":{"kind":"string","value":"[recovery] merge crypto and pto timers"},"ground_truth":{"kind":"string","value":" <8>: self._crypto_count = 0\n<16>: self._time_of_last_sent_crypto_packet = 0.0\n"},"main_code":{"kind":"string","value":" # module: aioquic.recovery\n class QuicPacketRecovery:\n def __init__(self, send_probe: Callable[[], None]) -> None:\n <0> self.ack_delay_exponent = 3\n <1> self.max_ack_delay = 25 # ms\n <2> self.spaces: List[QuicPacketSpace] = []\n <3> \n <4> # callbacks\n <5> self._send_probe = send_probe\n <6> \n <7> # loss detection\n <8> self._crypto_count = 0\n <9> self._pto_count = 0\n<10> self._rtt_initialized = False\n<11> self._rtt_latest = 0.0\n<12> self._rtt_min = math.inf\n<13> self._rtt_smoothed = 0.0\n<14> self._rtt_variance = 0.0\n<15> self._time_of_last_sent_ack_eliciting_packet = 0.0\n<16> self._time_of_last_sent_crypto_packet = 0.0\n<17> \n<18> # congestion control\n<19> self.bytes_in_flight = 0\n<20> self.congestion_window = K_INITIAL_WINDOW\n<21> self._congestion_recovery_start_time = 0.0\n<22> self._ssthresh = math.inf\n<23> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.recovery\n K_INITIAL_WINDOW = 10 * K_MAX_DATAGRAM_SIZE\n \n QuicPacketSpace()\n \n at: aioquic.recovery.QuicPacketRecovery.on_ack_received\n self._rtt_latest = max(latest_rtt, 0.001)\n self._rtt_latest -= ack_delay\n \n self._rtt_min = self._rtt_latest\n \n self._rtt_initialized = True\n \n self._rtt_variance = latest_rtt / 2\n self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs(\n self._rtt_min - self._rtt_latest\n )\n \n self._rtt_smoothed = latest_rtt\n self._rtt_smoothed = (\n 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest\n )\n \n self._pto_count = 0\n \n at: aioquic.recovery.QuicPacketRecovery.on_loss_detection_timeout\n self._pto_count += 1\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_acked\n self.bytes_in_flight -= packet.sent_bytes\n \n self.congestion_window += (\n K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window\n )\n self.congestion_window += packet.sent_bytes\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_expired\n self.bytes_in_flight -= packet.sent_bytes\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_lost\n self.bytes_in_flight -= packet.sent_bytes\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_sent\n self._time_of_last_sent_ack_eliciting_packet = packet.sent_time\n \n self.bytes_in_flight += packet.sent_bytes\n \n \n===========unchanged ref 1===========\n at: aioquic.recovery.QuicPacketRecovery.on_packets_lost\n self._congestion_recovery_start_time = now\n \n self.congestion_window = max(\n int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW\n )\n \n self._ssthresh = self.congestion_window\n \n at: math\n inf: float\n \n at: typing\n List = _alias(list, 1, inst=False, name='List')\n \n \n===========changed ref 0===========\n # module: aioquic.recovery\n class QuicPacketSpace:\n def __init__(self) -> None:\n self.ack_at: Optional[float] = None\n self.ack_queue = RangeSet()\n self.expected_packet_number = 0\n self.largest_received_packet = 0\n \n # sent packets and loss\n self.ack_eliciting_in_flight = 0\n - self.crypto_packet_in_flight = 0\n self.largest_acked_packet = 0\n self.loss_time: Optional[float] = None\n self.sent_packets: Dict[int, QuicSentPacket] = {}\n "}}},{"rowIdx":2959,"cells":{"path":{"kind":"string","value":"aioquic.recovery/QuicPacketRecovery.discard_space"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"fc09c97d4543d7bc241308ff9cc9b5e88635a5eb"},"commit_message":{"kind":"string","value":"[recovery] merge crypto and pto timers"},"ground_truth":{"kind":"string","value":" <9>: space.crypto_packet_in_flight = 0\n"},"main_code":{"kind":"string","value":" # module: aioquic.recovery\n class QuicPacketRecovery:\n def discard_space(self, space: QuicPacketSpace) -> None:\n <0> assert space in self.spaces\n <1> \n <2> for packet in space.sent_packets.values():\n <3> if packet.in_flight:\n <4> self.on_packet_expired(packet)\n <5> space.sent_packets.clear()\n <6> \n <7> space.ack_at = None\n <8> space.ack_eliciting_in_flight = 0\n <9> space.crypto_packet_in_flight = 0\n<10> space.loss_time = None\n<11> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.packet_builder.QuicSentPacket\n epoch: Epoch\n \n in_flight: bool\n \n is_ack_eliciting: bool\n \n is_crypto_packet: bool\n \n packet_number: int\n \n sent_time: Optional[float] = None\n \n sent_bytes: int = 0\n \n delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(\n default_factory=list\n )\n \n at: aioquic.recovery\n QuicPacketSpace()\n \n at: aioquic.recovery.QuicPacketRecovery\n on_packet_expired(packet: QuicSentPacket) -> None\n \n at: aioquic.recovery.QuicPacketRecovery.__init__\n self.spaces: List[QuicPacketSpace] = []\n \n at: aioquic.recovery.QuicPacketSpace.__init__\n self.ack_at: Optional[float] = None\n \n self.ack_eliciting_in_flight = 0\n \n self.loss_time: Optional[float] = None\n \n self.sent_packets: Dict[int, QuicSentPacket] = {}\n \n \n===========changed ref 0===========\n # module: aioquic.recovery\n class QuicPacketSpace:\n def __init__(self) -> None:\n self.ack_at: Optional[float] = None\n self.ack_queue = RangeSet()\n self.expected_packet_number = 0\n self.largest_received_packet = 0\n \n # sent packets and loss\n self.ack_eliciting_in_flight = 0\n - self.crypto_packet_in_flight = 0\n self.largest_acked_packet = 0\n self.loss_time: Optional[float] = None\n self.sent_packets: Dict[int, QuicSentPacket] = {}\n \n===========changed ref 1===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def __init__(self, send_probe: Callable[[], None]) -> None:\n self.ack_delay_exponent = 3\n self.max_ack_delay = 25 # ms\n self.spaces: List[QuicPacketSpace] = []\n \n # callbacks\n self._send_probe = send_probe\n \n # loss detection\n - self._crypto_count = 0\n self._pto_count = 0\n self._rtt_initialized = False\n self._rtt_latest = 0.0\n self._rtt_min = math.inf\n self._rtt_smoothed = 0.0\n self._rtt_variance = 0.0\n self._time_of_last_sent_ack_eliciting_packet = 0.0\n - self._time_of_last_sent_crypto_packet = 0.0\n \n # congestion control\n self.bytes_in_flight = 0\n self.congestion_window = K_INITIAL_WINDOW\n self._congestion_recovery_start_time = 0.0\n self._ssthresh = math.inf\n "}}},{"rowIdx":2960,"cells":{"path":{"kind":"string","value":"aioquic.recovery/QuicPacketRecovery.get_loss_detection_time"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"fc09c97d4543d7bc241308ff9cc9b5e88635a5eb"},"commit_message":{"kind":"string","value":"[recovery] merge crypto and pto timers"},"ground_truth":{"kind":"string","value":" <5>: # crypto timer\n <6>: if sum(space.crypto_packet_in_flight for space in self.spaces):\n <7>: timeout = max(\n <8>: 2 * (self._rtt_smoothed if self._rtt_initialized else K_INITIAL_RTT),\n <9>: K_GRANULARITY,\n<10>: ) * (2 ** self._crypto_count)\n<11>: return self._time_of_last_sent_crypto_packet + timeout\n<12>: \n<15>: if not self._rtt_initialized:\n timeout = 2 * K_INITIAL_RTT * (2 ** self._pto_count)\n else:\n timeout = (\n timeout = (\n<16>: self._rtt_smoothed\n self._rtt_smoothed\n<17>: + max(4 * self._rtt_variance, K_GRANULARITY)\n + max(4 * self._rtt_variance, K_GRANULARITY)\n<18>: + self.max_ack_delay / 1000\n + self.max_ack_delay / 1000\n<19>: ) * (2 ** self._pto_count)\n ) * (2 ** self._pto_count)\n"},"main_code":{"kind":"string","value":" # module: aioquic.recovery\n class QuicPacketRecovery:\n def get_loss_detection_time(self) -> float:\n <0> # loss timer\n <1> loss_space = self.get_earliest_loss_time()\n <2> if loss_space is not None:\n <3> return loss_space.loss_time\n <4> \n <5> # crypto timer\n <6> if sum(space.crypto_packet_in_flight for space in self.spaces):\n <7> timeout = max(\n <8> 2 * (self._rtt_smoothed if self._rtt_initialized else K_INITIAL_RTT),\n <9> K_GRANULARITY,\n<10> ) * (2 ** self._crypto_count)\n<11> return self._time_of_last_sent_crypto_packet + timeout\n<12> \n<13> # packet timer\n<14> if sum(space.ack_eliciting_in_flight for space in self.spaces):\n<15> timeout = (\n<16> self._rtt_smoothed\n<17> + max(4 * self._rtt_variance, K_GRANULARITY)\n<18> + self.max_ack_delay / 1000\n<19> ) * (2 ** self._pto_count)\n<20> return self._time_of_last_sent_ack_eliciting_packet + timeout\n<21> \n<22> return None\n<23> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.recovery\n K_INITIAL_RTT = 0.5 # seconds\n \n K_GRANULARITY = 0.001 # seconds\n \n at: aioquic.recovery.QuicPacketRecovery.__init__\n self.max_ack_delay = 25 # ms\n \n self.spaces: List[QuicPacketSpace] = []\n \n self._pto_count = 0\n \n self._rtt_initialized = False\n \n self._rtt_smoothed = 0.0\n \n self._rtt_variance = 0.0\n \n self._time_of_last_sent_ack_eliciting_packet = 0.0\n \n at: aioquic.recovery.QuicPacketRecovery.get_loss_detection_time\n loss_space = self.get_earliest_loss_time()\n \n at: aioquic.recovery.QuicPacketRecovery.on_ack_received\n self._rtt_initialized = True\n \n self._rtt_variance = latest_rtt / 2\n self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs(\n self._rtt_min - self._rtt_latest\n )\n \n self._rtt_smoothed = latest_rtt\n self._rtt_smoothed = (\n 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest\n )\n \n self._pto_count = 0\n \n at: aioquic.recovery.QuicPacketRecovery.on_loss_detection_timeout\n self._pto_count += 1\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_sent\n self._time_of_last_sent_ack_eliciting_packet = packet.sent_time\n \n at: aioquic.recovery.QuicPacketSpace.__init__\n self.ack_eliciting_in_flight = 0\n \n self.loss_time: Optional[float] = None\n \n \n===========changed ref 0===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def discard_space(self, space: QuicPacketSpace) -> None:\n assert space in self.spaces\n \n for packet in space.sent_packets.values():\n if packet.in_flight:\n self.on_packet_expired(packet)\n space.sent_packets.clear()\n \n space.ack_at = None\n space.ack_eliciting_in_flight = 0\n - space.crypto_packet_in_flight = 0\n space.loss_time = None\n \n===========changed ref 1===========\n # module: aioquic.recovery\n class QuicPacketSpace:\n def __init__(self) -> None:\n self.ack_at: Optional[float] = None\n self.ack_queue = RangeSet()\n self.expected_packet_number = 0\n self.largest_received_packet = 0\n \n # sent packets and loss\n self.ack_eliciting_in_flight = 0\n - self.crypto_packet_in_flight = 0\n self.largest_acked_packet = 0\n self.loss_time: Optional[float] = None\n self.sent_packets: Dict[int, QuicSentPacket] = {}\n \n===========changed ref 2===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def __init__(self, send_probe: Callable[[], None]) -> None:\n self.ack_delay_exponent = 3\n self.max_ack_delay = 25 # ms\n self.spaces: List[QuicPacketSpace] = []\n \n # callbacks\n self._send_probe = send_probe\n \n # loss detection\n - self._crypto_count = 0\n self._pto_count = 0\n self._rtt_initialized = False\n self._rtt_latest = 0.0\n self._rtt_min = math.inf\n self._rtt_smoothed = 0.0\n self._rtt_variance = 0.0\n self._time_of_last_sent_ack_eliciting_packet = 0.0\n - self._time_of_last_sent_crypto_packet = 0.0\n \n # congestion control\n self.bytes_in_flight = 0\n self.congestion_window = K_INITIAL_WINDOW\n self._congestion_recovery_start_time = 0.0\n self._ssthresh = math.inf\n "}}},{"rowIdx":2961,"cells":{"path":{"kind":"string","value":"aioquic.recovery/QuicPacketRecovery.on_ack_received"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"fc09c97d4543d7bc241308ff9cc9b5e88635a5eb"},"commit_message":{"kind":"string","value":"[recovery] merge crypto and pto timers"},"ground_truth":{"kind":"string","value":"<20>: if packet.is_crypto_packet:\n<21>: space.crypto_packet_in_flight -= 1\n"},"main_code":{"kind":"string","value":" # module: aioquic.recovery\n class QuicPacketRecovery:\n def on_ack_received(\n self,\n space: QuicPacketSpace,\n ack_rangeset: RangeSet,\n ack_delay_encoded: int,\n now: float,\n ) -> None:\n <0> \"\"\"\n <1> Update metrics as the result of an ACK being received.\n <2> \"\"\"\n <3> is_ack_eliciting = False\n <4> largest_acked = ack_rangeset.bounds().stop - 1\n <5> largest_newly_acked = None\n <6> largest_sent_time = None\n <7> \n <8> if largest_acked > space.largest_acked_packet:\n <9> space.largest_acked_packet = largest_acked\n<10> \n<11> for packet_number in sorted(space.sent_packets.keys()):\n<12> if packet_number > largest_acked:\n<13> break\n<14> if packet_number in ack_rangeset:\n<15> # remove packet and update counters\n<16> packet = space.sent_packets.pop(packet_number)\n<17> if packet.is_ack_eliciting:\n<18> is_ack_eliciting = True\n<19> space.ack_eliciting_in_flight -= 1\n<20> if packet.is_crypto_packet:\n<21> space.crypto_packet_in_flight -= 1\n<22> if packet.in_flight:\n<23> self.on_packet_acked(packet)\n<24> largest_newly_acked = packet_number\n<25> largest_sent_time = packet.sent_time\n<26> \n<27> # trigger callbacks\n<28> for handler, args in packet.delivery_handlers:\n<29> handler(QuicDeliveryState.ACKED, *args)\n<30> \n<31> # nothing to do if there are no newly acked packets\n<32> if largest_newly_acked is None:\n<33> return\n<34> \n<35> if largest_acked == largest_newly_acked and is_ack_eliciting:\n<36> latest_rtt = now - largest_sent_time\n<37> \n<38> # decode ACK delay into seconds\n<39> "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def on_ack_received(\n self,\n space: QuicPacketSpace,\n ack_rangeset: RangeSet,\n ack_delay_encoded: int,\n now: float,\n ) -> None:\n # offset: 1\n (ack_delay_encoded << self.ack_delay_exponent) / 1000000,\n self.max_ack_delay / 1000,\n )\n \n # update RTT estimate, which cannot be < 1 ms\n self._rtt_latest = max(latest_rtt, 0.001)\n if self._rtt_latest < self._rtt_min:\n self._rtt_min = self._rtt_latest\n if self._rtt_latest > self._rtt_min + ack_delay:\n self._rtt_latest -= ack_delay\n \n if not self._rtt_initialized:\n self._rtt_initialized = True\n self._rtt_variance = latest_rtt / 2\n self._rtt_smoothed = latest_rtt\n else:\n self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs(\n self._rtt_min - self._rtt_latest\n )\n self._rtt_smoothed = (\n 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest\n )\n \n self.detect_loss(space, now=now)\n \n self._crypto_count = 0\n self._pto_count = 0\n \n \n===========unchanged ref 0===========\n at: aioquic.packet_builder\n QuicDeliveryState()\n \n at: aioquic.packet_builder.QuicSentPacket\n in_flight: bool\n \n is_ack_eliciting: bool\n \n sent_time: Optional[float] = None\n \n delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(\n default_factory=list\n )\n \n at: aioquic.rangeset.RangeSet\n bounds() -> range\n \n at: aioquic.recovery.QuicPacketRecovery\n detect_loss(self, space: QuicPacketSpace, now: float) -> None\n detect_loss(space: QuicPacketSpace, now: float) -> None\n \n get_earliest_loss_time(self) -> Optional[QuicPacketSpace]\n get_earliest_loss_time() -> Optional[QuicPacketSpace]\n \n on_packet_acked(packet: QuicSentPacket) -> None\n on_packet_acked(self, packet: QuicSentPacket) -> None\n \n at: aioquic.recovery.QuicPacketRecovery.__init__\n self.ack_delay_exponent = 3\n \n self.max_ack_delay = 25 # ms\n \n self.spaces: List[QuicPacketSpace] = []\n \n self._pto_count = 0\n \n self._rtt_initialized = False\n \n self._rtt_latest = 0.0\n \n self._rtt_min = math.inf\n \n self._rtt_smoothed = 0.0\n \n self._rtt_variance = 0.0\n \n at: aioquic.recovery.QuicPacketSpace.__init__\n self.ack_eliciting_in_flight = 0\n \n self.largest_acked_packet = 0\n \n self.sent_packets: Dict[int, QuicSentPacket] = {}\n \n at: typing.MutableMapping\n pop(key: _KT) -> _VT\n pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T]\n \n \n===========changed ref 0===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def discard_space(self, space: QuicPacketSpace) -> None:\n assert space in self.spaces\n \n for packet in space.sent_packets.values():\n if packet.in_flight:\n self.on_packet_expired(packet)\n space.sent_packets.clear()\n \n space.ack_at = None\n space.ack_eliciting_in_flight = 0\n - space.crypto_packet_in_flight = 0\n space.loss_time = None\n \n===========changed ref 1===========\n # module: aioquic.recovery\n class QuicPacketSpace:\n def __init__(self) -> None:\n self.ack_at: Optional[float] = None\n self.ack_queue = RangeSet()\n self.expected_packet_number = 0\n self.largest_received_packet = 0\n \n # sent packets and loss\n self.ack_eliciting_in_flight = 0\n - self.crypto_packet_in_flight = 0\n self.largest_acked_packet = 0\n self.loss_time: Optional[float] = None\n self.sent_packets: Dict[int, QuicSentPacket] = {}\n \n===========changed ref 2===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def __init__(self, send_probe: Callable[[], None]) -> None:\n self.ack_delay_exponent = 3\n self.max_ack_delay = 25 # ms\n self.spaces: List[QuicPacketSpace] = []\n \n # callbacks\n self._send_probe = send_probe\n \n # loss detection\n - self._crypto_count = 0\n self._pto_count = 0\n self._rtt_initialized = False\n self._rtt_latest = 0.0\n self._rtt_min = math.inf\n self._rtt_smoothed = 0.0\n self._rtt_variance = 0.0\n self._time_of_last_sent_ack_eliciting_packet = 0.0\n - self._time_of_last_sent_crypto_packet = 0.0\n \n # congestion control\n self.bytes_in_flight = 0\n self.congestion_window = K_INITIAL_WINDOW\n self._congestion_recovery_start_time = 0.0\n self._ssthresh = math.inf\n \n===========changed ref 3===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def get_loss_detection_time(self) -> float:\n # loss timer\n loss_space = self.get_earliest_loss_time()\n if loss_space is not None:\n return loss_space.loss_time\n \n - # crypto timer\n - if sum(space.crypto_packet_in_flight for space in self.spaces):\n - timeout = max(\n - 2 * (self._rtt_smoothed if self._rtt_initialized else K_INITIAL_RTT),\n - K_GRANULARITY,\n - ) * (2 ** self._crypto_count)\n - return self._time_of_last_sent_crypto_packet + timeout\n - \n # packet timer\n if sum(space.ack_eliciting_in_flight for space in self.spaces):\n + if not self._rtt_initialized:\n + timeout = 2 * K_INITIAL_RTT * (2 ** self._pto_count)\n + else:\n + timeout = (\n - timeout = (\n + self._rtt_smoothed\n - self._rtt_smoothed\n + + max(4 * self._rtt_variance, K_GRANULARITY)\n - + max(4 * self._rtt_variance, K_GRANULARITY)\n + + self.max_ack_delay / 1000\n - + self.max_ack_delay / 1000\n + ) * (2 ** self._pto_count)\n - ) * (2 ** self._pto_count)\n return self._time_of_last_sent_ack_eliciting_packet + timeout\n \n return None\n "}}},{"rowIdx":2962,"cells":{"path":{"kind":"string","value":"aioquic.recovery/QuicPacketRecovery.on_loss_detection_timeout"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"fc09c97d4543d7bc241308ff9cc9b5e88635a5eb"},"commit_message":{"kind":"string","value":"[recovery] merge crypto and pto timers"},"ground_truth":{"kind":"string","value":" <3>: else:\n self._pto_count += 1\n \n # reschedule some data\n elif sum(space.crypto_packet_in_flight for space in self.spaces):\n <4>: # reschedule crypto packets\n<11>: self._crypto_count += 1\n<12>: else:\n<13>: self._pto_count += 1\n<14>: \n"},"main_code":{"kind":"string","value":" # module: aioquic.recovery\n class QuicPacketRecovery:\n def on_loss_detection_timeout(self, now: float) -> None:\n <0> loss_space = self.get_earliest_loss_time()\n <1> if loss_space is not None:\n <2> self.detect_loss(loss_space, now=now)\n <3> elif sum(space.crypto_packet_in_flight for space in self.spaces):\n <4> # reschedule crypto packets\n <5> for space in self.spaces:\n <6> for packet_number, packet in list(\n <7> filter(lambda i: i[1].is_crypto_packet, space.sent_packets.items())\n <8> ):\n <9> # remove packet and update counters\n<10> self.on_packet_lost(packet, space)\n<11> self._crypto_count += 1\n<12> else:\n<13> self._pto_count += 1\n<14> self._send_probe()\n<15> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.packet_builder\n QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field(\n default_factory=list\n ))\n \n at: aioquic.packet_builder.QuicSentPacket\n sent_time: Optional[float] = None\n \n sent_bytes: int = 0\n \n at: aioquic.recovery.QuicPacketRecovery\n on_packet_lost(packet: QuicSentPacket, space: QuicPacketSpace) -> None\n \n at: aioquic.recovery.QuicPacketRecovery.__init__\n self._send_probe = send_probe\n \n self.bytes_in_flight = 0\n \n self.congestion_window = K_INITIAL_WINDOW\n \n self._congestion_recovery_start_time = 0.0\n \n self._ssthresh = math.inf\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_expired\n self.bytes_in_flight -= packet.sent_bytes\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_lost\n self.bytes_in_flight -= packet.sent_bytes\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_sent\n self.bytes_in_flight += packet.sent_bytes\n \n at: aioquic.recovery.QuicPacketRecovery.on_packets_lost\n self._congestion_recovery_start_time = now\n \n self.congestion_window = max(\n int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW\n )\n \n self._ssthresh = self.congestion_window\n \n \n===========changed ref 0===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def discard_space(self, space: QuicPacketSpace) -> None:\n assert space in self.spaces\n \n for packet in space.sent_packets.values():\n if packet.in_flight:\n self.on_packet_expired(packet)\n space.sent_packets.clear()\n \n space.ack_at = None\n space.ack_eliciting_in_flight = 0\n - space.crypto_packet_in_flight = 0\n space.loss_time = None\n \n===========changed ref 1===========\n # module: aioquic.recovery\n class QuicPacketSpace:\n def __init__(self) -> None:\n self.ack_at: Optional[float] = None\n self.ack_queue = RangeSet()\n self.expected_packet_number = 0\n self.largest_received_packet = 0\n \n # sent packets and loss\n self.ack_eliciting_in_flight = 0\n - self.crypto_packet_in_flight = 0\n self.largest_acked_packet = 0\n self.loss_time: Optional[float] = None\n self.sent_packets: Dict[int, QuicSentPacket] = {}\n \n===========changed ref 2===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def __init__(self, send_probe: Callable[[], None]) -> None:\n self.ack_delay_exponent = 3\n self.max_ack_delay = 25 # ms\n self.spaces: List[QuicPacketSpace] = []\n \n # callbacks\n self._send_probe = send_probe\n \n # loss detection\n - self._crypto_count = 0\n self._pto_count = 0\n self._rtt_initialized = False\n self._rtt_latest = 0.0\n self._rtt_min = math.inf\n self._rtt_smoothed = 0.0\n self._rtt_variance = 0.0\n self._time_of_last_sent_ack_eliciting_packet = 0.0\n - self._time_of_last_sent_crypto_packet = 0.0\n \n # congestion control\n self.bytes_in_flight = 0\n self.congestion_window = K_INITIAL_WINDOW\n self._congestion_recovery_start_time = 0.0\n self._ssthresh = math.inf\n \n===========changed ref 3===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def get_loss_detection_time(self) -> float:\n # loss timer\n loss_space = self.get_earliest_loss_time()\n if loss_space is not None:\n return loss_space.loss_time\n \n - # crypto timer\n - if sum(space.crypto_packet_in_flight for space in self.spaces):\n - timeout = max(\n - 2 * (self._rtt_smoothed if self._rtt_initialized else K_INITIAL_RTT),\n - K_GRANULARITY,\n - ) * (2 ** self._crypto_count)\n - return self._time_of_last_sent_crypto_packet + timeout\n - \n # packet timer\n if sum(space.ack_eliciting_in_flight for space in self.spaces):\n + if not self._rtt_initialized:\n + timeout = 2 * K_INITIAL_RTT * (2 ** self._pto_count)\n + else:\n + timeout = (\n - timeout = (\n + self._rtt_smoothed\n - self._rtt_smoothed\n + + max(4 * self._rtt_variance, K_GRANULARITY)\n - + max(4 * self._rtt_variance, K_GRANULARITY)\n + + self.max_ack_delay / 1000\n - + self.max_ack_delay / 1000\n + ) * (2 ** self._pto_count)\n - ) * (2 ** self._pto_count)\n return self._time_of_last_sent_ack_eliciting_packet + timeout\n \n return None\n \n===========changed ref 4===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def on_ack_received(\n self,\n space: QuicPacketSpace,\n ack_rangeset: RangeSet,\n ack_delay_encoded: int,\n now: float,\n ) -> None:\n \"\"\"\n Update metrics as the result of an ACK being received.\n \"\"\"\n is_ack_eliciting = False\n largest_acked = ack_rangeset.bounds().stop - 1\n largest_newly_acked = None\n largest_sent_time = None\n \n if largest_acked > space.largest_acked_packet:\n space.largest_acked_packet = largest_acked\n \n for packet_number in sorted(space.sent_packets.keys()):\n if packet_number > largest_acked:\n break\n if packet_number in ack_rangeset:\n # remove packet and update counters\n packet = space.sent_packets.pop(packet_number)\n if packet.is_ack_eliciting:\n is_ack_eliciting = True\n space.ack_eliciting_in_flight -= 1\n - if packet.is_crypto_packet:\n - space.crypto_packet_in_flight -= 1\n if packet.in_flight:\n self.on_packet_acked(packet)\n largest_newly_acked = packet_number\n largest_sent_time = packet.sent_time\n \n # trigger callbacks\n for handler, args in packet.delivery_handlers:\n handler(QuicDeliveryState.ACKED, *args)\n \n # nothing to do if there are no newly acked packets\n if largest_newly_acked is None:\n return\n \n if largest_acked == largest_newly_acked and is_ack_eliciting:\n latest_rtt = now - largest_sent_time\n \n # decode ACK delay into seconds\n ack_delay = max(\n (ack_delay_encoded << self.ack_delay_exponent) / 1000000,\n self.max_ack_delay / 1000"}}},{"rowIdx":2963,"cells":{"path":{"kind":"string","value":"aioquic.recovery/QuicPacketRecovery.on_packet_lost"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"fc09c97d4543d7bc241308ff9cc9b5e88635a5eb"},"commit_message":{"kind":"string","value":"[recovery] merge crypto and pto timers"},"ground_truth":{"kind":"string","value":" <4>: if packet.is_crypto_packet:\n <5>: space.crypto_packet_in_flight -= 1\n"},"main_code":{"kind":"string","value":" # module: aioquic.recovery\n class QuicPacketRecovery:\n def on_packet_lost(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None:\n <0> del space.sent_packets[packet.packet_number]\n <1> \n <2> if packet.is_ack_eliciting:\n <3> space.ack_eliciting_in_flight -= 1\n <4> if packet.is_crypto_packet:\n <5> space.crypto_packet_in_flight -= 1\n <6> if packet.in_flight:\n <7> self.bytes_in_flight -= packet.sent_bytes\n <8> \n <9> # trigger callbacks\n<10> for handler, args in packet.delivery_handlers:\n<11> handler(QuicDeliveryState.LOST, *args)\n<12> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.packet_builder\n QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field(\n default_factory=list\n ))\n \n at: aioquic.packet_builder.QuicSentPacket\n in_flight: bool\n \n is_ack_eliciting: bool\n \n packet_number: int\n \n sent_time: Optional[float] = None\n \n sent_bytes: int = 0\n \n at: aioquic.recovery\n QuicPacketSpace()\n \n at: aioquic.recovery.QuicPacketRecovery.__init__\n self._time_of_last_sent_ack_eliciting_packet = 0.0\n \n self.bytes_in_flight = 0\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_acked\n self.bytes_in_flight -= packet.sent_bytes\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_expired\n self.bytes_in_flight -= packet.sent_bytes\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_lost\n self.bytes_in_flight -= packet.sent_bytes\n \n at: aioquic.recovery.QuicPacketSpace.__init__\n self.ack_eliciting_in_flight = 0\n \n self.sent_packets: Dict[int, QuicSentPacket] = {}\n \n \n===========changed ref 0===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def on_loss_detection_timeout(self, now: float) -> None:\n loss_space = self.get_earliest_loss_time()\n if loss_space is not None:\n self.detect_loss(loss_space, now=now)\n + else:\n + self._pto_count += 1\n + \n + # reschedule some data\n - elif sum(space.crypto_packet_in_flight for space in self.spaces):\n - # reschedule crypto packets\n for space in self.spaces:\n for packet_number, packet in list(\n filter(lambda i: i[1].is_crypto_packet, space.sent_packets.items())\n ):\n # remove packet and update counters\n self.on_packet_lost(packet, space)\n - self._crypto_count += 1\n - else:\n - self._pto_count += 1\n + \n self._send_probe()\n \n===========changed ref 1===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def discard_space(self, space: QuicPacketSpace) -> None:\n assert space in self.spaces\n \n for packet in space.sent_packets.values():\n if packet.in_flight:\n self.on_packet_expired(packet)\n space.sent_packets.clear()\n \n space.ack_at = None\n space.ack_eliciting_in_flight = 0\n - space.crypto_packet_in_flight = 0\n space.loss_time = None\n \n===========changed ref 2===========\n # module: aioquic.recovery\n class QuicPacketSpace:\n def __init__(self) -> None:\n self.ack_at: Optional[float] = None\n self.ack_queue = RangeSet()\n self.expected_packet_number = 0\n self.largest_received_packet = 0\n \n # sent packets and loss\n self.ack_eliciting_in_flight = 0\n - self.crypto_packet_in_flight = 0\n self.largest_acked_packet = 0\n self.loss_time: Optional[float] = None\n self.sent_packets: Dict[int, QuicSentPacket] = {}\n \n===========changed ref 3===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def __init__(self, send_probe: Callable[[], None]) -> None:\n self.ack_delay_exponent = 3\n self.max_ack_delay = 25 # ms\n self.spaces: List[QuicPacketSpace] = []\n \n # callbacks\n self._send_probe = send_probe\n \n # loss detection\n - self._crypto_count = 0\n self._pto_count = 0\n self._rtt_initialized = False\n self._rtt_latest = 0.0\n self._rtt_min = math.inf\n self._rtt_smoothed = 0.0\n self._rtt_variance = 0.0\n self._time_of_last_sent_ack_eliciting_packet = 0.0\n - self._time_of_last_sent_crypto_packet = 0.0\n \n # congestion control\n self.bytes_in_flight = 0\n self.congestion_window = K_INITIAL_WINDOW\n self._congestion_recovery_start_time = 0.0\n self._ssthresh = math.inf\n \n===========changed ref 4===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def get_loss_detection_time(self) -> float:\n # loss timer\n loss_space = self.get_earliest_loss_time()\n if loss_space is not None:\n return loss_space.loss_time\n \n - # crypto timer\n - if sum(space.crypto_packet_in_flight for space in self.spaces):\n - timeout = max(\n - 2 * (self._rtt_smoothed if self._rtt_initialized else K_INITIAL_RTT),\n - K_GRANULARITY,\n - ) * (2 ** self._crypto_count)\n - return self._time_of_last_sent_crypto_packet + timeout\n - \n # packet timer\n if sum(space.ack_eliciting_in_flight for space in self.spaces):\n + if not self._rtt_initialized:\n + timeout = 2 * K_INITIAL_RTT * (2 ** self._pto_count)\n + else:\n + timeout = (\n - timeout = (\n + self._rtt_smoothed\n - self._rtt_smoothed\n + + max(4 * self._rtt_variance, K_GRANULARITY)\n - + max(4 * self._rtt_variance, K_GRANULARITY)\n + + self.max_ack_delay / 1000\n - + self.max_ack_delay / 1000\n + ) * (2 ** self._pto_count)\n - ) * (2 ** self._pto_count)\n return self._time_of_last_sent_ack_eliciting_packet + timeout\n \n return None\n "}}},{"rowIdx":2964,"cells":{"path":{"kind":"string","value":"aioquic.recovery/QuicPacketRecovery.on_packet_sent"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"fc09c97d4543d7bc241308ff9cc9b5e88635a5eb"},"commit_message":{"kind":"string","value":"[recovery] merge crypto and pto timers"},"ground_truth":{"kind":"string","value":" <4>: if packet.is_crypto_packet:\n <5>: space.crypto_packet_in_flight += 1\n <7>: if packet.is_crypto_packet:\n <8>: self._time_of_last_sent_crypto_packet = packet.sent_time\n"},"main_code":{"kind":"string","value":" # module: aioquic.recovery\n class QuicPacketRecovery:\n def on_packet_sent(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None:\n <0> space.sent_packets[packet.packet_number] = packet\n <1> \n <2> if packet.is_ack_eliciting:\n <3> space.ack_eliciting_in_flight += 1\n <4> if packet.is_crypto_packet:\n <5> space.crypto_packet_in_flight += 1\n <6> if packet.in_flight:\n <7> if packet.is_crypto_packet:\n <8> self._time_of_last_sent_crypto_packet = packet.sent_time\n <9> if packet.is_ack_eliciting:\n<10> self._time_of_last_sent_ack_eliciting_packet = packet.sent_time\n<11> \n<12> # add packet to bytes in flight\n<13> self.bytes_in_flight += packet.sent_bytes\n<14> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.recovery\n K_MINIMUM_WINDOW = 2 * K_MAX_DATAGRAM_SIZE\n \n K_LOSS_REDUCTION_FACTOR = 0.5\n \n at: aioquic.recovery.QuicPacketRecovery.__init__\n self.congestion_window = K_INITIAL_WINDOW\n \n self._congestion_recovery_start_time = 0.0\n \n self._ssthresh = math.inf\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_acked\n self.congestion_window += (\n K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window\n )\n self.congestion_window += packet.sent_bytes\n \n \n===========changed ref 0===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def on_packet_lost(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None:\n del space.sent_packets[packet.packet_number]\n \n if packet.is_ack_eliciting:\n space.ack_eliciting_in_flight -= 1\n - if packet.is_crypto_packet:\n - space.crypto_packet_in_flight -= 1\n if packet.in_flight:\n self.bytes_in_flight -= packet.sent_bytes\n \n # trigger callbacks\n for handler, args in packet.delivery_handlers:\n handler(QuicDeliveryState.LOST, *args)\n \n===========changed ref 1===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def on_loss_detection_timeout(self, now: float) -> None:\n loss_space = self.get_earliest_loss_time()\n if loss_space is not None:\n self.detect_loss(loss_space, now=now)\n + else:\n + self._pto_count += 1\n + \n + # reschedule some data\n - elif sum(space.crypto_packet_in_flight for space in self.spaces):\n - # reschedule crypto packets\n for space in self.spaces:\n for packet_number, packet in list(\n filter(lambda i: i[1].is_crypto_packet, space.sent_packets.items())\n ):\n # remove packet and update counters\n self.on_packet_lost(packet, space)\n - self._crypto_count += 1\n - else:\n - self._pto_count += 1\n + \n self._send_probe()\n \n===========changed ref 2===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def discard_space(self, space: QuicPacketSpace) -> None:\n assert space in self.spaces\n \n for packet in space.sent_packets.values():\n if packet.in_flight:\n self.on_packet_expired(packet)\n space.sent_packets.clear()\n \n space.ack_at = None\n space.ack_eliciting_in_flight = 0\n - space.crypto_packet_in_flight = 0\n space.loss_time = None\n \n===========changed ref 3===========\n # module: aioquic.recovery\n class QuicPacketSpace:\n def __init__(self) -> None:\n self.ack_at: Optional[float] = None\n self.ack_queue = RangeSet()\n self.expected_packet_number = 0\n self.largest_received_packet = 0\n \n # sent packets and loss\n self.ack_eliciting_in_flight = 0\n - self.crypto_packet_in_flight = 0\n self.largest_acked_packet = 0\n self.loss_time: Optional[float] = None\n self.sent_packets: Dict[int, QuicSentPacket] = {}\n \n===========changed ref 4===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def __init__(self, send_probe: Callable[[], None]) -> None:\n self.ack_delay_exponent = 3\n self.max_ack_delay = 25 # ms\n self.spaces: List[QuicPacketSpace] = []\n \n # callbacks\n self._send_probe = send_probe\n \n # loss detection\n - self._crypto_count = 0\n self._pto_count = 0\n self._rtt_initialized = False\n self._rtt_latest = 0.0\n self._rtt_min = math.inf\n self._rtt_smoothed = 0.0\n self._rtt_variance = 0.0\n self._time_of_last_sent_ack_eliciting_packet = 0.0\n - self._time_of_last_sent_crypto_packet = 0.0\n \n # congestion control\n self.bytes_in_flight = 0\n self.congestion_window = K_INITIAL_WINDOW\n self._congestion_recovery_start_time = 0.0\n self._ssthresh = math.inf\n \n===========changed ref 5===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def get_loss_detection_time(self) -> float:\n # loss timer\n loss_space = self.get_earliest_loss_time()\n if loss_space is not None:\n return loss_space.loss_time\n \n - # crypto timer\n - if sum(space.crypto_packet_in_flight for space in self.spaces):\n - timeout = max(\n - 2 * (self._rtt_smoothed if self._rtt_initialized else K_INITIAL_RTT),\n - K_GRANULARITY,\n - ) * (2 ** self._crypto_count)\n - return self._time_of_last_sent_crypto_packet + timeout\n - \n # packet timer\n if sum(space.ack_eliciting_in_flight for space in self.spaces):\n + if not self._rtt_initialized:\n + timeout = 2 * K_INITIAL_RTT * (2 ** self._pto_count)\n + else:\n + timeout = (\n - timeout = (\n + self._rtt_smoothed\n - self._rtt_smoothed\n + + max(4 * self._rtt_variance, K_GRANULARITY)\n - + max(4 * self._rtt_variance, K_GRANULARITY)\n + + self.max_ack_delay / 1000\n - + self.max_ack_delay / 1000\n + ) * (2 ** self._pto_count)\n - ) * (2 ** self._pto_count)\n return self._time_of_last_sent_ack_eliciting_packet + timeout\n \n return None\n "}}},{"rowIdx":2965,"cells":{"path":{"kind":"string","value":"tests.test_recovery/QuicPacketRecoveryTest.test_on_packet_lost_crypto"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"fc09c97d4543d7bc241308ff9cc9b5e88635a5eb"},"commit_message":{"kind":"string","value":"[recovery] merge crypto and pto timers"},"ground_truth":{"kind":"string","value":"<14>: self.assertEqual(space.crypto_packet_in_flight, 1)\n<20>: self.assertEqual(space.crypto_packet_in_flight, 0)\n"},"main_code":{"kind":"string","value":" # module: tests.test_recovery\n class QuicPacketRecoveryTest(TestCase):\n def test_on_packet_lost_crypto(self):\n <0> packet = QuicSentPacket(\n <1> epoch=tls.Epoch.INITIAL,\n <2> in_flight=True,\n <3> is_ack_eliciting=True,\n <4> is_crypto_packet=True,\n <5> packet_number=0,\n <6> sent_bytes=1280,\n <7> sent_time=123.45,\n <8> )\n <9> space = self.INITIAL_SPACE\n<10> \n<11> self.recovery.on_packet_sent(packet, space)\n<12> self.assertEqual(self.recovery.bytes_in_flight, 1280)\n<13> self.assertEqual(space.ack_eliciting_in_flight, 1)\n<14> self.assertEqual(space.crypto_packet_in_flight, 1)\n<15> self.assertEqual(len(space.sent_packets), 1)\n<16> \n<17> self.recovery.on_packet_lost(packet, space)\n<18> self.assertEqual(self.recovery.bytes_in_flight, 0)\n<19> self.assertEqual(space.ack_eliciting_in_flight, 0)\n<20> self.assertEqual(space.crypto_packet_in_flight, 0)\n<21> self.assertEqual(len(space.sent_packets), 0)\n<22> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.packet_builder\n QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field(\n default_factory=list\n ))\n \n at: aioquic.packet_builder.QuicSentPacket\n epoch: Epoch\n \n in_flight: bool\n \n is_ack_eliciting: bool\n \n is_crypto_packet: bool\n \n packet_number: int\n \n sent_time: Optional[float] = None\n \n sent_bytes: int = 0\n \n delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(\n default_factory=list\n )\n \n at: aioquic.recovery.QuicPacketRecovery\n on_packet_lost(packet: QuicSentPacket, space: QuicPacketSpace) -> None\n \n on_packet_sent(packet: QuicSentPacket, space: QuicPacketSpace) -> None\n \n at: aioquic.recovery.QuicPacketRecovery.__init__\n self.bytes_in_flight = 0\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_acked\n self.bytes_in_flight -= packet.sent_bytes\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_expired\n self.bytes_in_flight -= packet.sent_bytes\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_lost\n self.bytes_in_flight -= packet.sent_bytes\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_sent\n self.bytes_in_flight += packet.sent_bytes\n \n at: aioquic.recovery.QuicPacketSpace.__init__\n self.ack_eliciting_in_flight = 0\n \n self.sent_packets: Dict[int, QuicSentPacket] = {}\n \n \n===========unchanged ref 1===========\n at: aioquic.tls\n Epoch()\n \n at: tests.test_recovery.QuicPacketRecoveryTest.setUp\n self.INITIAL_SPACE = QuicPacketSpace()\n \n self.recovery = QuicPacketRecovery(send_probe=send_probe)\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n _testMethodDoc: str\n \n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def on_packet_lost(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None:\n del space.sent_packets[packet.packet_number]\n \n if packet.is_ack_eliciting:\n space.ack_eliciting_in_flight -= 1\n - if packet.is_crypto_packet:\n - space.crypto_packet_in_flight -= 1\n if packet.in_flight:\n self.bytes_in_flight -= packet.sent_bytes\n \n # trigger callbacks\n for handler, args in packet.delivery_handlers:\n handler(QuicDeliveryState.LOST, *args)\n \n===========changed ref 1===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def on_packet_sent(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None:\n space.sent_packets[packet.packet_number] = packet\n \n if packet.is_ack_eliciting:\n space.ack_eliciting_in_flight += 1\n - if packet.is_crypto_packet:\n - space.crypto_packet_in_flight += 1\n if packet.in_flight:\n - if packet.is_crypto_packet:\n - self._time_of_last_sent_crypto_packet = packet.sent_time\n if packet.is_ack_eliciting:\n self._time_of_last_sent_ack_eliciting_packet = packet.sent_time\n \n # add packet to bytes in flight\n self.bytes_in_flight += packet.sent_bytes\n \n===========changed ref 2===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def discard_space(self, space: QuicPacketSpace) -> None:\n assert space in self.spaces\n \n for packet in space.sent_packets.values():\n if packet.in_flight:\n self.on_packet_expired(packet)\n space.sent_packets.clear()\n \n space.ack_at = None\n space.ack_eliciting_in_flight = 0\n - space.crypto_packet_in_flight = 0\n space.loss_time = None\n \n===========changed ref 3===========\n # module: aioquic.recovery\n class QuicPacketSpace:\n def __init__(self) -> None:\n self.ack_at: Optional[float] = None\n self.ack_queue = RangeSet()\n self.expected_packet_number = 0\n self.largest_received_packet = 0\n \n # sent packets and loss\n self.ack_eliciting_in_flight = 0\n - self.crypto_packet_in_flight = 0\n self.largest_acked_packet = 0\n self.loss_time: Optional[float] = None\n self.sent_packets: Dict[int, QuicSentPacket] = {}\n \n===========changed ref 4===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def on_loss_detection_timeout(self, now: float) -> None:\n loss_space = self.get_earliest_loss_time()\n if loss_space is not None:\n self.detect_loss(loss_space, now=now)\n + else:\n + self._pto_count += 1\n + \n + # reschedule some data\n - elif sum(space.crypto_packet_in_flight for space in self.spaces):\n - # reschedule crypto packets\n for space in self.spaces:\n for packet_number, packet in list(\n filter(lambda i: i[1].is_crypto_packet, space.sent_packets.items())\n ):\n # remove packet and update counters\n self.on_packet_lost(packet, space)\n - self._crypto_count += 1\n - else:\n - self._pto_count += 1\n + \n self._send_probe()\n \n===========changed ref 5===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def __init__(self, send_probe: Callable[[], None]) -> None:\n self.ack_delay_exponent = 3\n self.max_ack_delay = 25 # ms\n self.spaces: List[QuicPacketSpace] = []\n \n # callbacks\n self._send_probe = send_probe\n \n # loss detection\n - self._crypto_count = 0\n self._pto_count = 0\n self._rtt_initialized = False\n self._rtt_latest = 0.0\n self._rtt_min = math.inf\n self._rtt_smoothed = 0.0\n self._rtt_variance = 0.0\n self._time_of_last_sent_ack_eliciting_packet = 0.0\n - self._time_of_last_sent_crypto_packet = 0.0\n \n # congestion control\n self.bytes_in_flight = 0\n self.congestion_window = K_INITIAL_WINDOW\n self._congestion_recovery_start_time = 0.0\n self._ssthresh = math.inf\n "}}},{"rowIdx":2966,"cells":{"path":{"kind":"string","value":"aioquic.recovery/QuicPacketRecovery.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"091d169f28d7efeeac27d58a1dec1a6cef1d39a3"},"commit_message":{"kind":"string","value":"[recovery] send anti-deadlock packets more agressively"},"ground_truth":{"kind":"string","value":" <1>: self.is_client_without_1rtt = is_client_without_1rtt\n"},"main_code":{"kind":"string","value":" # module: aioquic.recovery\n class QuicPacketRecovery:\n + def __init__(\n + self, is_client_without_1rtt: bool, send_probe: Callable[[], None]\n + ) -> None:\n - def __init__(self, send_probe: Callable[[], None]) -> None:\n <0> self.ack_delay_exponent = 3\n <1> self.max_ack_delay = 25 # ms\n <2> self.spaces: List[QuicPacketSpace] = []\n <3> \n <4> # callbacks\n <5> self._send_probe = send_probe\n <6> \n <7> # loss detection\n <8> self._pto_count = 0\n <9> self._rtt_initialized = False\n<10> self._rtt_latest = 0.0\n<11> self._rtt_min = math.inf\n<12> self._rtt_smoothed = 0.0\n<13> self._rtt_variance = 0.0\n<14> self._time_of_last_sent_ack_eliciting_packet = 0.0\n<15> \n<16> # congestion control\n<17> self.bytes_in_flight = 0\n<18> self.congestion_window = K_INITIAL_WINDOW\n<19> self._congestion_recovery_start_time = 0.0\n<20> self._ssthresh = math.inf\n<21> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.recovery\n QuicPacketSpace()\n \n at: aioquic.recovery.QuicPacketRecovery.on_ack_received\n self._rtt_latest = max(latest_rtt, 0.001)\n self._rtt_latest -= ack_delay\n \n self._rtt_min = self._rtt_latest\n \n self._rtt_initialized = True\n \n self._rtt_variance = latest_rtt / 2\n self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs(\n self._rtt_min - self._rtt_latest\n )\n \n self._rtt_smoothed = latest_rtt\n self._rtt_smoothed = (\n 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest\n )\n \n self._pto_count = 0\n \n at: aioquic.recovery.QuicPacketRecovery.on_loss_detection_timeout\n self._pto_count += 1\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_acked\n self.bytes_in_flight -= packet.sent_bytes\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_expired\n self.bytes_in_flight -= packet.sent_bytes\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_lost\n self.bytes_in_flight -= packet.sent_bytes\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_sent\n self._time_of_last_sent_ack_eliciting_packet = packet.sent_time\n \n self.bytes_in_flight += packet.sent_bytes\n \n at: math\n inf: float\n \n at: typing\n Callable = _CallableType(collections.abc.Callable, 2)\n \n List = _alias(list, 1, inst=False, name='List')\n \n "}}},{"rowIdx":2967,"cells":{"path":{"kind":"string","value":"aioquic.recovery/QuicPacketRecovery.get_loss_detection_time"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"091d169f28d7efeeac27d58a1dec1a6cef1d39a3"},"commit_message":{"kind":"string","value":"[recovery] send anti-deadlock packets more agressively"},"ground_truth":{"kind":"string","value":" <6>: if (\n self.is_client_without_1rtt\n or sum(space.ack_eliciting_in_flight for space in self.spaces) > 0\n if sum(space.ack_eliciting_in_flight for space in self.spaces):\n <7>: ):\n"},"main_code":{"kind":"string","value":" # module: aioquic.recovery\n class QuicPacketRecovery:\n def get_loss_detection_time(self) -> float:\n <0> # loss timer\n <1> loss_space = self.get_earliest_loss_time()\n <2> if loss_space is not None:\n <3> return loss_space.loss_time\n <4> \n <5> # packet timer\n <6> if sum(space.ack_eliciting_in_flight for space in self.spaces):\n <7> if not self._rtt_initialized:\n <8> timeout = 2 * K_INITIAL_RTT * (2 ** self._pto_count)\n <9> else:\n<10> timeout = (\n<11> self._rtt_smoothed\n<12> + max(4 * self._rtt_variance, K_GRANULARITY)\n<13> + self.max_ack_delay / 1000\n<14> ) * (2 ** self._pto_count)\n<15> return self._time_of_last_sent_ack_eliciting_packet + timeout\n<16> \n<17> return None\n<18> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.recovery\n K_INITIAL_RTT = 0.5 # seconds\n \n at: aioquic.recovery.QuicPacketRecovery\n get_earliest_loss_time() -> Optional[QuicPacketSpace]\n \n at: aioquic.recovery.QuicPacketRecovery.__init__\n self.is_client_without_1rtt = is_client_without_1rtt\n \n self.spaces: List[QuicPacketSpace] = []\n \n self._pto_count = 0\n \n self._rtt_initialized = False\n \n self._rtt_smoothed = 0.0\n \n at: aioquic.recovery.QuicPacketRecovery.on_ack_received\n self._rtt_initialized = True\n \n self._rtt_smoothed = latest_rtt\n self._rtt_smoothed = (\n 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest\n )\n \n self._pto_count = 0\n \n at: aioquic.recovery.QuicPacketRecovery.on_loss_detection_timeout\n self._pto_count += 1\n \n at: aioquic.recovery.QuicPacketSpace.__init__\n self.ack_eliciting_in_flight = 0\n \n self.loss_time: Optional[float] = None\n \n \n===========changed ref 0===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n + def __init__(\n + self, is_client_without_1rtt: bool, send_probe: Callable[[], None]\n + ) -> None:\n - def __init__(self, send_probe: Callable[[], None]) -> None:\n self.ack_delay_exponent = 3\n + self.is_client_without_1rtt = is_client_without_1rtt\n self.max_ack_delay = 25 # ms\n self.spaces: List[QuicPacketSpace] = []\n \n # callbacks\n self._send_probe = send_probe\n \n # loss detection\n self._pto_count = 0\n self._rtt_initialized = False\n self._rtt_latest = 0.0\n self._rtt_min = math.inf\n self._rtt_smoothed = 0.0\n self._rtt_variance = 0.0\n self._time_of_last_sent_ack_eliciting_packet = 0.0\n \n # congestion control\n self.bytes_in_flight = 0\n self.congestion_window = K_INITIAL_WINDOW\n self._congestion_recovery_start_time = 0.0\n self._ssthresh = math.inf\n "}}},{"rowIdx":2968,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"091d169f28d7efeeac27d58a1dec1a6cef1d39a3"},"commit_message":{"kind":"string","value":"[recovery] send anti-deadlock packets more agressively"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n original_connection_id: Optional[bytes] = None,\n session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,\n session_ticket_handler: Optional[tls.SessionTicketHandler] = None,\n ) -> None:\n <0> if configuration.is_client:\n <1> assert (\n <2> original_connection_id is None\n <3> ), \"Cannot set original_connection_id for a client\"\n <4> else:\n <5> assert (\n <6> configuration.certificate is not None\n <7> ), \"SSL certificate is required for a server\"\n <8> assert (\n <9> configuration.private_key is not None\n<10> ), \"SSL private key is required for a server\"\n<11> \n<12> # counters for debugging\n<13> self._stateless_retry_count = 0\n<14> self._version_negotiation_count = 0\n<15> \n<16> # configuration\n<17> self._configuration = configuration\n<18> self._is_client = configuration.is_client\n<19> \n<20> self._ack_delay = K_GRANULARITY\n<21> self._close_at: Optional[float] = None\n<22> self._close_event: Optional[events.ConnectionTerminated] = None\n<23> self._connect_called = False\n<24> self._cryptos: Dict[tls.Epoch, CryptoPair] = {}\n<25> self._crypto_buffers: Dict[tls.Epoch, Buffer] = {}\n<26> self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}\n<27> self._events: Deque[events.Event] = deque()\n<28> self._handshake_complete = False\n<29> self._handshake_confirmed = False\n<30> self._host_cids = [\n<31> QuicConnectionId(\n<32> cid=os.urandom(8),\n<33> sequence_number=0,\n<34> stateless_reset_token=os.urandom(16),\n<35> was_sent=True,\n<36> )\n<37> ]\n<38> self.host_cid = self._"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.connection\n class QuicConnection:\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n original_connection_id: Optional[bytes] = None,\n session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,\n session_ticket_handler: Optional[tls.SessionTicketHandler] = None,\n ) -> None:\n # offset: 1\n self._host_cid_seq = 1\n self._local_max_data = MAX_DATA_WINDOW\n self._local_max_data_sent = MAX_DATA_WINDOW\n self._local_max_data_used = 0\n self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW\n self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW\n self._local_max_stream_data_uni = MAX_DATA_WINDOW\n self._local_max_streams_bidi = 128\n self._local_max_streams_uni = 128\n self._logger = QuicConnectionAdapter(\n logger, {\"host_cid\": dump_cid(self.host_cid)}\n )\n self._loss = QuicPacketRecovery(send_probe=self._send_probe)\n self._loss_at: Optional[float] = None\n self._network_paths: List[QuicNetworkPath] = []\n self._original_connection_id = original_connection_id\n self._packet_number = 0\n self._parameters_received = False\n self._peer_cid = os.urandom(8)\n self._peer_cid_seq: Optional[int] = None\n self._peer_cid_available: List[QuicConnectionId] = []\n self._peer_token = b\"\"\n self._remote_idle_timeout = 0.0 # seconds\n self._remote_max_data = 0\n self._remote_max_data_used = 0\n self._remote_max_stream_data_bidi_local = 0\n self._remote_max_stream_data_bidi_remote = 0\n self._remote_max\n===========below chunk 1===========\n # module: aioquic.connection\n class QuicConnection:\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n original_connection_id: Optional[bytes] = None,\n session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,\n session_ticket_handler: Optional[tls.SessionTicketHandler] = None,\n ) -> None:\n # offset: 2\n i_local = 0\n self._remote_max_stream_data_bidi_remote = 0\n self._remote_max_stream_data_uni = 0\n self._remote_max_streams_bidi = 0\n self._remote_max_streams_uni = 0\n self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}\n self._spin_bit = False\n self._spin_bit_peer = False\n self._spin_highest_pn = 0\n self._state = QuicConnectionState.FIRSTFLIGHT\n self._streams: Dict[int, QuicStream] = {}\n self._streams_blocked_bidi: List[QuicStream] = []\n self._streams_blocked_uni: List[QuicStream] = []\n self._version: Optional[int] = None\n \n # things to send\n self._close_pending = False\n self._ping_pending: List[int] = []\n self._probe_pending = False\n self._retire_connection_ids: List[int] = []\n self._streams_blocked_pending = False\n \n # callbacks\n self._session_ticket_fetcher = session_ticket_fetcher\n self._session_ticket_handler = session_ticket_handler\n \n # frame handlers\n self.__frame_handlers = [\n (self._handle_padding_frame, EPOCHS(\"IZHO\")),\n (self._handle_padding_frame, EPOCHS(\"ZO\")),\n (self._handle_ack_frame, EPOCHS(\"IHO\")),\n \n===========below chunk 2===========\n # module: aioquic.connection\n class QuicConnection:\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n original_connection_id: Optional[bytes] = None,\n session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,\n session_ticket_handler: Optional[tls.SessionTicketHandler] = None,\n ) -> None:\n # offset: 3\n self._handle_ack_frame, EPOCHS(\"IHO\")),\n (self._handle_reset_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stop_sending_frame, EPOCHS(\"ZO\")),\n (self._handle_crypto_frame, EPOCHS(\"IHO\")),\n (self._handle_new_token_frame, EPOCHS(\"O\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_max_data_frame, EPOCHS(\"ZO\")),\n (self._handle_max_stream_data_frame, EPOCHS(\"ZO\")),\n (self._handle_max_streams_bidi_frame, EPOCHS(\"ZO\")),\n (self._handle_max_streams_uni_frame, EPOCHS(\"ZO\")),\n (self._handle_data_blocked_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_data_blocked\n===========below chunk 3===========\n # module: aioquic.connection\n class QuicConnection:\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n original_connection_id: Optional[bytes] = None,\n session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,\n session_ticket_handler: Optional[tls.SessionTicketHandler] = None,\n ) -> None:\n # offset: 4\n , EPOCHS(\"ZO\")),\n (self._handle_streams_blocked_frame, EPOCHS(\"ZO\")),\n (self._handle_streams_blocked_frame, EPOCHS(\"ZO\")),\n (self._handle_new_connection_id_frame, EPOCHS(\"ZO\")),\n (self._handle_retire_connection_id_frame, EPOCHS(\"O\")),\n (self._handle_path_challenge_frame, EPOCHS(\"ZO\")),\n (self._handle_path_response_frame, EPOCHS(\"O\")),\n (self._handle_connection_close_frame, EPOCHS(\"IZHO\")),\n (self._handle_connection_close_frame, EPOCHS(\"ZO\")),\n ]\n \n "}}},{"rowIdx":2969,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection._handle_crypto_frame"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"091d169f28d7efeeac27d58a1dec1a6cef1d39a3"},"commit_message":{"kind":"string","value":"[recovery] send anti-deadlock packets more agressively"},"ground_truth":{"kind":"string","value":"<38>: self._loss.is_client_without_1rtt = False\n"},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def _handle_crypto_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n <0> \"\"\"\n <1> Handle a CRYPTO frame.\n <2> \"\"\"\n <3> stream = self._crypto_streams[context.epoch]\n <4> stream.add_frame(pull_crypto_frame(buf))\n <5> data = stream.pull_data()\n <6> if data:\n <7> # pass data to TLS layer\n <8> try:\n <9> self.tls.handle_message(data, self._crypto_buffers)\n<10> self._push_crypto_data()\n<11> except tls.Alert as exc:\n<12> raise QuicConnectionError(\n<13> error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description),\n<14> frame_type=QuicFrameType.CRYPTO,\n<15> reason_phrase=str(exc),\n<16> )\n<17> \n<18> # parse transport parameters\n<19> if (\n<20> not self._parameters_received\n<21> and self.tls.received_extensions is not None\n<22> ):\n<23> for ext_type, ext_data in self.tls.received_extensions:\n<24> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:\n<25> self._parse_transport_parameters(ext_data)\n<26> self._parameters_received = True\n<27> break\n<28> assert (\n<29> self._parameters_received\n<30> ), \"No QUIC transport parameters received\"\n<31> \n<32> # update current epoch\n<33> if not self._handshake_complete and self.tls.state in [\n<34> tls.State.CLIENT_POST_HANDSHAKE,\n<35> tls.State.SERVER_POST_HANDSHAKE,\n<36> ]:\n<37> self._handshake_complete = True\n<38> self._replenish_connection_ids()\n<39> self._events.append(\n<40> events.HandshakeCompleted(\n<41> alpn_protocol=self.tls.alpn_negotiated,\n<42> early_data_accepted=self.tls.early_data_accepted,"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_crypto_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n # offset: 1\n )\n )\n self._unblock_streams(is_unidirectional=False)\n self._unblock_streams(is_unidirectional=True)\n self._logger.info(\n \"ALPN negotiated protocol %s\", self.tls.alpn_negotiated\n )\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic.connection\n QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str)\n \n QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, time: float)\n \n at: aioquic.connection.QuicConnection\n _close_begin(is_initiator: bool, now: float) -> None\n \n _replenish_connection_ids() -> None\n \n _push_crypto_data() -> None\n \n _parse_transport_parameters(data: bytes, from_session_ticket: bool=False) -> None\n \n _unblock_streams(is_unidirectional: bool) -> None\n \n at: aioquic.connection.QuicConnection.__init__\n self._crypto_buffers: Dict[tls.Epoch, Buffer] = {}\n \n self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}\n \n self._events: Deque[events.Event] = deque()\n \n self._handshake_complete = False\n \n self._loss = QuicPacketRecovery(\n is_client_without_1rtt=self._is_client, send_probe=self._send_probe\n )\n \n self._parameters_received = False\n \n at: aioquic.connection.QuicConnection._initialize\n self.tls = tls.Context(is_client=self._is_client, logger=self._logger)\n \n self._crypto_buffers = {\n tls.Epoch.INITIAL: Buffer(capacity=4096),\n tls.Epoch.HANDSHAKE: Buffer(capacity=4096),\n tls.Epoch.ONE_RTT: Buffer(capacity=4096),\n }\n \n self._crypto_streams = {\n tls.Epoch.INITIAL: QuicStream(),\n tls.Epoch.HANDSHAKE: QuicStream(),\n tls.Epoch.ONE_RTT: QuicStream(),\n }\n \n \n===========unchanged ref 1===========\n at: aioquic.connection.QuicReceiveContext\n epoch: tls.Epoch\n \n host_cid: bytes\n \n network_path: QuicNetworkPath\n \n time: float\n \n at: aioquic.events\n HandshakeCompleted(alpn_protocol: Optional[str], early_data_accepted: bool, session_resumed: bool)\n \n at: aioquic.events.HandshakeCompleted\n alpn_protocol: Optional[str]\n \n early_data_accepted: bool\n \n session_resumed: bool\n \n at: aioquic.packet\n QuicErrorCode(x: Union[str, bytes, bytearray], base: int)\n QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n QuicFrameType(x: Union[str, bytes, bytearray], base: int)\n \n pull_crypto_frame(buf: Buffer) -> QuicStreamFrame\n \n at: aioquic.recovery.QuicPacketRecovery.__init__\n self.is_client_without_1rtt = is_client_without_1rtt\n \n at: aioquic.stream.QuicStream\n add_frame(frame: QuicStreamFrame) -> None\n \n pull_data() -> bytes\n \n at: aioquic.tls\n Alert(*args: object)\n \n State()\n \n ExtensionType(x: Union[str, bytes, bytearray], base: int)\n ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n at: aioquic.tls.Alert\n description: AlertDescription\n \n at: aioquic.tls.Context\n handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None\n \n at: aioquic.tls.Context.__init__\n self.alpn_negotiated: Optional[str] = None\n \n self.early_data_accepted = False\n \n self.received_extensions: Optional[List[Extension]] = None\n \n \n===========unchanged ref 2===========\n self.state = State.CLIENT_HANDSHAKE_START\n self.state = State.SERVER_EXPECT_CLIENT_HELLO\n \n at: aioquic.tls.Context._client_handle_encrypted_extensions\n self.alpn_negotiated = encrypted_extensions.alpn_protocol\n \n self.early_data_accepted = encrypted_extensions.early_data\n \n self.received_extensions = encrypted_extensions.other_extensions\n \n at: aioquic.tls.Context._server_handle_hello\n self.alpn_negotiated = negotiate(\n self.alpn_protocols,\n peer_hello.alpn_protocols,\n AlertHandshakeFailure(\"No common ALPN protocols\"),\n )\n \n self.received_extensions = peer_hello.other_extensions\n \n self.early_data_accepted = True\n \n at: aioquic.tls.Context._set_state\n self.state = state\n \n at: collections.deque\n append(x: _T) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n + def __init__(\n + self, is_client_without_1rtt: bool, send_probe: Callable[[], None]\n + ) -> None:\n - def __init__(self, send_probe: Callable[[], None]) -> None:\n self.ack_delay_exponent = 3\n + self.is_client_without_1rtt = is_client_without_1rtt\n self.max_ack_delay = 25 # ms\n self.spaces: List[QuicPacketSpace] = []\n \n # callbacks\n self._send_probe = send_probe\n \n # loss detection\n self._pto_count = 0\n self._rtt_initialized = False\n self._rtt_latest = 0.0\n self._rtt_min = math.inf\n self._rtt_smoothed = 0.0\n self._rtt_variance = 0.0\n self._time_of_last_sent_ack_eliciting_packet = 0.0\n \n # congestion control\n self.bytes_in_flight = 0\n self.congestion_window = K_INITIAL_WINDOW\n self._congestion_recovery_start_time = 0.0\n self._ssthresh = math.inf\n \n===========changed ref 1===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def get_loss_detection_time(self) -> float:\n # loss timer\n loss_space = self.get_earliest_loss_time()\n if loss_space is not None:\n return loss_space.loss_time\n \n # packet timer\n + if (\n + self.is_client_without_1rtt\n + or sum(space.ack_eliciting_in_flight for space in self.spaces) > 0\n - if sum(space.ack_eliciting_in_flight for space in self.spaces):\n + ):\n if not self._rtt_initialized:\n timeout = 2 * K_INITIAL_RTT * (2 ** self._pto_count)\n else:\n timeout = (\n self._rtt_smoothed\n + max(4 * self._rtt_variance, K_GRANULARITY)\n + self.max_ack_delay / 1000\n ) * (2 ** self._pto_count)\n return self._time_of_last_sent_ack_eliciting_packet + timeout\n \n return None\n "}}},{"rowIdx":2970,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection._write_handshake"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"091d169f28d7efeeac27d58a1dec1a6cef1d39a3"},"commit_message":{"kind":"string","value":"[recovery] send anti-deadlock packets more agressively"},"ground_truth":{"kind":"string","value":"<13>: builder.start_packet(packet_type, crypto, is_probe=self._probe_pending)\n builder.start_packet(packet_type, crypto)\n<25>: # PADDING (anti-deadlock packet)\n if self._probe_pending and self._is_client and epoch == tls.Epoch.HANDSHAKE:\n buf.push_bytes(bytes(builder.remaining_space))\n self._probe_pending = False\n \n"},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def _write_handshake(self, builder: QuicPacketBuilder, epoch: tls.Epoch) -> None:\n <0> crypto = self._cryptos[epoch]\n <1> if not crypto.send.is_valid():\n <2> return\n <3> \n <4> buf = builder.buffer\n <5> crypto_stream = self._crypto_streams[epoch]\n <6> space = self._spaces[epoch]\n <7> \n <8> while True:\n <9> if epoch == tls.Epoch.INITIAL:\n<10> packet_type = PACKET_TYPE_INITIAL\n<11> else:\n<12> packet_type = PACKET_TYPE_HANDSHAKE\n<13> builder.start_packet(packet_type, crypto)\n<14> \n<15> # ACK\n<16> if space.ack_at is not None:\n<17> builder.start_frame(QuicFrameType.ACK)\n<18> push_ack_frame(buf, space.ack_queue, 0)\n<19> space.ack_at = None\n<20> \n<21> # CRYPTO\n<22> if not crypto_stream.send_buffer_is_empty:\n<23> write_crypto_frame(builder=builder, space=space, stream=crypto_stream)\n<24> \n<25> if not builder.end_packet():\n<26> break\n<27> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.connection\n write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None\n \n at: aioquic.connection.QuicConnection.__init__\n self._cryptos: Dict[tls.Epoch, CryptoPair] = {}\n \n self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}\n \n self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}\n \n self._probe_pending = False\n \n at: aioquic.connection.QuicConnection._initialize\n self._cryptos = {\n tls.Epoch.INITIAL: CryptoPair(),\n tls.Epoch.ZERO_RTT: CryptoPair(),\n tls.Epoch.HANDSHAKE: CryptoPair(),\n tls.Epoch.ONE_RTT: CryptoPair(),\n }\n \n self._crypto_streams = {\n tls.Epoch.INITIAL: QuicStream(),\n tls.Epoch.HANDSHAKE: QuicStream(),\n tls.Epoch.ONE_RTT: QuicStream(),\n }\n \n self._spaces = {\n tls.Epoch.INITIAL: QuicPacketSpace(),\n tls.Epoch.HANDSHAKE: QuicPacketSpace(),\n tls.Epoch.ONE_RTT: QuicPacketSpace(),\n }\n \n at: aioquic.connection.QuicConnection._send_probe\n self._probe_pending = True\n \n at: aioquic.connection.QuicConnection._write_application\n self._probe_pending = False\n \n at: aioquic.connection.QuicConnection._write_handshake\n self._probe_pending = False\n \n at: aioquic.crypto.CryptoContext\n is_valid() -> bool\n \n at: aioquic.crypto.CryptoPair.__init__\n self.send = CryptoContext()\n \n at: aioquic.packet\n PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00\n \n PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20\n \n \n===========unchanged ref 1===========\n QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n QuicFrameType(x: Union[str, bytes, bytearray], base: int)\n \n push_ack_frame(buf: Buffer, rangeset: RangeSet, delay: int) -> None\n \n at: aioquic.packet_builder\n 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)\n \n at: aioquic.packet_builder.QuicPacketBuilder\n start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None\n \n start_packet(packet_type: int, crypto: CryptoPair, is_probe=False) -> None\n \n end_packet() -> bool\n \n at: aioquic.packet_builder.QuicPacketBuilder.__init__\n self.buffer = Buffer(PACKET_MAX_SIZE)\n \n at: aioquic.recovery.QuicPacketSpace.__init__\n self.ack_at: Optional[float] = None\n \n self.ack_queue = RangeSet()\n \n at: aioquic.stream.QuicStream.__init__\n self.send_buffer_is_empty = True\n \n at: aioquic.stream.QuicStream.get_frame\n self.send_buffer_is_empty = True\n \n at: aioquic.stream.QuicStream.on_data_delivery\n self.send_buffer_is_empty = False\n \n at: aioquic.stream.QuicStream.write\n self.send_buffer_is_empty = False\n \n at: aioquic.tls\n Epoch()\n \n \n===========changed ref 0===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_crypto_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n \"\"\"\n Handle a CRYPTO frame.\n \"\"\"\n stream = self._crypto_streams[context.epoch]\n stream.add_frame(pull_crypto_frame(buf))\n data = stream.pull_data()\n if data:\n # pass data to TLS layer\n try:\n self.tls.handle_message(data, self._crypto_buffers)\n self._push_crypto_data()\n except tls.Alert as exc:\n raise QuicConnectionError(\n error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description),\n frame_type=QuicFrameType.CRYPTO,\n reason_phrase=str(exc),\n )\n \n # parse transport parameters\n if (\n not self._parameters_received\n and self.tls.received_extensions is not None\n ):\n for ext_type, ext_data in self.tls.received_extensions:\n if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:\n self._parse_transport_parameters(ext_data)\n self._parameters_received = True\n break\n assert (\n self._parameters_received\n ), \"No QUIC transport parameters received\"\n \n # update current epoch\n if not self._handshake_complete and self.tls.state in [\n tls.State.CLIENT_POST_HANDSHAKE,\n tls.State.SERVER_POST_HANDSHAKE,\n ]:\n self._handshake_complete = True\n + self._loss.is_client_without_1rtt = False\n self._replenish_connection_ids()\n self._events.append(\n events.HandshakeCompleted(\n alpn_protocol=self.tls.alpn_negotiated,\n early_data_accepted=self.tls.early_data_accepted,\n session_resumed=self.tls.session_resumed,\n )\n )\n \n===========changed ref 1===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_crypto_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n # offset: 1\n _data_accepted,\n session_resumed=self.tls.session_resumed,\n )\n )\n self._unblock_streams(is_unidirectional=False)\n self._unblock_streams(is_unidirectional=True)\n self._logger.info(\n \"ALPN negotiated protocol %s\", self.tls.alpn_negotiated\n )\n \n===========changed ref 2===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n + def __init__(\n + self, is_client_without_1rtt: bool, send_probe: Callable[[], None]\n + ) -> None:\n - def __init__(self, send_probe: Callable[[], None]) -> None:\n self.ack_delay_exponent = 3\n + self.is_client_without_1rtt = is_client_without_1rtt\n self.max_ack_delay = 25 # ms\n self.spaces: List[QuicPacketSpace] = []\n \n # callbacks\n self._send_probe = send_probe\n \n # loss detection\n self._pto_count = 0\n self._rtt_initialized = False\n self._rtt_latest = 0.0\n self._rtt_min = math.inf\n self._rtt_smoothed = 0.0\n self._rtt_variance = 0.0\n self._time_of_last_sent_ack_eliciting_packet = 0.0\n \n # congestion control\n self.bytes_in_flight = 0\n self.congestion_window = K_INITIAL_WINDOW\n self._congestion_recovery_start_time = 0.0\n self._ssthresh = math.inf\n "}}},{"rowIdx":2971,"cells":{"path":{"kind":"string","value":"tests.test_recovery/QuicPacketRecoveryTest.setUp"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"091d169f28d7efeeac27d58a1dec1a6cef1d39a3"},"commit_message":{"kind":"string","value":"[recovery] send anti-deadlock packets more agressively"},"ground_truth":{"kind":"string","value":" <4>: self.recovery = QuicPacketRecovery(\n self.recovery = QuicPacketRecovery(send_probe=send_probe)\n <5>: is_client_without_1rtt=False, send_probe=send_probe\n )\n"},"main_code":{"kind":"string","value":" # module: tests.test_recovery\n class QuicPacketRecoveryTest(TestCase):\n def setUp(self):\n <0> self.INITIAL_SPACE = QuicPacketSpace()\n <1> self.HANDSHAKE_SPACE = QuicPacketSpace()\n <2> self.ONE_RTT_SPACE = QuicPacketSpace()\n <3> \n <4> self.recovery = QuicPacketRecovery(send_probe=send_probe)\n <5> self.recovery.spaces = [\n <6> self.INITIAL_SPACE,\n <7> self.HANDSHAKE_SPACE,\n <8> self.ONE_RTT_SPACE,\n <9> ]\n<10> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.recovery\n QuicPacketSpace()\n \n QuicPacketRecovery(is_client_without_1rtt: bool, send_probe: Callable[[], None])\n \n at: aioquic.recovery.QuicPacketRecovery.__init__\n self.spaces: List[QuicPacketSpace] = []\n \n at: tests.test_recovery\n send_probe()\n \n at: unittest.case.TestCase\n failureException = AssertionError\n \n longMessage = True\n \n maxDiff = 80*8\n \n _diffThreshold = 2**16\n \n setUp(self) -> None\n \n failUnlessEqual = assertEquals = _deprecate(assertEqual)\n \n failUnlessEqual = assertEquals = _deprecate(assertEqual)\n \n failIfEqual = assertNotEquals = _deprecate(assertNotEqual)\n \n failIfEqual = assertNotEquals = _deprecate(assertNotEqual)\n \n failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual)\n \n failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual)\n \n failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual)\n \n failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual)\n \n failUnless = assert_ = _deprecate(assertTrue)\n \n failUnless = assert_ = _deprecate(assertTrue)\n \n failUnlessRaises = _deprecate(assertRaises)\n \n failIf = _deprecate(assertFalse)\n \n assertRaisesRegexp = _deprecate(assertRaisesRegex)\n \n assertRegexpMatches = _deprecate(assertRegex)\n \n assertNotRegexpMatches = _deprecate(assertNotRegex)\n \n \n===========changed ref 0===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n + def __init__(\n + self, is_client_without_1rtt: bool, send_probe: Callable[[], None]\n + ) -> None:\n - def __init__(self, send_probe: Callable[[], None]) -> None:\n self.ack_delay_exponent = 3\n + self.is_client_without_1rtt = is_client_without_1rtt\n self.max_ack_delay = 25 # ms\n self.spaces: List[QuicPacketSpace] = []\n \n # callbacks\n self._send_probe = send_probe\n \n # loss detection\n self._pto_count = 0\n self._rtt_initialized = False\n self._rtt_latest = 0.0\n self._rtt_min = math.inf\n self._rtt_smoothed = 0.0\n self._rtt_variance = 0.0\n self._time_of_last_sent_ack_eliciting_packet = 0.0\n \n # congestion control\n self.bytes_in_flight = 0\n self.congestion_window = K_INITIAL_WINDOW\n self._congestion_recovery_start_time = 0.0\n self._ssthresh = math.inf\n \n===========changed ref 1===========\n # module: aioquic.recovery\n class QuicPacketRecovery:\n def get_loss_detection_time(self) -> float:\n # loss timer\n loss_space = self.get_earliest_loss_time()\n if loss_space is not None:\n return loss_space.loss_time\n \n # packet timer\n + if (\n + self.is_client_without_1rtt\n + or sum(space.ack_eliciting_in_flight for space in self.spaces) > 0\n - if sum(space.ack_eliciting_in_flight for space in self.spaces):\n + ):\n if not self._rtt_initialized:\n timeout = 2 * K_INITIAL_RTT * (2 ** self._pto_count)\n else:\n timeout = (\n self._rtt_smoothed\n + max(4 * self._rtt_variance, K_GRANULARITY)\n + self.max_ack_delay / 1000\n ) * (2 ** self._pto_count)\n return self._time_of_last_sent_ack_eliciting_packet + timeout\n \n return None\n \n===========changed ref 2===========\n # module: aioquic.connection\n class QuicConnection:\n def _write_handshake(self, builder: QuicPacketBuilder, epoch: tls.Epoch) -> None:\n crypto = self._cryptos[epoch]\n if not crypto.send.is_valid():\n return\n \n buf = builder.buffer\n crypto_stream = self._crypto_streams[epoch]\n space = self._spaces[epoch]\n \n while True:\n if epoch == tls.Epoch.INITIAL:\n packet_type = PACKET_TYPE_INITIAL\n else:\n packet_type = PACKET_TYPE_HANDSHAKE\n + builder.start_packet(packet_type, crypto, is_probe=self._probe_pending)\n - builder.start_packet(packet_type, crypto)\n \n # ACK\n if space.ack_at is not None:\n builder.start_frame(QuicFrameType.ACK)\n push_ack_frame(buf, space.ack_queue, 0)\n space.ack_at = None\n \n # CRYPTO\n if not crypto_stream.send_buffer_is_empty:\n write_crypto_frame(builder=builder, space=space, stream=crypto_stream)\n \n + # PADDING (anti-deadlock packet)\n + if self._probe_pending and self._is_client and epoch == tls.Epoch.HANDSHAKE:\n + buf.push_bytes(bytes(builder.remaining_space))\n + self._probe_pending = False\n + \n if not builder.end_packet():\n break\n \n===========changed ref 3===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_crypto_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n \"\"\"\n Handle a CRYPTO frame.\n \"\"\"\n stream = self._crypto_streams[context.epoch]\n stream.add_frame(pull_crypto_frame(buf))\n data = stream.pull_data()\n if data:\n # pass data to TLS layer\n try:\n self.tls.handle_message(data, self._crypto_buffers)\n self._push_crypto_data()\n except tls.Alert as exc:\n raise QuicConnectionError(\n error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description),\n frame_type=QuicFrameType.CRYPTO,\n reason_phrase=str(exc),\n )\n \n # parse transport parameters\n if (\n not self._parameters_received\n and self.tls.received_extensions is not None\n ):\n for ext_type, ext_data in self.tls.received_extensions:\n if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:\n self._parse_transport_parameters(ext_data)\n self._parameters_received = True\n break\n assert (\n self._parameters_received\n ), \"No QUIC transport parameters received\"\n \n # update current epoch\n if not self._handshake_complete and self.tls.state in [\n tls.State.CLIENT_POST_HANDSHAKE,\n tls.State.SERVER_POST_HANDSHAKE,\n ]:\n self._handshake_complete = True\n + self._loss.is_client_without_1rtt = False\n self._replenish_connection_ids()\n self._events.append(\n events.HandshakeCompleted(\n alpn_protocol=self.tls.alpn_negotiated,\n early_data_accepted=self.tls.early_data_accepted,\n session_resumed=self.tls.session_resumed,\n )\n )\n "}}},{"rowIdx":2972,"cells":{"path":{"kind":"string","value":"aioquic.packet_builder/QuicPacketBuilder.start_packet"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"c365ee7ac070a33e21106ea936f953afe1bd7b80"},"commit_message":{"kind":"string","value":"[connection] ensure we can send one packet when probe is needed"},"ground_truth":{"kind":"string","value":"<15>: if self.max_flight_bytes is not None:\n if self.max_flight_bytes is not None and not is_probe:\n"},"main_code":{"kind":"string","value":" # module: aioquic.packet_builder\n class QuicPacketBuilder:\n - def start_packet(\n - self, packet_type: int, crypto: CryptoPair, is_probe=False\n - ) -> None:\n + def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n <0> \"\"\"\n <1> Starts a new packet.\n <2> \"\"\"\n <3> buf = self.buffer\n <4> self._ack_eliciting = False\n <5> \n <6> # if there is too little space remaining, start a new datagram\n <7> # FIXME: the limit is arbitrary!\n <8> packet_start = buf.tell()\n <9> if self._buffer_capacity - packet_start < 128:\n<10> self._flush_current_datagram()\n<11> packet_start = 0\n<12> \n<13> # initialize datagram if needed\n<14> if self._datagram_init:\n<15> if self.max_flight_bytes is not None and not is_probe:\n<16> remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes\n<17> if remaining_flight_bytes < self._buffer_capacity:\n<18> self._buffer_capacity = remaining_flight_bytes\n<19> if self.max_total_bytes is not None:\n<20> remaining_total_bytes = self.max_total_bytes - self._total_bytes\n<21> if remaining_total_bytes < self._buffer_capacity:\n<22> self._buffer_capacity = remaining_total_bytes\n<23> self._datagram_init = False\n<24> \n<25> # calculate header size\n<26> packet_long_header = is_long_header(packet_type)\n<27> if packet_long_header:\n<28> header_size = 10 + len(self._peer_cid) + len(self._host_cid)\n<29> if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL:\n<30> token_length = len(self._peer_token)\n<31> header_size += size_uint_var(token_length) + token_length\n<32> else:\n<33> header_size = 3 + len(self._peer_cid)\n "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n - def start_packet(\n - self, packet_type: int, crypto: CryptoPair, is_probe=False\n - ) -> None:\n + def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n # offset: 1\n # check we have enough space\n if packet_start + header_size >= self._buffer_capacity:\n raise QuicPacketBuilderStop\n \n # determine ack epoch\n if packet_type == PACKET_TYPE_INITIAL:\n epoch = Epoch.INITIAL\n elif packet_type == PACKET_TYPE_HANDSHAKE:\n epoch = Epoch.HANDSHAKE\n else:\n epoch = Epoch.ONE_RTT\n \n self._header_size = header_size\n self._packet = QuicSentPacket(\n epoch=epoch,\n in_flight=False,\n is_ack_eliciting=False,\n is_crypto_packet=False,\n packet_number=self._packet_number,\n )\n self._packet_crypto = crypto\n self._packet_long_header = packet_long_header\n self._packet_start = packet_start\n self._packet_type = packet_type\n \n buf.seek(self._packet_start + self._header_size)\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer.Buffer\n seek(pos: int) -> None\n \n tell() -> int\n \n at: aioquic.buffer\n size_uint_var(value: int) -> int\n \n at: aioquic.crypto\n CryptoPair()\n \n at: aioquic.packet\n PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00\n \n PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20\n \n PACKET_TYPE_MASK = 0xF0\n \n is_long_header(first_byte: int) -> bool\n \n at: aioquic.packet_builder\n QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field(\n default_factory=list\n ))\n \n QuicPacketBuilderStop(*args: object)\n \n at: aioquic.packet_builder.QuicPacketBuilder\n _flush_current_datagram() -> None\n \n at: aioquic.packet_builder.QuicPacketBuilder.__init__\n self.max_flight_bytes: Optional[int] = None\n \n self.max_total_bytes: Optional[int] = None\n \n self._host_cid = host_cid\n \n self._peer_cid = peer_cid\n \n self._peer_token = peer_token\n \n self._ack_eliciting = False\n \n self._datagram_init = True\n \n self._flight_bytes = 0\n \n self._total_bytes = 0\n \n self._header_size = 0\n \n self._packet: Optional[QuicSentPacket] = None\n \n self._packet_crypto: Optional[CryptoPair] = None\n \n self._packet_long_header = False\n \n self._packet_number = packet_number\n \n self._packet_start = 0\n \n \n===========unchanged ref 1===========\n self._packet_type = 0\n \n self.buffer = Buffer(PACKET_MAX_SIZE)\n \n self._buffer_capacity = PACKET_MAX_SIZE\n \n at: aioquic.packet_builder.QuicPacketBuilder._flush_current_datagram\n self._datagram_init = True\n \n self._flight_bytes += datagram_bytes\n \n self._total_bytes += datagram_bytes\n \n at: aioquic.packet_builder.QuicPacketBuilder.end_packet\n self._packet_number += 1\n \n self._packet = None\n \n at: aioquic.packet_builder.QuicPacketBuilder.start_frame\n self._ack_eliciting = True\n \n at: aioquic.packet_builder.QuicSentPacket\n epoch: Epoch\n \n in_flight: bool\n \n is_ack_eliciting: bool\n \n is_crypto_packet: bool\n \n packet_number: int\n \n sent_time: Optional[float] = None\n \n sent_bytes: int = 0\n \n delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(\n default_factory=list\n )\n \n at: aioquic.tls\n Epoch()\n \n "}}},{"rowIdx":2973,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection.datagrams_to_send"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"c365ee7ac070a33e21106ea936f953afe1bd7b80"},"commit_message":{"kind":"string","value":"[connection] ensure we can send one packet when probe is needed"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]:\n <0> \"\"\"\n <1> Return a list of `(data, addr)` tuples of datagrams which need to be\n <2> sent, and the network address to which they need to be sent.\n <3> \"\"\"\n <4> network_path = self._network_paths[0]\n <5> \n <6> if self._state in END_STATES:\n <7> return []\n <8> \n <9> # build datagrams\n<10> builder = QuicPacketBuilder(\n<11> host_cid=self.host_cid,\n<12> packet_number=self._packet_number,\n<13> pad_first_datagram=(\n<14> self._is_client and self._state == QuicConnectionState.FIRSTFLIGHT\n<15> ),\n<16> peer_cid=self._peer_cid,\n<17> peer_token=self._peer_token,\n<18> spin_bit=self._spin_bit,\n<19> version=self._version,\n<20> )\n<21> if self._close_pending:\n<22> for epoch, packet_type in (\n<23> (tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT),\n<24> (tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE),\n<25> (tls.Epoch.INITIAL, PACKET_TYPE_INITIAL),\n<26> ):\n<27> crypto = self._cryptos[epoch]\n<28> if crypto.send.is_valid():\n<29> builder.start_packet(packet_type, crypto)\n<30> write_close_frame(\n<31> builder=builder,\n<32> error_code=self._close_event.error_code,\n<33> frame_type=self._close_event.frame_type,\n<34> reason_phrase=self._close_event.reason_phrase,\n<35> )\n<36> builder.end_packet()\n<37> self._close_pending = False\n<38> break\n<39> self._close_begin(is_initiator=True, now=now)\n<40> else:\n<41> # congestion control"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.connection\n class QuicConnection:\n def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]:\n # offset: 1\n self._loss.congestion_window - self._loss.bytes_in_flight\n )\n if not network_path.is_validated:\n # limit data on un-validated network paths\n builder.max_total_bytes = (\n network_path.bytes_received * 3 - network_path.bytes_sent\n )\n \n try:\n if not self._handshake_confirmed:\n for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]:\n self._write_handshake(builder, epoch)\n self._write_application(builder, network_path, now)\n except QuicPacketBuilderStop:\n pass\n \n datagrams, packets = builder.flush()\n \n if datagrams:\n self._packet_number = builder.packet_number\n \n # register packets\n sent_handshake = False\n for packet in packets:\n packet.sent_time = now\n self._loss.on_packet_sent(\n packet=packet, space=self._spaces[packet.epoch]\n )\n if packet.epoch == tls.Epoch.HANDSHAKE:\n sent_handshake = True\n \n # check if we can discard initial keys\n if sent_handshake and self._is_client:\n self._discard_epoch(tls.Epoch.INITIAL)\n \n # return datagrams to send and the destination network address\n ret = []\n for datagram in datagrams:\n network_path.bytes_sent += len(datagram)\n ret.append((datagram, network_path.addr))\n return ret\n \n \n===========unchanged ref 0===========\n at: aioquic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n certificate: Any = None\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n private_key: Any = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[tls.SessionTicket] = None\n \n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_19,\n QuicProtocolVersion.DRAFT_20,\n ]\n )\n \n at: aioquic.connection\n NetworkAddress = Any\n \n write_close_frame(builder: QuicPacketBuilder, error_code: int, frame_type: Optional[int], reason_phrase: str) -> None\n \n QuicConnectionState()\n \n END_STATES = frozenset(\n [\n QuicConnectionState.CLOSING,\n QuicConnectionState.DRAINING,\n QuicConnectionState.TERMINATED,\n ]\n )\n \n at: aioquic.connection.QuicConnection\n _close_begin(is_initiator: bool, now: float) -> None\n \n _connect(now: float) -> None\n \n at: aioquic.connection.QuicConnection.__init__\n self._configuration = configuration\n \n self._is_client = configuration.is_client\n \n self._close_event: Optional[events.ConnectionTerminated] = None\n \n self._cryptos: Dict[tls.Epoch, CryptoPair] = {}\n \n self.host_cid = self._host_cids[0].cid\n \n self._loss = QuicPacketRecovery(\n is_client_without_1rtt=self._is_client, send_probe=self._send_probe\n )\n \n self._network_paths: List[QuicNetworkPath] = []\n \n self._packet_number = 0\n \n self._peer_cid = os.urandom(8)\n \n self._peer_token = b\"\"\n \n \n===========unchanged ref 1===========\n self._spin_bit = False\n \n self._state = QuicConnectionState.FIRSTFLIGHT\n \n self._version: Optional[int] = None\n \n self._close_pending = False\n \n self._probe_pending = False\n \n at: aioquic.connection.QuicConnection._handle_connection_close_frame\n self._close_event = events.ConnectionTerminated(\n error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase\n )\n \n at: aioquic.connection.QuicConnection._initialize\n self._cryptos = {\n tls.Epoch.INITIAL: CryptoPair(),\n tls.Epoch.ZERO_RTT: CryptoPair(),\n tls.Epoch.HANDSHAKE: CryptoPair(),\n tls.Epoch.ONE_RTT: CryptoPair(),\n }\n \n self._packet_number = 0\n \n at: aioquic.connection.QuicConnection._send_probe\n self._probe_pending = True\n \n at: aioquic.connection.QuicConnection._set_state\n self._state = state\n \n at: aioquic.connection.QuicConnection._write_application\n self._probe_pending = False\n \n at: aioquic.connection.QuicConnection._write_handshake\n self._probe_pending = False\n \n at: aioquic.connection.QuicConnection.change_connection_id\n self._peer_cid = connection_id.cid\n \n at: aioquic.connection.QuicConnection.close\n self._close_event = events.ConnectionTerminated(\n error_code=error_code,\n frame_type=frame_type,\n reason_phrase=reason_phrase,\n )\n \n self._close_pending = True\n \n at: aioquic.connection.QuicConnection.connect\n self._network_paths = [QuicNetworkPath(addr, is_validated=True)]\n \n \n===========unchanged ref 2===========\n at: aioquic.connection.QuicConnection.handle_timer\n self._close_event = events.ConnectionTerminated(\n error_code=QuicErrorCode.INTERNAL_ERROR,\n frame_type=None,\n reason_phrase=\"Idle timeout\",\n )\n \n at: aioquic.connection.QuicConnection.receive_datagram\n self._close_event = events.ConnectionTerminated(\n error_code=QuicErrorCode.INTERNAL_ERROR,\n frame_type=None,\n reason_phrase=\"Could not find a common protocol version\",\n )\n \n self._version = QuicProtocolVersion(header.version)\n self._version = QuicProtocolVersion(max(common))\n \n self._peer_cid = header.source_cid\n \n self._peer_token = header.token\n \n self._network_paths = [network_path]\n \n self._spin_bit = self._spin_bit_peer\n self._spin_bit = not self._spin_bit_peer\n \n self.host_cid = context.host_cid\n \n at: aioquic.connection.QuicNetworkPath\n addr: NetworkAddress\n \n bytes_received: int = 0\n \n bytes_sent: int = 0\n \n is_validated: bool = False\n \n local_challenge: Optional[bytes] = None\n \n remote_challenge: Optional[bytes] = None\n \n at: aioquic.crypto.CryptoContext\n is_valid() -> bool\n \n at: aioquic.crypto.CryptoPair.__init__\n self.send = CryptoContext()\n \n at: aioquic.events.ConnectionTerminated\n error_code: int\n \n frame_type: Optional[int]\n \n reason_phrase: str\n \n at: aioquic.packet\n PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00\n \n PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20\n \n PACKET_TYPE_ONE_RTT = PACKET_FIXED_BIT\n \n "}}},{"rowIdx":2974,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection._write_application"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"c365ee7ac070a33e21106ea936f953afe1bd7b80"},"commit_message":{"kind":"string","value":"[connection] ensure we can send one packet when probe is needed"},"ground_truth":{"kind":"string","value":"<16>: builder.start_packet(packet_type, crypto)\n builder.start_packet(packet_type, crypto, is_probe=self._probe_pending)\n"},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def _write_application(\n self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float\n ) -> None:\n <0> crypto_stream: Optional[QuicStream] = None\n <1> if self._cryptos[tls.Epoch.ONE_RTT].send.is_valid():\n <2> crypto = self._cryptos[tls.Epoch.ONE_RTT]\n <3> crypto_stream = self._crypto_streams[tls.Epoch.ONE_RTT]\n <4> packet_type = PACKET_TYPE_ONE_RTT\n <5> elif self._cryptos[tls.Epoch.ZERO_RTT].send.is_valid():\n <6> crypto = self._cryptos[tls.Epoch.ZERO_RTT]\n <7> packet_type = PACKET_TYPE_ZERO_RTT\n <8> else:\n <9> return\n<10> space = self._spaces[tls.Epoch.ONE_RTT]\n<11> \n<12> buf = builder.buffer\n<13> \n<14> while True:\n<15> # write header\n<16> builder.start_packet(packet_type, crypto, is_probe=self._probe_pending)\n<17> \n<18> if self._handshake_complete:\n<19> # ACK\n<20> if space.ack_at is not None and space.ack_at <= now:\n<21> builder.start_frame(\n<22> QuicFrameType.ACK,\n<23> self._on_ack_delivery,\n<24> (space, space.largest_received_packet),\n<25> )\n<26> push_ack_frame(buf, space.ack_queue, 0)\n<27> space.ack_at = None\n<28> \n<29> # PATH CHALLENGE\n<30> if (\n<31> not network_path.is_validated\n<32> and network_path.local_challenge is None\n<33> ):\n<34> self._logger.info(\n<35> \"Network path %s sending challenge\", network_path.addr\n<36> )\n<37> network_path.local_challenge = os.urandom(8)\n<38> builder.start_frame(QuicFrameType.PATH_CHALLENG"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.connection\n class QuicConnection:\n def _write_application(\n self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float\n ) -> None:\n # offset: 1\n buf.push_bytes(network_path.local_challenge)\n \n # PATH RESPONSE\n if network_path.remote_challenge is not None:\n builder.start_frame(QuicFrameType.PATH_RESPONSE)\n buf.push_bytes(network_path.remote_challenge)\n network_path.remote_challenge = None\n \n # NEW_CONNECTION_ID\n for connection_id in self._host_cids:\n if not connection_id.was_sent:\n builder.start_frame(\n QuicFrameType.NEW_CONNECTION_ID,\n self._on_new_connection_id_delivery,\n (connection_id,),\n )\n push_new_connection_id_frame(\n buf,\n connection_id.sequence_number,\n connection_id.cid,\n connection_id.stateless_reset_token,\n )\n connection_id.was_sent = True\n self._events.append(\n events.ConnectionIdIssued(connection_id=connection_id.cid)\n )\n \n # RETIRE_CONNECTION_ID\n while self._retire_connection_ids:\n sequence_number = self._retire_connection_ids.pop(0)\n builder.start_frame(\n QuicFrameType.RETIRE_CONNECTION_ID,\n self._on_retire_connection_id_delivery,\n (sequence_number,),\n )\n buf.push_uint_var(sequence_number)\n \n # STREAMS_BLOCKED\n if self._streams_blocked_pending:\n if self._streams_blocked_bidi:\n builder.start_frame(QuicFrameType.STREAMS_BLOCKED_BIDI)\n buf.push_uint_var(self._remote_max_streams_bidi)\n if self._streams_blocked_uni:\n builder.start_frame(QuicFrame\n===========below chunk 1===========\n # module: aioquic.connection\n class QuicConnection:\n def _write_application(\n self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float\n ) -> None:\n # offset: 2\n max_streams_bidi)\n if self._streams_blocked_uni:\n builder.start_frame(QuicFrameType.STREAMS_BLOCKED_UNI)\n buf.push_uint_var(self._remote_max_streams_uni)\n self._streams_blocked_pending = False\n \n # connection-level limits\n self._write_connection_limits(builder=builder, space=space)\n \n # stream-level limits\n for stream in self._streams.values():\n self._write_stream_limits(builder=builder, space=space, stream=stream)\n \n # PING (user-request)\n if self._ping_pending:\n self._logger.info(\"Sending PING in packet %d\", builder.packet_number)\n builder.start_frame(\n QuicFrameType.PING,\n self._on_ping_delivery,\n (tuple(self._ping_pending),),\n )\n self._ping_pending.clear()\n \n # PING (probe)\n if self._probe_pending:\n self._logger.info(\"Sending probe\")\n builder.start_frame(QuicFrameType.PING)\n self._probe_pending = False\n \n # CRYPTO\n if crypto_stream is not None and not crypto_stream.send_buffer_is_empty:\n write_crypto_frame(builder=builder, space=space, stream=crypto_stream)\n \n for stream in self._streams.values():\n # STREAM\n if not stream.is_blocked and not stream.send_buffer_is_empty:\n self._remote_max_data_used += write_stream_frame(\n builder=builder,\n space=space,\n stream=stream,\n max_offset=min(\n stream\n===========below chunk 2===========\n # module: aioquic.connection\n class QuicConnection:\n def _write_application(\n self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float\n ) -> None:\n # offset: 3\n _highest\n + self._remote_max_data\n - self._remote_max_data_used,\n stream.max_stream_data_remote,\n ),\n )\n \n if not builder.end_packet():\n break\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer.Buffer\n push_bytes(value: bytes) -> None\n \n push_uint_var(value: int) -> None\n \n at: aioquic.connection\n write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None\n \n write_stream_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream, max_offset: int) -> int\n \n QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None)\n \n at: aioquic.connection.QuicConnection\n _on_ack_delivery(delivery: QuicDeliveryState, space: QuicPacketSpace, highest_acked: int) -> None\n \n _on_new_connection_id_delivery(delivery: QuicDeliveryState, connection_id: QuicConnectionId) -> None\n \n _on_ping_delivery(delivery: QuicDeliveryState, uids: Sequence[int]) -> None\n \n _on_retire_connection_id_delivery(delivery: QuicDeliveryState, sequence_number: int) -> None\n \n _write_connection_limits(builder: QuicPacketBuilder, space: QuicPacketSpace) -> None\n \n _write_stream_limits(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None\n \n at: aioquic.connection.QuicConnection.__init__\n self._cryptos: Dict[tls.Epoch, CryptoPair] = {}\n \n self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}\n \n self._events: Deque[events.Event] = deque()\n \n self._handshake_complete = False\n \n "}}},{"rowIdx":2975,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection._write_handshake"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"c365ee7ac070a33e21106ea936f953afe1bd7b80"},"commit_message":{"kind":"string","value":"[connection] ensure we can send one packet when probe is needed"},"ground_truth":{"kind":"string","value":"<13>: builder.start_packet(packet_type, crypto)\n builder.start_packet(packet_type, crypto, is_probe=self._probe_pending)\n"},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def _write_handshake(self, builder: QuicPacketBuilder, epoch: tls.Epoch) -> None:\n <0> crypto = self._cryptos[epoch]\n <1> if not crypto.send.is_valid():\n <2> return\n <3> \n <4> buf = builder.buffer\n <5> crypto_stream = self._crypto_streams[epoch]\n <6> space = self._spaces[epoch]\n <7> \n <8> while True:\n <9> if epoch == tls.Epoch.INITIAL:\n<10> packet_type = PACKET_TYPE_INITIAL\n<11> else:\n<12> packet_type = PACKET_TYPE_HANDSHAKE\n<13> builder.start_packet(packet_type, crypto, is_probe=self._probe_pending)\n<14> \n<15> # ACK\n<16> if space.ack_at is not None:\n<17> builder.start_frame(QuicFrameType.ACK)\n<18> push_ack_frame(buf, space.ack_queue, 0)\n<19> space.ack_at = None\n<20> \n<21> # CRYPTO\n<22> if not crypto_stream.send_buffer_is_empty:\n<23> write_crypto_frame(builder=builder, space=space, stream=crypto_stream)\n<24> \n<25> # PADDING (anti-deadlock packet)\n<26> if self._probe_pending and self._is_client and epoch == tls.Epoch.HANDSHAKE:\n<27> buf.push_bytes(bytes(builder.remaining_space))\n<28> self._probe_pending = False\n<29> \n<30> if not builder.end_packet():\n<31> break\n<32> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.connection\n write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None\n \n at: aioquic.connection.QuicConnection.__init__\n self._cryptos: Dict[tls.Epoch, CryptoPair] = {}\n \n self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}\n \n self._remote_max_data_used = 0\n \n self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}\n \n at: aioquic.connection.QuicConnection._initialize\n self._cryptos = {\n tls.Epoch.INITIAL: CryptoPair(),\n tls.Epoch.ZERO_RTT: CryptoPair(),\n tls.Epoch.HANDSHAKE: CryptoPair(),\n tls.Epoch.ONE_RTT: CryptoPair(),\n }\n \n self._crypto_streams = {\n tls.Epoch.INITIAL: QuicStream(),\n tls.Epoch.HANDSHAKE: QuicStream(),\n tls.Epoch.ONE_RTT: QuicStream(),\n }\n \n self._spaces = {\n tls.Epoch.INITIAL: QuicPacketSpace(),\n tls.Epoch.HANDSHAKE: QuicPacketSpace(),\n tls.Epoch.ONE_RTT: QuicPacketSpace(),\n }\n \n at: aioquic.connection.QuicConnection._write_application\n self._remote_max_data_used += write_stream_frame(\n builder=builder,\n space=space,\n stream=stream,\n max_offset=min(\n stream._send_highest\n + self._remote_max_data\n - self._remote_max_data_used,\n stream.max_stream_data_remote,\n ),\n )\n \n at: aioquic.crypto.CryptoContext\n is_valid() -> bool\n \n at: aioquic.crypto.CryptoPair.__init__\n self.send = CryptoContext()\n \n at: aioquic.packet\n PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00\n \n \n===========unchanged ref 1===========\n PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20\n \n QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n QuicFrameType(x: Union[str, bytes, bytearray], base: int)\n \n push_ack_frame(buf: Buffer, rangeset: RangeSet, delay: int) -> None\n \n at: aioquic.packet_builder\n 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)\n \n at: aioquic.packet_builder.QuicPacketBuilder\n start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None\n \n start_packet(packet_type: int, crypto: CryptoPair) -> None\n \n end_packet() -> bool\n \n at: aioquic.packet_builder.QuicPacketBuilder.__init__\n self.buffer = Buffer(PACKET_MAX_SIZE)\n \n at: aioquic.recovery.QuicPacketSpace.__init__\n self.ack_at: Optional[float] = None\n \n self.ack_queue = RangeSet()\n \n at: aioquic.stream.QuicStream.__init__\n self.send_buffer_is_empty = True\n \n at: aioquic.stream.QuicStream.get_frame\n self.send_buffer_is_empty = True\n \n at: aioquic.stream.QuicStream.on_data_delivery\n self.send_buffer_is_empty = False\n \n at: aioquic.stream.QuicStream.write\n self.send_buffer_is_empty = False\n \n at: aioquic.tls\n Epoch()\n \n \n===========changed ref 0===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n - def start_packet(\n - self, packet_type: int, crypto: CryptoPair, is_probe=False\n - ) -> None:\n + def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n \"\"\"\n Starts a new packet.\n \"\"\"\n buf = self.buffer\n self._ack_eliciting = False\n \n # if there is too little space remaining, start a new datagram\n # FIXME: the limit is arbitrary!\n packet_start = buf.tell()\n if self._buffer_capacity - packet_start < 128:\n self._flush_current_datagram()\n packet_start = 0\n \n # initialize datagram if needed\n if self._datagram_init:\n + if self.max_flight_bytes is not None:\n - if self.max_flight_bytes is not None and not is_probe:\n remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes\n if remaining_flight_bytes < self._buffer_capacity:\n self._buffer_capacity = remaining_flight_bytes\n if self.max_total_bytes is not None:\n remaining_total_bytes = self.max_total_bytes - self._total_bytes\n if remaining_total_bytes < self._buffer_capacity:\n self._buffer_capacity = remaining_total_bytes\n self._datagram_init = False\n \n # calculate header size\n packet_long_header = is_long_header(packet_type)\n if packet_long_header:\n header_size = 10 + len(self._peer_cid) + len(self._host_cid)\n if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL:\n token_length = len(self._peer_token)\n header_size += size_uint_var(token_length) + token_length\n else:\n header_size = 3 + len(self._peer_cid)\n \n # check we have enough space\n if packet_start + header_size\n===========changed ref 1===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n - def start_packet(\n - self, packet_type: int, crypto: CryptoPair, is_probe=False\n - ) -> None:\n + def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n # offset: 1\n = 3 + len(self._peer_cid)\n \n # check we have enough space\n if packet_start + header_size >= self._buffer_capacity:\n raise QuicPacketBuilderStop\n \n # determine ack epoch\n if packet_type == PACKET_TYPE_INITIAL:\n epoch = Epoch.INITIAL\n elif packet_type == PACKET_TYPE_HANDSHAKE:\n epoch = Epoch.HANDSHAKE\n else:\n epoch = Epoch.ONE_RTT\n \n self._header_size = header_size\n self._packet = QuicSentPacket(\n epoch=epoch,\n in_flight=False,\n is_ack_eliciting=False,\n is_crypto_packet=False,\n packet_number=self._packet_number,\n )\n self._packet_crypto = crypto\n self._packet_long_header = packet_long_header\n self._packet_start = packet_start\n self._packet_type = packet_type\n \n buf.seek(self._packet_start + self._header_size)\n "}}},{"rowIdx":2976,"cells":{"path":{"kind":"string","value":"examples.http3-server/HttpServer.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"f797370e721ad2f72a3366ac81e0e4df2136d691"},"commit_message":{"kind":"string","value":"[examples] wire up timers for HTTP/3 server example"},"ground_truth":{"kind":"string","value":" <6>: self._timer: Dict[QuicConnection, Tuple[asyncio.TimerHandle, float]] = {}\n"},"main_code":{"kind":"string","value":" # module: examples.http3-server\n class HttpServer(asyncio.DatagramProtocol):\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n session_ticket_fetcher: Optional[SessionTicketFetcher] = None,\n session_ticket_handler: Optional[SessionTicketHandler] = None,\n stateless_retry: bool = False,\n ) -> None:\n <0> self._connections: Dict[bytes, QuicConnection] = {}\n <1> self._configuration = configuration\n <2> self._http: Dict[QuicConnection, HttpConnection] = {}\n <3> self._loop = asyncio.get_event_loop()\n <4> self._session_ticket_fetcher = session_ticket_fetcher\n <5> self._session_ticket_handler = session_ticket_handler\n <6> self._transport: Optional[asyncio.DatagramTransport] = None\n <7> \n <8> if stateless_retry:\n <9> self._retry = QuicRetryTokenHandler()\n<10> else:\n<11> self._retry = None\n<12> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: _asyncio\n get_event_loop()\n \n at: aioquic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_19,\n QuicProtocolVersion.DRAFT_20,\n ]\n ))\n \n at: aioquic.connection\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.retry\n QuicRetryTokenHandler()\n \n at: aioquic.tls\n SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]]\n \n SessionTicketHandler = Callable[[SessionTicket], None]\n \n at: asyncio.events\n TimerHandle(when: float, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop, context: Optional[Context]=...)\n \n get_event_loop() -> AbstractEventLoop\n \n at: asyncio.protocols\n DatagramProtocol()\n \n at: asyncio.transports\n DatagramTransport(extra: Optional[Mapping[Any, Any]]=...)\n \n at: examples.http3-server\n HttpConnection = Union[H0Connection, H3Connection]\n \n at: examples.http3-server.HttpServer.connection_made\n self._transport = cast(asyncio.DatagramTransport, transport)\n \n at: typing\n Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')\n \n Dict = _alias(dict, 2, inst=False, name='Dict')\n \n "}}},{"rowIdx":2977,"cells":{"path":{"kind":"string","value":"examples.http3-server/HttpServer._consume_events"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"f797370e721ad2f72a3366ac81e0e4df2136d691"},"commit_message":{"kind":"string","value":"[examples] wire up timers for HTTP/3 server example"},"ground_truth":{"kind":"string","value":" <3>: if isinstance(event, aioquic.events.ConnectionTerminated):\n # remove the connection\n for cid, conn in list(self._connections.items()):\n if conn == connection:\n del self._connections[cid]\n self._http.pop(connection, None)\n self._timer.pop(connection, None)\n return\n elif isinstance(event, aioquic.events.HandshakeCompleted):\n if isinstance(event, aioquic.events.HandshakeCompleted):\n<27>: \"\"\"\n<28>: next_timer_at = connection.get_timer()\n timer_at = connection.get_timer()\n<29>: (timer, timer_at) = self._timer.get(connection, (None, None))\n if timer is not None and timer_at != next_timer_at:\n if self._timer is not None and self._timer_at != timer_at:\n<30>: timer.cancel()\n self._timer.cancel()\n<31>: timer = None\n self._timer = None\n<32>: if timer is None and timer_at is not None:\n if self._timer is None and timer_at is not None:\n<33>: timer = self._loop.call_at(\n next_timer_at, partial("},"main_code":{"kind":"string","value":" # module: examples.http3-server\n class HttpServer(asyncio.DatagramProtocol):\n def _consume_events(self, connection: QuicConnection) -> None:\n <0> # process events\n <1> event = connection.next_event()\n <2> while event is not None:\n <3> if isinstance(event, aioquic.events.HandshakeCompleted):\n <4> if event.alpn_protocol == \"h3-20\":\n <5> self._http[connection] = H3Connection(connection)\n <6> elif event.alpn_protocol == \"hq-20\":\n <7> self._http[connection] = H0Connection(connection)\n <8> elif isinstance(event, aioquic.events.ConnectionIdIssued):\n <9> self._connections[event.connection_id] = connection\n<10> elif isinstance(event, aioquic.events.ConnectionIdRetired):\n<11> assert self._connections[event.connection_id] == connection\n<12> del self._connections[event.connection_id]\n<13> \n<14> #  pass event to the HTTP layer\n<15> http = self._http.get(connection)\n<16> if http is not None:\n<17> for http_event in http.handle_event(event):\n<18> handle_http_event(http, http_event)\n<19> \n<20> event = connection.next_event()\n<21> \n<22> # send datagrams\n<23> for data, addr in connection.datagrams_to_send(now=self._loop.time()):\n<24> self._transport.sendto(data, addr)\n<25> \n<26> # re-arm timer\n<27> \"\"\"\n<28> timer_at = connection.get_timer()\n<29> if self._timer is not None and self._timer_at != timer_at:\n<30> self._timer.cancel()\n<31> self._timer = None\n<32> if self._timer is None and timer_at is not None:\n<33> self._timer = self._loop.call_at(timer_at, self._handle_timer)\n<34> self._timer_at = timer_at\n<35> \"\"\"\n<36> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.connection\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.connection.QuicConnection\n datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]]\n \n next_event() -> Optional[events.Event]\n \n at: aioquic.events\n ConnectionIdIssued(connection_id: bytes)\n \n ConnectionIdRetired(connection_id: bytes)\n \n ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str)\n \n HandshakeCompleted(alpn_protocol: Optional[str], early_data_accepted: bool, session_resumed: bool)\n \n at: aioquic.h3.connection\n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection\n handle_event(event: aioquic.events.Event) -> List[Event]\n \n at: asyncio.events.AbstractEventLoop\n time() -> float\n \n at: asyncio.transports.DatagramTransport\n __slots__ = ()\n \n sendto(data: Any, addr: Optional[_Address]=...) -> None\n \n at: examples.http3-server\n H0Connection(quic: QuicConnection)\n \n handle_http_event(connection: HttpConnection, event: aioquic.h3.events.Event) -> None\n \n at: examples.http3-server.H0Connection\n handle_event(event: aioquic.events.Event)\n \n at: examples.http3-server.HttpServer.__init__\n self._connections: Dict[bytes, QuicConnection] = {}\n \n self._http: Dict[QuicConnection, HttpConnection] = {}\n \n self._loop = asyncio.get_event_loop()\n \n self._timer: Dict[QuicConnection, Tuple[asyncio.TimerHandle, float]] = {}\n \n \n===========unchanged ref 1===========\n self._transport: Optional[asyncio.DatagramTransport] = None\n \n at: examples.http3-server.HttpServer.connection_made\n self._transport = cast(asyncio.DatagramTransport, transport)\n \n at: examples.http3-server.HttpServer.datagram_received\n connection = self._connections.get(header.destination_cid, None)\n connection = QuicConnection(\n configuration=self._configuration,\n original_connection_id=original_connection_id,\n session_ticket_fetcher=self._session_ticket_fetcher,\n session_ticket_handler=self._session_ticket_handler,\n )\n \n at: typing.Mapping\n get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]\n get(key: _KT) -> Optional[_VT_co]\n \n at: typing.MutableMapping\n pop(key: _KT) -> _VT\n pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T]\n \n \n===========changed ref 0===========\n # module: examples.http3-server\n class HttpServer(asyncio.DatagramProtocol):\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n session_ticket_fetcher: Optional[SessionTicketFetcher] = None,\n session_ticket_handler: Optional[SessionTicketHandler] = None,\n stateless_retry: bool = False,\n ) -> None:\n self._connections: Dict[bytes, QuicConnection] = {}\n self._configuration = configuration\n self._http: Dict[QuicConnection, HttpConnection] = {}\n self._loop = asyncio.get_event_loop()\n self._session_ticket_fetcher = session_ticket_fetcher\n self._session_ticket_handler = session_ticket_handler\n + self._timer: Dict[QuicConnection, Tuple[asyncio.TimerHandle, float]] = {}\n self._transport: Optional[asyncio.DatagramTransport] = None\n \n if stateless_retry:\n self._retry = QuicRetryTokenHandler()\n else:\n self._retry = None\n "}}},{"rowIdx":2978,"cells":{"path":{"kind":"string","value":"examples.client/run"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"c6e2fd76e359835b0e0ba12cd0486e613a0f962a"},"commit_message":{"kind":"string","value":"[examples] make HTTP/0.9 client take an URL"},"ground_truth":{"kind":"string","value":" <0>: # parse URL\n parsed = urlparse(url)\n assert parsed.scheme == \"https\", \"Only HTTPS URLs are supported.\"\n if \":\" in parsed.netloc:\n server_name, port_str = parsed.netloc.split(\":\")\n port = int(port_str)\n else:\n server_name = parsed.netloc\n port = 443\n \n async with connect(server_name, port, **kwargs) as connection:\n async with connect(host, port, **kwargs) as connection:\n <3>: writer.write((\"GET %s\\r\\n\" % parsed.path).encode(\"utf8\"))\n writer.write((\"GET %s\\r\\n\" % path).encode(\"utf8\"))\n"},"main_code":{"kind":"string","value":" # module: examples.client\n + def run(url, **kwargs):\n - def run(host, port, path, **kwargs):\n <0> async with connect(host, port, **kwargs) as connection:\n <1> # perform HTTP/0.9 request\n <2> reader, writer = await connection.create_stream()\n <3> writer.write((\"GET %s\\r\\n\" % path).encode(\"utf8\"))\n <4> writer.write_eof()\n <5> \n <6> start = time.time()\n <7> response = await reader.read()\n <8> elapsed = time.time() - start\n <9> print(response.decode(\"utf8\"))\n<10> \n<11> octets = len(response)\n<12> logger.info(\n<13> \"Received %d bytes in %.1f s (%.3f Mbps)\"\n<14> % (octets, elapsed, octets * 8 / elapsed / 1000000)\n<15> )\n<16> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.asyncio.client\n connect(*args, **kwds)\n connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None]\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol\n create_stream(is_unidirectional: bool=False) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]\n \n at: asyncio.streams.StreamWriter\n write(data: bytes) -> None\n \n write_eof() -> None\n \n at: urllib.parse\n urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult\n urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes\n \n \n===========changed ref 0===========\n # module: examples.http3-client\n if __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"HTTP/3 client\")\n + parser.add_argument(\"url\", type=str, help=\"the URL to query (must be HTTPS)\")\n - parser.add_argument(\"url\", type=str, help=\"the server's host name or address\")\n parser.add_argument(\n \"-l\",\n \"--secrets-log\",\n type=str,\n help=\"log secrets to a file, for use with Wireshark\",\n )\n parser.add_argument(\n \"-s\",\n \"--session-ticket\",\n type=str,\n help=\"read and write session ticket from the specified file\",\n )\n parser.add_argument(\n \"-v\", \"--verbose\", action=\"store_true\", help=\"increase logging verbosity\"\n )\n args = parser.parse_args()\n \n logging.basicConfig(\n format=\"%(asctime)s %(levelname)s %(name)s %(message)s\",\n level=logging.DEBUG if args.verbose else logging.INFO,\n )\n \n # open SSL log file\n if args.secrets_log:\n secrets_log_file = open(args.secrets_log, \"a\")\n else:\n secrets_log_file = None\n \n # load session ticket\n session_ticket = None\n if args.session_ticket:\n try:\n with open(args.session_ticket, \"rb\") as fp:\n session_ticket = pickle.load(fp)\n except FileNotFoundError:\n pass\n \n run(url=args.url, secrets_log_file=secrets_log_file, session_ticket=session_ticket)\n "}}},{"rowIdx":2979,"cells":{"path":{"kind":"string","value":"aioquic.packet/pull_quic_header"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <7>: cid_lengths = buf.pull_uint8()\n <9>: destination_cid_length = buf.pull_uint8()\n destination_cid_length = decode_cid_length(cid_lengths // 16)\n<12>: source_cid_length = buf.pull_uint8()\n source_cid_length = decode_cid_length(cid_lengths % 16)\n<29>: original_destination_cid_length = buf.pull_uint8()\n original_destination_cid_length = decode_cid_length(first_byte & 0xF)\n"},"main_code":{"kind":"string","value":" # module: aioquic.packet\n def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader:\n <0> first_byte = buf.pull_uint8()\n <1> \n <2> original_destination_cid = b\"\"\n <3> token = b\"\"\n <4> if is_long_header(first_byte):\n <5> # long header packet\n <6> version = buf.pull_uint32()\n <7> cid_lengths = buf.pull_uint8()\n <8> \n <9> destination_cid_length = decode_cid_length(cid_lengths // 16)\n<10> destination_cid = buf.pull_bytes(destination_cid_length)\n<11> \n<12> source_cid_length = decode_cid_length(cid_lengths % 16)\n<13> source_cid = buf.pull_bytes(source_cid_length)\n<14> \n<15> if version == QuicProtocolVersion.NEGOTIATION:\n<16> # version negotiation\n<17> packet_type = None\n<18> rest_length = buf.capacity - buf.tell()\n<19> else:\n<20> if not (first_byte & PACKET_FIXED_BIT):\n<21> raise ValueError(\"Packet fixed bit is zero\")\n<22> \n<23> packet_type = first_byte & PACKET_TYPE_MASK\n<24> if packet_type == PACKET_TYPE_INITIAL:\n<25> token_length = buf.pull_uint_var()\n<26> token = buf.pull_bytes(token_length)\n<27> rest_length = buf.pull_uint_var()\n<28> elif packet_type == PACKET_TYPE_RETRY:\n<29> original_destination_cid_length = decode_cid_length(first_byte & 0xF)\n<30> original_destination_cid = buf.pull_bytes(\n<31> original_destination_cid_length\n<32> )\n<33> token = buf.pull_bytes(buf.capacity - buf.tell())\n<34> rest_length = 0\n<35> else:\n<36> rest_length = buf.pull_uint_var()\n<37> \n<38> return QuicHeader(\n<39> is_long_header=True,\n<40> version=version,\n "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.packet\n def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader:\n # offset: 1\n destination_cid=destination_cid,\n source_cid=source_cid,\n original_destination_cid=original_destination_cid,\n token=token,\n rest_length=rest_length,\n )\n else:\n # short header packet\n if not (first_byte & PACKET_FIXED_BIT):\n raise ValueError(\"Packet fixed bit is zero\")\n \n packet_type = first_byte & PACKET_TYPE_MASK\n destination_cid = buf.pull_bytes(host_cid_length)\n return QuicHeader(\n is_long_header=False,\n version=None,\n packet_type=packet_type,\n destination_cid=destination_cid,\n source_cid=b\"\",\n token=b\"\",\n rest_length=buf.capacity - buf.tell(),\n )\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer.Buffer\n tell() -> int\n \n pull_bytes(length: int) -> bytes\n \n pull_uint8() -> int\n \n pull_uint32() -> int\n \n pull_uint_var() -> int\n \n at: aioquic.packet\n PACKET_FIXED_BIT = 0x40\n \n PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00\n \n PACKET_TYPE_RETRY = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x30\n \n PACKET_TYPE_MASK = 0xF0\n \n QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int)\n QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n QuicHeader(is_long_header: bool, version: Optional[int], packet_type: int, destination_cid: bytes, source_cid: bytes, original_destination_cid: bytes=b\"\", token: bytes=b\"\", rest_length: int=0)\n \n at: aioquic.packet.QuicHeader\n is_long_header: bool\n \n version: Optional[int]\n \n packet_type: int\n \n destination_cid: bytes\n \n source_cid: bytes\n \n original_destination_cid: bytes = b\"\"\n \n token: bytes = b\"\"\n \n rest_length: int = 0\n \n at: aioquic.packet.pull_quic_header\n first_byte = buf.pull_uint8()\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 1===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 2===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - "}}},{"rowIdx":2980,"cells":{"path":{"kind":"string","value":"aioquic.packet/encode_quic_retry"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <1>: capacity=8\n capacity=6\n <7>: buf.push_uint8(PACKET_TYPE_RETRY)\n buf.push_uint8(PACKET_TYPE_RETRY | encode_cid_length(len(original_destination_cid)))\n <9>: buf.push_uint8(\n<10>: (encode_cid_length(len(destination_cid)) << 4)\n<11>: | encode_cid_length(len(source_cid))\n<12>: )\n<13>: buf.push_uint8(len(destination_cid))\n<14>: buf.push_uint8(len(source_cid))\n<15>: buf.push_uint8(len(original_destination_cid))\n"},"main_code":{"kind":"string","value":" # module: aioquic.packet\n def encode_quic_retry(\n version: int,\n source_cid: bytes,\n destination_cid: bytes,\n original_destination_cid: bytes,\n retry_token: bytes,\n ) -> bytes:\n <0> buf = Buffer(\n <1> capacity=6\n <2> + len(destination_cid)\n <3> + len(source_cid)\n <4> + len(original_destination_cid)\n <5> + len(retry_token)\n <6> )\n <7> buf.push_uint8(PACKET_TYPE_RETRY | encode_cid_length(len(original_destination_cid)))\n <8> buf.push_uint32(version)\n <9> buf.push_uint8(\n<10> (encode_cid_length(len(destination_cid)) << 4)\n<11> | encode_cid_length(len(source_cid))\n<12> )\n<13> buf.push_bytes(destination_cid)\n<14> buf.push_bytes(source_cid)\n<15> buf.push_bytes(original_destination_cid)\n<16> buf.push_bytes(retry_token)\n<17> return buf.data\n<18> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n push_bytes(value: bytes) -> None\n \n push_uint8(value: int) -> None\n \n push_uint32(v: int) -> None\n \n at: aioquic.packet\n PACKET_TYPE_RETRY = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x30\n \n QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int)\n QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n at: typing\n List = _alias(list, 1, inst=False, name='List')\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 1===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 2===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - \n===========changed ref 3===========\n # module: aioquic.packet\n def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader:\n first_byte = buf.pull_uint8()\n \n original_destination_cid = b\"\"\n token = b\"\"\n if is_long_header(first_byte):\n # long header packet\n version = buf.pull_uint32()\n - cid_lengths = buf.pull_uint8()\n \n + destination_cid_length = buf.pull_uint8()\n - destination_cid_length = decode_cid_length(cid_lengths // 16)\n destination_cid = buf.pull_bytes(destination_cid_length)\n \n + source_cid_length = buf.pull_uint8()\n - source_cid_length = decode_cid_length(cid_lengths % 16)\n source_cid = buf.pull_bytes(source_cid_length)\n \n if version == QuicProtocolVersion.NEGOTIATION:\n # version negotiation\n packet_type = None\n rest_length = buf.capacity - buf.tell()\n else:\n if not (first_byte & PACKET_FIXED_BIT):\n raise ValueError(\"Packet fixed bit is zero\")\n \n packet_type = first_byte & PACKET_TYPE_MASK\n if packet_type == PACKET_TYPE_INITIAL:\n token_length = buf.pull_uint_var()\n token = buf.pull_bytes(token_length)\n rest_length = buf.pull_uint_var()\n elif packet_type == PACKET_TYPE_RETRY:\n + original_destination_cid_length = buf.pull_uint8()\n - original_destination_cid_length = decode_cid_length(first_byte & 0xF)\n original_destination_cid = buf.pull_bytes(\n original_destination_cid_length\n )\n token = buf.pull_bytes(buf.capacity - buf.tell())\n rest_length = 0\n else:\n rest_length = buf.pull_uint_var()\n \n return QuicHeader(\n is_\n===========changed ref 4===========\n # module: aioquic.packet\n def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader:\n # offset: 1\n \n else:\n rest_length = buf.pull_uint_var()\n \n return QuicHeader(\n is_long_header=True,\n version=version,\n packet_type=packet_type,\n destination_cid=destination_cid,\n source_cid=source_cid,\n original_destination_cid=original_destination_cid,\n token=token,\n rest_length=rest_length,\n )\n else:\n # short header packet\n if not (first_byte & PACKET_FIXED_BIT):\n raise ValueError(\"Packet fixed bit is zero\")\n \n packet_type = first_byte & PACKET_TYPE_MASK\n destination_cid = buf.pull_bytes(host_cid_length)\n return QuicHeader(\n is_long_header=False,\n version=None,\n packet_type=packet_type,\n destination_cid=destination_cid,\n source_cid=b\"\",\n token=b\"\",\n rest_length=buf.capacity - buf.tell(),\n )\n "}}},{"rowIdx":2981,"cells":{"path":{"kind":"string","value":"aioquic.packet/encode_quic_version_negotiation"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <1>: capacity=7\n capacity=6\n <8>: buf.push_uint8(\n <9>: (encode_cid_length(len(destination_cid)) << 4)\n<10>: | encode_cid_length(len(source_cid))\n<11>: )\n<12>: buf.push_uint8(len(destination_cid))\n<13>: buf.push_uint8(len(source_cid))\n"},"main_code":{"kind":"string","value":" # module: aioquic.packet\n def encode_quic_version_negotiation(\n source_cid: bytes,\n destination_cid: bytes,\n supported_versions: List[QuicProtocolVersion],\n ) -> bytes:\n <0> buf = Buffer(\n <1> capacity=6\n <2> + len(destination_cid)\n <3> + len(source_cid)\n <4> + 4 * len(supported_versions)\n <5> )\n <6> buf.push_uint8(os.urandom(1)[0] | PACKET_LONG_HEADER)\n <7> buf.push_uint32(QuicProtocolVersion.NEGOTIATION)\n <8> buf.push_uint8(\n <9> (encode_cid_length(len(destination_cid)) << 4)\n<10> | encode_cid_length(len(source_cid))\n<11> )\n<12> buf.push_bytes(destination_cid)\n<13> buf.push_bytes(source_cid)\n<14> for version in supported_versions:\n<15> buf.push_uint32(version)\n<16> return buf.data\n<17> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer.Buffer\n push_bytes(value: bytes) -> None\n \n push_uint8(value: int) -> None\n \n push_uint32(v: int) -> None\n \n at: aioquic.packet\n PACKET_LONG_HEADER = 0x80\n \n QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int)\n QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n at: aioquic.packet.QuicTransportParameters\n original_connection_id: Optional[bytes] = None\n \n idle_timeout: Optional[int] = None\n \n stateless_reset_token: Optional[bytes] = None\n \n max_packet_size: Optional[int] = None\n \n initial_max_data: Optional[int] = None\n \n initial_max_stream_data_bidi_local: Optional[int] = None\n \n initial_max_stream_data_bidi_remote: Optional[int] = None\n \n initial_max_stream_data_uni: Optional[int] = None\n \n initial_max_streams_bidi: Optional[int] = None\n \n initial_max_streams_uni: Optional[int] = None\n \n ack_delay_exponent: Optional[int] = None\n \n max_ack_delay: Optional[int] = None\n \n disable_migration: Optional[bool] = False\n \n preferred_address: Optional[bytes] = None\n \n active_connection_id_limit: Optional[int] = None\n \n at: aioquic.packet.encode_quic_version_negotiation\n buf = Buffer(\n capacity=7\n + len(destination_cid)\n + len(source_cid)\n + 4 * len(supported_versions)\n )\n \n \n===========unchanged ref 1===========\n at: dataclasses\n field(*, default_factory: Callable[[], _T], init: bool=..., repr: bool=..., hash: Optional[bool]=..., compare: bool=..., metadata: Optional[Mapping[str, Any]]=...) -> _T\n field(*, init: bool=..., repr: bool=..., hash: Optional[bool]=..., compare: bool=..., metadata: Optional[Mapping[str, Any]]=...) -> Any\n field(*, default: _T, init: bool=..., repr: bool=..., hash: Optional[bool]=..., compare: bool=..., metadata: Optional[Mapping[str, Any]]=...) -> _T\n \n dataclass(*, init: bool=..., repr: bool=..., eq: bool=..., order: bool=..., unsafe_hash: bool=..., frozen: bool=...) -> Callable[[Type[_T]], Type[_T]]\n dataclass(_cls: None) -> Callable[[Type[_T]], Type[_T]]\n dataclass(_cls: Type[_T]) -> Type[_T]\n \n at: os\n urandom(size: int, /) -> bytes\n \n at: typing\n List = _alias(list, 1, inst=False, name='List')\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 1===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 2===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - \n===========changed ref 3===========\n # module: aioquic.packet\n def encode_quic_retry(\n version: int,\n source_cid: bytes,\n destination_cid: bytes,\n original_destination_cid: bytes,\n retry_token: bytes,\n ) -> bytes:\n buf = Buffer(\n + capacity=8\n - capacity=6\n + len(destination_cid)\n + len(source_cid)\n + len(original_destination_cid)\n + len(retry_token)\n )\n + buf.push_uint8(PACKET_TYPE_RETRY)\n - buf.push_uint8(PACKET_TYPE_RETRY | encode_cid_length(len(original_destination_cid)))\n buf.push_uint32(version)\n - buf.push_uint8(\n - (encode_cid_length(len(destination_cid)) << 4)\n - | encode_cid_length(len(source_cid))\n - )\n + buf.push_uint8(len(destination_cid))\n buf.push_bytes(destination_cid)\n + buf.push_uint8(len(source_cid))\n buf.push_bytes(source_cid)\n + buf.push_uint8(len(original_destination_cid))\n buf.push_bytes(original_destination_cid)\n buf.push_bytes(retry_token)\n return buf.data\n \n===========changed ref 4===========\n # module: aioquic.packet\n def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader:\n first_byte = buf.pull_uint8()\n \n original_destination_cid = b\"\"\n token = b\"\"\n if is_long_header(first_byte):\n # long header packet\n version = buf.pull_uint32()\n - cid_lengths = buf.pull_uint8()\n \n + destination_cid_length = buf.pull_uint8()\n - destination_cid_length = decode_cid_length(cid_lengths // 16)\n destination_cid = buf.pull_bytes(destination_cid_length)\n \n + source_cid_length = buf.pull_uint8()\n - source_cid_length = decode_cid_length(cid_lengths % 16)\n source_cid = buf.pull_bytes(source_cid_length)\n \n if version == QuicProtocolVersion.NEGOTIATION:\n # version negotiation\n packet_type = None\n rest_length = buf.capacity - buf.tell()\n else:\n if not (first_byte & PACKET_FIXED_BIT):\n raise ValueError(\"Packet fixed bit is zero\")\n \n packet_type = first_byte & PACKET_TYPE_MASK\n if packet_type == PACKET_TYPE_INITIAL:\n token_length = buf.pull_uint_var()\n token = buf.pull_bytes(token_length)\n rest_length = buf.pull_uint_var()\n elif packet_type == PACKET_TYPE_RETRY:\n + original_destination_cid_length = buf.pull_uint8()\n - original_destination_cid_length = decode_cid_length(first_byte & 0xF)\n original_destination_cid = buf.pull_bytes(\n original_destination_cid_length\n )\n token = buf.pull_bytes(buf.capacity - buf.tell())\n rest_length = 0\n else:\n rest_length = buf.pull_uint_var()\n \n return QuicHeader(\n is_"}}},{"rowIdx":2982,"cells":{"path":{"kind":"string","value":"aioquic.packet/pull_new_connection_id_frame"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <1>: retire_prior_to = buf.pull_uint_var()\n <4>: return (sequence_number, retire_prior_to, connection_id, stateless_reset_token)\n return (sequence_number, connection_id, stateless_reset_token)\n"},"main_code":{"kind":"string","value":" # module: aioquic.packet\n + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]:\n - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, bytes, bytes]:\n <0> sequence_number = buf.pull_uint_var()\n <1> length = buf.pull_uint8()\n <2> connection_id = buf.pull_bytes(length)\n <3> stateless_reset_token = buf.pull_bytes(16)\n <4> return (sequence_number, connection_id, stateless_reset_token)\n <5> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 1===========\n # module: aioquic.packet\n PARAMS = [\n (\"original_connection_id\", bytes),\n (\"idle_timeout\", int),\n (\"stateless_reset_token\", bytes),\n (\"max_packet_size\", int),\n (\"initial_max_data\", int),\n (\"initial_max_stream_data_bidi_local\", int),\n (\"initial_max_stream_data_bidi_remote\", int),\n (\"initial_max_stream_data_uni\", int),\n (\"initial_max_streams_bidi\", int),\n (\"initial_max_streams_uni\", int),\n (\"ack_delay_exponent\", int),\n (\"max_ack_delay\", int),\n (\"disable_migration\", bool),\n (\"preferred_address\", bytes),\n + (\"active_connection_id_limit\", int),\n ]\n \n===========changed ref 2===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - \n===========changed ref 3===========\n # module: aioquic.packet\n def encode_quic_version_negotiation(\n source_cid: bytes,\n destination_cid: bytes,\n supported_versions: List[QuicProtocolVersion],\n ) -> bytes:\n buf = Buffer(\n + capacity=7\n - capacity=6\n + len(destination_cid)\n + len(source_cid)\n + 4 * len(supported_versions)\n )\n buf.push_uint8(os.urandom(1)[0] | PACKET_LONG_HEADER)\n buf.push_uint32(QuicProtocolVersion.NEGOTIATION)\n - buf.push_uint8(\n - (encode_cid_length(len(destination_cid)) << 4)\n - | encode_cid_length(len(source_cid))\n - )\n + buf.push_uint8(len(destination_cid))\n buf.push_bytes(destination_cid)\n + buf.push_uint8(len(source_cid))\n buf.push_bytes(source_cid)\n for version in supported_versions:\n buf.push_uint32(version)\n return buf.data\n \n===========changed ref 4===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 5===========\n # module: aioquic.packet\n # TLS EXTENSION\n \n \n @dataclass\n class QuicTransportParameters:\n initial_version: Optional[QuicProtocolVersion] = None\n negotiated_version: Optional[QuicProtocolVersion] = None\n supported_versions: List[QuicProtocolVersion] = field(default_factory=list)\n \n original_connection_id: Optional[bytes] = None\n idle_timeout: Optional[int] = None\n stateless_reset_token: Optional[bytes] = None\n max_packet_size: Optional[int] = None\n initial_max_data: Optional[int] = None\n initial_max_stream_data_bidi_local: Optional[int] = None\n initial_max_stream_data_bidi_remote: Optional[int] = None\n initial_max_stream_data_uni: Optional[int] = None\n initial_max_streams_bidi: Optional[int] = None\n initial_max_streams_uni: Optional[int] = None\n ack_delay_exponent: Optional[int] = None\n max_ack_delay: Optional[int] = None\n disable_migration: Optional[bool] = False\n preferred_address: Optional[bytes] = None\n + active_connection_id_limit: Optional[int] = None\n \n===========changed ref 6===========\n # module: aioquic.packet\n def encode_quic_retry(\n version: int,\n source_cid: bytes,\n destination_cid: bytes,\n original_destination_cid: bytes,\n retry_token: bytes,\n ) -> bytes:\n buf = Buffer(\n + capacity=8\n - capacity=6\n + len(destination_cid)\n + len(source_cid)\n + len(original_destination_cid)\n + len(retry_token)\n )\n + buf.push_uint8(PACKET_TYPE_RETRY)\n - buf.push_uint8(PACKET_TYPE_RETRY | encode_cid_length(len(original_destination_cid)))\n buf.push_uint32(version)\n - buf.push_uint8(\n - (encode_cid_length(len(destination_cid)) << 4)\n - | encode_cid_length(len(source_cid))\n - )\n + buf.push_uint8(len(destination_cid))\n buf.push_bytes(destination_cid)\n + buf.push_uint8(len(source_cid))\n buf.push_bytes(source_cid)\n + buf.push_uint8(len(original_destination_cid))\n buf.push_bytes(original_destination_cid)\n buf.push_bytes(retry_token)\n return buf.data\n \n===========changed ref 7===========\n # module: aioquic.packet\n def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader:\n first_byte = buf.pull_uint8()\n \n original_destination_cid = b\"\"\n token = b\"\"\n if is_long_header(first_byte):\n # long header packet\n version = buf.pull_uint32()\n - cid_lengths = buf.pull_uint8()\n \n + destination_cid_length = buf.pull_uint8()\n - destination_cid_length = decode_cid_length(cid_lengths // 16)\n destination_cid = buf.pull_bytes(destination_cid_length)\n \n + source_cid_length = buf.pull_uint8()\n - source_cid_length = decode_cid_length(cid_lengths % 16)\n source_cid = buf.pull_bytes(source_cid_length)\n \n if version == QuicProtocolVersion.NEGOTIATION:\n # version negotiation\n packet_type = None\n rest_length = buf.capacity - buf.tell()\n else:\n if not (first_byte & PACKET_FIXED_BIT):\n raise ValueError(\"Packet fixed bit is zero\")\n \n packet_type = first_byte & PACKET_TYPE_MASK\n if packet_type == PACKET_TYPE_INITIAL:\n token_length = buf.pull_uint_var()\n token = buf.pull_bytes(token_length)\n rest_length = buf.pull_uint_var()\n elif packet_type == PACKET_TYPE_RETRY:\n + original_destination_cid_length = buf.pull_uint8()\n - original_destination_cid_length = decode_cid_length(first_byte & 0xF)\n original_destination_cid = buf.pull_bytes(\n original_destination_cid_length\n )\n token = buf.pull_bytes(buf.capacity - buf.tell())\n rest_length = 0\n else:\n rest_length = buf.pull_uint_var()\n \n return QuicHeader(\n is_"}}},{"rowIdx":2983,"cells":{"path":{"kind":"string","value":"aioquic.packet/push_new_connection_id_frame"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <2>: buf.push_uint_var(retire_prior_to)\n"},"main_code":{"kind":"string","value":" # module: aioquic.packet\n def push_new_connection_id_frame(\n buf: Buffer,\n sequence_number: int,\n + retire_prior_to: int,\n connection_id: bytes,\n stateless_reset_token: bytes,\n ) -> None:\n <0> assert len(stateless_reset_token) == 16\n <1> buf.push_uint_var(sequence_number)\n <2> buf.push_uint8(len(connection_id))\n <3> buf.push_bytes(connection_id)\n <4> buf.push_bytes(stateless_reset_token)\n <5> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer.Buffer\n push_bytes(value: bytes) -> None\n \n push_uint8(value: int) -> None\n \n push_uint_var(value: int) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]:\n - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, bytes, bytes]:\n sequence_number = buf.pull_uint_var()\n + retire_prior_to = buf.pull_uint_var()\n length = buf.pull_uint8()\n connection_id = buf.pull_bytes(length)\n stateless_reset_token = buf.pull_bytes(16)\n + return (sequence_number, retire_prior_to, connection_id, stateless_reset_token)\n - return (sequence_number, connection_id, stateless_reset_token)\n \n===========changed ref 1===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 2===========\n # module: aioquic.packet\n PARAMS = [\n (\"original_connection_id\", bytes),\n (\"idle_timeout\", int),\n (\"stateless_reset_token\", bytes),\n (\"max_packet_size\", int),\n (\"initial_max_data\", int),\n (\"initial_max_stream_data_bidi_local\", int),\n (\"initial_max_stream_data_bidi_remote\", int),\n (\"initial_max_stream_data_uni\", int),\n (\"initial_max_streams_bidi\", int),\n (\"initial_max_streams_uni\", int),\n (\"ack_delay_exponent\", int),\n (\"max_ack_delay\", int),\n (\"disable_migration\", bool),\n (\"preferred_address\", bytes),\n + (\"active_connection_id_limit\", int),\n ]\n \n===========changed ref 3===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - \n===========changed ref 4===========\n # module: aioquic.packet\n def encode_quic_version_negotiation(\n source_cid: bytes,\n destination_cid: bytes,\n supported_versions: List[QuicProtocolVersion],\n ) -> bytes:\n buf = Buffer(\n + capacity=7\n - capacity=6\n + len(destination_cid)\n + len(source_cid)\n + 4 * len(supported_versions)\n )\n buf.push_uint8(os.urandom(1)[0] | PACKET_LONG_HEADER)\n buf.push_uint32(QuicProtocolVersion.NEGOTIATION)\n - buf.push_uint8(\n - (encode_cid_length(len(destination_cid)) << 4)\n - | encode_cid_length(len(source_cid))\n - )\n + buf.push_uint8(len(destination_cid))\n buf.push_bytes(destination_cid)\n + buf.push_uint8(len(source_cid))\n buf.push_bytes(source_cid)\n for version in supported_versions:\n buf.push_uint32(version)\n return buf.data\n \n===========changed ref 5===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 6===========\n # module: aioquic.packet\n # TLS EXTENSION\n \n \n @dataclass\n class QuicTransportParameters:\n initial_version: Optional[QuicProtocolVersion] = None\n negotiated_version: Optional[QuicProtocolVersion] = None\n supported_versions: List[QuicProtocolVersion] = field(default_factory=list)\n \n original_connection_id: Optional[bytes] = None\n idle_timeout: Optional[int] = None\n stateless_reset_token: Optional[bytes] = None\n max_packet_size: Optional[int] = None\n initial_max_data: Optional[int] = None\n initial_max_stream_data_bidi_local: Optional[int] = None\n initial_max_stream_data_bidi_remote: Optional[int] = None\n initial_max_stream_data_uni: Optional[int] = None\n initial_max_streams_bidi: Optional[int] = None\n initial_max_streams_uni: Optional[int] = None\n ack_delay_exponent: Optional[int] = None\n max_ack_delay: Optional[int] = None\n disable_migration: Optional[bool] = False\n preferred_address: Optional[bytes] = None\n + active_connection_id_limit: Optional[int] = None\n \n===========changed ref 7===========\n # module: aioquic.packet\n def encode_quic_retry(\n version: int,\n source_cid: bytes,\n destination_cid: bytes,\n original_destination_cid: bytes,\n retry_token: bytes,\n ) -> bytes:\n buf = Buffer(\n + capacity=8\n - capacity=6\n + len(destination_cid)\n + len(source_cid)\n + len(original_destination_cid)\n + len(retry_token)\n )\n + buf.push_uint8(PACKET_TYPE_RETRY)\n - buf.push_uint8(PACKET_TYPE_RETRY | encode_cid_length(len(original_destination_cid)))\n buf.push_uint32(version)\n - buf.push_uint8(\n - (encode_cid_length(len(destination_cid)) << 4)\n - | encode_cid_length(len(source_cid))\n - )\n + buf.push_uint8(len(destination_cid))\n buf.push_bytes(destination_cid)\n + buf.push_uint8(len(source_cid))\n buf.push_bytes(source_cid)\n + buf.push_uint8(len(original_destination_cid))\n buf.push_bytes(original_destination_cid)\n buf.push_bytes(retry_token)\n return buf.data\n "}}},{"rowIdx":2984,"cells":{"path":{"kind":"string","value":"aioquic.packet/pull_transport_close_frame"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <0>: error_code = buf.pull_uint_var()\n error_code = buf.pull_uint16()\n"},"main_code":{"kind":"string","value":" # module: aioquic.packet\n def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]:\n <0> error_code = buf.pull_uint16()\n <1> frame_type = buf.pull_uint_var()\n <2> reason_length = buf.pull_uint_var()\n <3> reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n <4> return (error_code, frame_type, reason_phrase)\n <5> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n pull_uint_var() -> int\n \n at: aioquic.packet.pull_transport_close_frame\n error_code = buf.pull_uint_var()\n \n frame_type = buf.pull_uint_var()\n \n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n \n at: typing\n Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n def push_new_connection_id_frame(\n buf: Buffer,\n sequence_number: int,\n + retire_prior_to: int,\n connection_id: bytes,\n stateless_reset_token: bytes,\n ) -> None:\n assert len(stateless_reset_token) == 16\n buf.push_uint_var(sequence_number)\n + buf.push_uint_var(retire_prior_to)\n buf.push_uint8(len(connection_id))\n buf.push_bytes(connection_id)\n buf.push_bytes(stateless_reset_token)\n \n===========changed ref 1===========\n # module: aioquic.packet\n + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]:\n - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, bytes, bytes]:\n sequence_number = buf.pull_uint_var()\n + retire_prior_to = buf.pull_uint_var()\n length = buf.pull_uint8()\n connection_id = buf.pull_bytes(length)\n stateless_reset_token = buf.pull_bytes(16)\n + return (sequence_number, retire_prior_to, connection_id, stateless_reset_token)\n - return (sequence_number, connection_id, stateless_reset_token)\n \n===========changed ref 2===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 3===========\n # module: aioquic.packet\n PARAMS = [\n (\"original_connection_id\", bytes),\n (\"idle_timeout\", int),\n (\"stateless_reset_token\", bytes),\n (\"max_packet_size\", int),\n (\"initial_max_data\", int),\n (\"initial_max_stream_data_bidi_local\", int),\n (\"initial_max_stream_data_bidi_remote\", int),\n (\"initial_max_stream_data_uni\", int),\n (\"initial_max_streams_bidi\", int),\n (\"initial_max_streams_uni\", int),\n (\"ack_delay_exponent\", int),\n (\"max_ack_delay\", int),\n (\"disable_migration\", bool),\n (\"preferred_address\", bytes),\n + (\"active_connection_id_limit\", int),\n ]\n \n===========changed ref 4===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - \n===========changed ref 5===========\n # module: aioquic.packet\n def encode_quic_version_negotiation(\n source_cid: bytes,\n destination_cid: bytes,\n supported_versions: List[QuicProtocolVersion],\n ) -> bytes:\n buf = Buffer(\n + capacity=7\n - capacity=6\n + len(destination_cid)\n + len(source_cid)\n + 4 * len(supported_versions)\n )\n buf.push_uint8(os.urandom(1)[0] | PACKET_LONG_HEADER)\n buf.push_uint32(QuicProtocolVersion.NEGOTIATION)\n - buf.push_uint8(\n - (encode_cid_length(len(destination_cid)) << 4)\n - | encode_cid_length(len(source_cid))\n - )\n + buf.push_uint8(len(destination_cid))\n buf.push_bytes(destination_cid)\n + buf.push_uint8(len(source_cid))\n buf.push_bytes(source_cid)\n for version in supported_versions:\n buf.push_uint32(version)\n return buf.data\n \n===========changed ref 6===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 7===========\n # module: aioquic.packet\n # TLS EXTENSION\n \n \n @dataclass\n class QuicTransportParameters:\n initial_version: Optional[QuicProtocolVersion] = None\n negotiated_version: Optional[QuicProtocolVersion] = None\n supported_versions: List[QuicProtocolVersion] = field(default_factory=list)\n \n original_connection_id: Optional[bytes] = None\n idle_timeout: Optional[int] = None\n stateless_reset_token: Optional[bytes] = None\n max_packet_size: Optional[int] = None\n initial_max_data: Optional[int] = None\n initial_max_stream_data_bidi_local: Optional[int] = None\n initial_max_stream_data_bidi_remote: Optional[int] = None\n initial_max_stream_data_uni: Optional[int] = None\n initial_max_streams_bidi: Optional[int] = None\n initial_max_streams_uni: Optional[int] = None\n ack_delay_exponent: Optional[int] = None\n max_ack_delay: Optional[int] = None\n disable_migration: Optional[bool] = False\n preferred_address: Optional[bytes] = None\n + active_connection_id_limit: Optional[int] = None\n \n===========changed ref 8===========\n # module: aioquic.packet\n def encode_quic_retry(\n version: int,\n source_cid: bytes,\n destination_cid: bytes,\n original_destination_cid: bytes,\n retry_token: bytes,\n ) -> bytes:\n buf = Buffer(\n + capacity=8\n - capacity=6\n + len(destination_cid)\n + len(source_cid)\n + len(original_destination_cid)\n + len(retry_token)\n )\n + buf.push_uint8(PACKET_TYPE_RETRY)\n - buf.push_uint8(PACKET_TYPE_RETRY | encode_cid_length(len(original_destination_cid)))\n buf.push_uint32(version)\n - buf.push_uint8(\n - (encode_cid_length(len(destination_cid)) << 4)\n - | encode_cid_length(len(source_cid))\n - )\n + buf.push_uint8(len(destination_cid))\n buf.push_bytes(destination_cid)\n + buf.push_uint8(len(source_cid))\n buf.push_bytes(source_cid)\n + buf.push_uint8(len(original_destination_cid))\n buf.push_bytes(original_destination_cid)\n buf.push_bytes(retry_token)\n return buf.data\n "}}},{"rowIdx":2985,"cells":{"path":{"kind":"string","value":"aioquic.packet/pull_application_close_frame"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <0>: error_code = buf.pull_uint_var()\n error_code = buf.pull_uint16()\n"},"main_code":{"kind":"string","value":" # module: aioquic.packet\n def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]:\n <0> error_code = buf.pull_uint16()\n <1> reason_length = buf.pull_uint_var()\n <2> reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n <3> return (error_code, reason_phrase)\n <4> \n "},"context":{"kind":"string","value":"===========changed ref 0===========\n # module: aioquic.packet\n def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n frame_type = buf.pull_uint_var()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, frame_type, reason_phrase)\n \n===========changed ref 1===========\n # module: aioquic.packet\n def push_new_connection_id_frame(\n buf: Buffer,\n sequence_number: int,\n + retire_prior_to: int,\n connection_id: bytes,\n stateless_reset_token: bytes,\n ) -> None:\n assert len(stateless_reset_token) == 16\n buf.push_uint_var(sequence_number)\n + buf.push_uint_var(retire_prior_to)\n buf.push_uint8(len(connection_id))\n buf.push_bytes(connection_id)\n buf.push_bytes(stateless_reset_token)\n \n===========changed ref 2===========\n # module: aioquic.packet\n + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]:\n - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, bytes, bytes]:\n sequence_number = buf.pull_uint_var()\n + retire_prior_to = buf.pull_uint_var()\n length = buf.pull_uint8()\n connection_id = buf.pull_bytes(length)\n stateless_reset_token = buf.pull_bytes(16)\n + return (sequence_number, retire_prior_to, connection_id, stateless_reset_token)\n - return (sequence_number, connection_id, stateless_reset_token)\n \n===========changed ref 3===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 4===========\n # module: aioquic.packet\n PARAMS = [\n (\"original_connection_id\", bytes),\n (\"idle_timeout\", int),\n (\"stateless_reset_token\", bytes),\n (\"max_packet_size\", int),\n (\"initial_max_data\", int),\n (\"initial_max_stream_data_bidi_local\", int),\n (\"initial_max_stream_data_bidi_remote\", int),\n (\"initial_max_stream_data_uni\", int),\n (\"initial_max_streams_bidi\", int),\n (\"initial_max_streams_uni\", int),\n (\"ack_delay_exponent\", int),\n (\"max_ack_delay\", int),\n (\"disable_migration\", bool),\n (\"preferred_address\", bytes),\n + (\"active_connection_id_limit\", int),\n ]\n \n===========changed ref 5===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - \n===========changed ref 6===========\n # module: aioquic.packet\n def encode_quic_version_negotiation(\n source_cid: bytes,\n destination_cid: bytes,\n supported_versions: List[QuicProtocolVersion],\n ) -> bytes:\n buf = Buffer(\n + capacity=7\n - capacity=6\n + len(destination_cid)\n + len(source_cid)\n + 4 * len(supported_versions)\n )\n buf.push_uint8(os.urandom(1)[0] | PACKET_LONG_HEADER)\n buf.push_uint32(QuicProtocolVersion.NEGOTIATION)\n - buf.push_uint8(\n - (encode_cid_length(len(destination_cid)) << 4)\n - | encode_cid_length(len(source_cid))\n - )\n + buf.push_uint8(len(destination_cid))\n buf.push_bytes(destination_cid)\n + buf.push_uint8(len(source_cid))\n buf.push_bytes(source_cid)\n for version in supported_versions:\n buf.push_uint32(version)\n return buf.data\n \n===========changed ref 7===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 8===========\n # module: aioquic.packet\n # TLS EXTENSION\n \n \n @dataclass\n class QuicTransportParameters:\n initial_version: Optional[QuicProtocolVersion] = None\n negotiated_version: Optional[QuicProtocolVersion] = None\n supported_versions: List[QuicProtocolVersion] = field(default_factory=list)\n \n original_connection_id: Optional[bytes] = None\n idle_timeout: Optional[int] = None\n stateless_reset_token: Optional[bytes] = None\n max_packet_size: Optional[int] = None\n initial_max_data: Optional[int] = None\n initial_max_stream_data_bidi_local: Optional[int] = None\n initial_max_stream_data_bidi_remote: Optional[int] = None\n initial_max_stream_data_uni: Optional[int] = None\n initial_max_streams_bidi: Optional[int] = None\n initial_max_streams_uni: Optional[int] = None\n ack_delay_exponent: Optional[int] = None\n max_ack_delay: Optional[int] = None\n disable_migration: Optional[bool] = False\n preferred_address: Optional[bytes] = None\n + active_connection_id_limit: Optional[int] = None\n \n===========changed ref 9===========\n # module: aioquic.packet\n def encode_quic_retry(\n version: int,\n source_cid: bytes,\n destination_cid: bytes,\n original_destination_cid: bytes,\n retry_token: bytes,\n ) -> bytes:\n buf = Buffer(\n + capacity=8\n - capacity=6\n + len(destination_cid)\n + len(source_cid)\n + len(original_destination_cid)\n + len(retry_token)\n )\n + buf.push_uint8(PACKET_TYPE_RETRY)\n - buf.push_uint8(PACKET_TYPE_RETRY | encode_cid_length(len(original_destination_cid)))\n buf.push_uint32(version)\n - buf.push_uint8(\n - (encode_cid_length(len(destination_cid)) << 4)\n - | encode_cid_length(len(source_cid))\n - )\n + buf.push_uint8(len(destination_cid))\n buf.push_bytes(destination_cid)\n + buf.push_uint8(len(source_cid))\n buf.push_bytes(source_cid)\n + buf.push_uint8(len(original_destination_cid))\n buf.push_bytes(original_destination_cid)\n buf.push_bytes(retry_token)\n return buf.data\n "}}},{"rowIdx":2986,"cells":{"path":{"kind":"string","value":"aioquic.packet_builder/QuicPacketBuilder.start_packet"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":"<28>: header_size = 11 + len(self._peer_cid) + len(self._host_cid)\n header_size = 10 + len(self._peer_cid) + len(self._host_cid)\n"},"main_code":{"kind":"string","value":" # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n <0> \"\"\"\n <1> Starts a new packet.\n <2> \"\"\"\n <3> buf = self.buffer\n <4> self._ack_eliciting = False\n <5> \n <6> # if there is too little space remaining, start a new datagram\n <7> # FIXME: the limit is arbitrary!\n <8> packet_start = buf.tell()\n <9> if self._buffer_capacity - packet_start < 128:\n<10> self._flush_current_datagram()\n<11> packet_start = 0\n<12> \n<13> # initialize datagram if needed\n<14> if self._datagram_init:\n<15> if self.max_flight_bytes is not None:\n<16> remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes\n<17> if remaining_flight_bytes < self._buffer_capacity:\n<18> self._buffer_capacity = remaining_flight_bytes\n<19> if self.max_total_bytes is not None:\n<20> remaining_total_bytes = self.max_total_bytes - self._total_bytes\n<21> if remaining_total_bytes < self._buffer_capacity:\n<22> self._buffer_capacity = remaining_total_bytes\n<23> self._datagram_init = False\n<24> \n<25> # calculate header size\n<26> packet_long_header = is_long_header(packet_type)\n<27> if packet_long_header:\n<28> header_size = 10 + len(self._peer_cid) + len(self._host_cid)\n<29> if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL:\n<30> token_length = len(self._peer_token)\n<31> header_size += size_uint_var(token_length) + token_length\n<32> else:\n<33> header_size = 3 + len(self._peer_cid)\n<34> \n<35> # check we have enough space\n<36> if packet_start + header_size >= self._buffer_capacity:\n<37> raise QuicPacketBuilderStop\n<38> \n<39> "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n # offset: 1\n if packet_type == PACKET_TYPE_INITIAL:\n epoch = Epoch.INITIAL\n elif packet_type == PACKET_TYPE_HANDSHAKE:\n epoch = Epoch.HANDSHAKE\n else:\n epoch = Epoch.ONE_RTT\n \n self._header_size = header_size\n self._packet = QuicSentPacket(\n epoch=epoch,\n in_flight=False,\n is_ack_eliciting=False,\n is_crypto_packet=False,\n packet_number=self._packet_number,\n )\n self._packet_crypto = crypto\n self._packet_long_header = packet_long_header\n self._packet_start = packet_start\n self._packet_type = packet_type\n \n buf.seek(self._packet_start + self._header_size)\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer.Buffer\n seek(pos: int) -> None\n \n tell() -> int\n \n at: aioquic.buffer\n size_uint_var(value: int) -> int\n \n at: aioquic.packet\n PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00\n \n PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20\n \n PACKET_TYPE_MASK = 0xF0\n \n is_long_header(first_byte: int) -> bool\n \n at: aioquic.packet_builder\n QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field(\n default_factory=list\n ))\n \n QuicPacketBuilderStop(*args: object)\n \n at: aioquic.packet_builder.QuicPacketBuilder\n _flush_current_datagram() -> None\n _flush_current_datagram(self) -> None\n \n at: aioquic.packet_builder.QuicPacketBuilder.__init__\n self.max_flight_bytes: Optional[int] = None\n \n self.max_total_bytes: Optional[int] = None\n \n self._host_cid = host_cid\n \n self._peer_cid = peer_cid\n \n self._peer_token = peer_token\n \n self._ack_eliciting = False\n \n self._datagram_init = True\n \n self._flight_bytes = 0\n \n self._total_bytes = 0\n \n self._header_size = 0\n \n self._packet: Optional[QuicSentPacket] = None\n \n self._packet_crypto: Optional[CryptoPair] = None\n \n self._packet_long_header = False\n \n self._packet_number = packet_number\n \n self._packet_start = 0\n \n \n===========unchanged ref 1===========\n self._packet_type = 0\n \n self.buffer = Buffer(PACKET_MAX_SIZE)\n \n self._buffer_capacity = PACKET_MAX_SIZE\n \n at: aioquic.packet_builder.QuicPacketBuilder._flush_current_datagram\n self._datagram_init = True\n \n self._flight_bytes += datagram_bytes\n \n self._total_bytes += datagram_bytes\n \n at: aioquic.packet_builder.QuicPacketBuilder.end_packet\n self._packet_number += 1\n \n self._packet = None\n \n at: aioquic.packet_builder.QuicPacketBuilder.start_frame\n self._ack_eliciting = True\n \n at: aioquic.packet_builder.QuicSentPacket\n epoch: Epoch\n \n in_flight: bool\n \n is_ack_eliciting: bool\n \n is_crypto_packet: bool\n \n packet_number: int\n \n sent_time: Optional[float] = None\n \n sent_bytes: int = 0\n \n delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(\n default_factory=list\n )\n \n at: aioquic.tls\n Epoch()\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 1===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - \n===========changed ref 2===========\n # module: aioquic.packet\n def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, reason_phrase)\n \n===========changed ref 3===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 4===========\n # module: aioquic.packet\n def push_new_connection_id_frame(\n buf: Buffer,\n sequence_number: int,\n + retire_prior_to: int,\n connection_id: bytes,\n stateless_reset_token: bytes,\n ) -> None:\n assert len(stateless_reset_token) == 16\n buf.push_uint_var(sequence_number)\n + buf.push_uint_var(retire_prior_to)\n buf.push_uint8(len(connection_id))\n buf.push_bytes(connection_id)\n buf.push_bytes(stateless_reset_token)\n \n===========changed ref 5===========\n # module: aioquic.packet\n def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n frame_type = buf.pull_uint_var()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, frame_type, reason_phrase)\n \n===========changed ref 6===========\n # module: aioquic.packet\n + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]:\n - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, bytes, bytes]:\n sequence_number = buf.pull_uint_var()\n + retire_prior_to = buf.pull_uint_var()\n length = buf.pull_uint8()\n connection_id = buf.pull_bytes(length)\n stateless_reset_token = buf.pull_bytes(16)\n + return (sequence_number, retire_prior_to, connection_id, stateless_reset_token)\n - return (sequence_number, connection_id, stateless_reset_token)\n "}}},{"rowIdx":2987,"cells":{"path":{"kind":"string","value":"aioquic.packet_builder/QuicPacketBuilder.end_packet"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":"<29>: buf.push_uint8(len(self._peer_cid))\n buf.push_uint8(\n<30>: (encode_cid_length(len(self._peer_cid)) << 4)\n<31>: | encode_cid_length(len(self._host_cid))\n<32>: )\n<34>: buf.push_uint8(len(self._host_cid))\n"},"main_code":{"kind":"string","value":" # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def end_packet(self) -> bool:\n <0> \"\"\"\n <1> Ends the current packet.\n <2> \n <3> Returns `True` if the packet contains data, `False` otherwise.\n <4> \"\"\"\n <5> buf = self.buffer\n <6> empty = True\n <7> packet_size = buf.tell() - self._packet_start\n <8> if packet_size > self._header_size:\n <9> empty = False\n<10> \n<11> # pad initial datagram\n<12> if self._pad_first_datagram:\n<13> buf.push_bytes(bytes(self.remaining_space))\n<14> packet_size = buf.tell() - self._packet_start\n<15> self._pad_first_datagram = False\n<16> \n<17> # write header\n<18> if self._packet_long_header:\n<19> length = (\n<20> packet_size\n<21> - self._header_size\n<22> + PACKET_NUMBER_SEND_SIZE\n<23> + self._packet_crypto.aead_tag_size\n<24> )\n<25> \n<26> buf.seek(self._packet_start)\n<27> buf.push_uint8(self._packet_type | (PACKET_NUMBER_SEND_SIZE - 1))\n<28> buf.push_uint32(self._version)\n<29> buf.push_uint8(\n<30> (encode_cid_length(len(self._peer_cid)) << 4)\n<31> | encode_cid_length(len(self._host_cid))\n<32> )\n<33> buf.push_bytes(self._peer_cid)\n<34> buf.push_bytes(self._host_cid)\n<35> if (self._packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL:\n<36> buf.push_uint_var(len(self._peer_token))\n<37> buf.push_bytes(self._peer_token)\n<38> buf.push_uint16(length | 0x4000)\n<39> buf.push_uint16(self._packet_number & 0xFFFF)\n<40> else:\n<41> buf.seek(self"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def end_packet(self) -> bool:\n # offset: 1\n buf.push_uint8(\n self._packet_type\n | (self._spin_bit << 5)\n | (self._packet_crypto.key_phase << 2)\n | (PACKET_NUMBER_SEND_SIZE - 1)\n )\n buf.push_bytes(self._peer_cid)\n buf.push_uint16(self._packet_number & 0xFFFF)\n \n # check whether we need padding\n padding_size = (\n PACKET_NUMBER_MAX_SIZE\n - PACKET_NUMBER_SEND_SIZE\n + self._header_size\n - packet_size\n )\n if padding_size > 0:\n buf.seek(self._packet_start + packet_size)\n buf.push_bytes(bytes(padding_size))\n packet_size += padding_size\n \n # encrypt in place\n plain = buf.data_slice(self._packet_start, self._packet_start + packet_size)\n buf.seek(self._packet_start)\n buf.push_bytes(\n self._packet_crypto.encrypt_packet(\n plain[0 : self._header_size],\n plain[self._header_size : packet_size],\n self._packet_number,\n )\n )\n self._packet.sent_bytes = buf.tell() - self._packet_start\n self._packets.append(self._packet)\n \n # short header packets cannot be coallesced, we need a new datagram\n if not self._packet_long_header:\n self._flush_current_datagram()\n \n self._packet_number += 1\n else:\n # \"cancel\" the packet\n buf.seek(self._packet_start)\n \n self._packet = None\n \n return not empty\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer.Buffer\n data_slice(start: int, end: int) -> bytes\n \n seek(pos: int) -> None\n \n tell() -> int\n \n push_bytes(value: bytes) -> None\n \n push_uint8(value: int) -> None\n \n push_uint16(value: int) -> None\n \n push_uint32(v: int) -> None\n \n push_uint_var(value: int) -> None\n \n at: aioquic.crypto.CryptoPair\n encrypt_packet(plain_header: bytes, plain_payload: bytes, packet_number: int) -> bytes\n \n at: aioquic.crypto.CryptoPair.__init__\n self.aead_tag_size = 16\n \n at: aioquic.packet\n PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00\n \n PACKET_TYPE_MASK = 0xF0\n \n PACKET_NUMBER_MAX_SIZE = 4\n \n at: aioquic.packet_builder\n PACKET_NUMBER_SEND_SIZE = 2\n \n at: aioquic.packet_builder.QuicPacketBuilder.__init__\n self._host_cid = host_cid\n \n self._pad_first_datagram = pad_first_datagram\n \n self._peer_cid = peer_cid\n \n self._peer_token = peer_token\n \n self._spin_bit = spin_bit\n \n self._version = version\n \n self._packets: List[QuicSentPacket] = []\n \n self._header_size = 0\n \n self._packet: Optional[QuicSentPacket] = None\n \n self._packet_crypto: Optional[CryptoPair] = None\n \n self._packet_long_header = False\n \n self._packet_number = packet_number\n \n self._packet_start = 0\n \n self._packet_type = 0\n \n self.buffer = Buffer(PACKET_MAX_SIZE)\n \n at: aioquic.packet_builder.QuicPacketBuilder.flush\n self._packets = []\n \n \n===========unchanged ref 1===========\n at: aioquic.packet_builder.QuicPacketBuilder.start_packet\n self._header_size = header_size\n \n self._packet = QuicSentPacket(\n epoch=epoch,\n in_flight=False,\n is_ack_eliciting=False,\n is_crypto_packet=False,\n packet_number=self._packet_number,\n )\n \n self._packet_crypto = crypto\n \n self._packet_long_header = packet_long_header\n \n self._packet_start = packet_start\n \n self._packet_type = packet_type\n \n at: aioquic.packet_builder.QuicSentPacket\n sent_bytes: int = 0\n \n \n===========changed ref 0===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n \"\"\"\n Starts a new packet.\n \"\"\"\n buf = self.buffer\n self._ack_eliciting = False\n \n # if there is too little space remaining, start a new datagram\n # FIXME: the limit is arbitrary!\n packet_start = buf.tell()\n if self._buffer_capacity - packet_start < 128:\n self._flush_current_datagram()\n packet_start = 0\n \n # initialize datagram if needed\n if self._datagram_init:\n if self.max_flight_bytes is not None:\n remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes\n if remaining_flight_bytes < self._buffer_capacity:\n self._buffer_capacity = remaining_flight_bytes\n if self.max_total_bytes is not None:\n remaining_total_bytes = self.max_total_bytes - self._total_bytes\n if remaining_total_bytes < self._buffer_capacity:\n self._buffer_capacity = remaining_total_bytes\n self._datagram_init = False\n \n # calculate header size\n packet_long_header = is_long_header(packet_type)\n if packet_long_header:\n + header_size = 11 + len(self._peer_cid) + len(self._host_cid)\n - header_size = 10 + len(self._peer_cid) + len(self._host_cid)\n if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL:\n token_length = len(self._peer_token)\n header_size += size_uint_var(token_length) + token_length\n else:\n header_size = 3 + len(self._peer_cid)\n \n # check we have enough space\n if packet_start + header_size >= self._buffer_capacity:\n raise QuicPacketBuilderStop\n \n # determine ack epoch\n if packet_type == PACKET\n===========changed ref 1===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n # offset: 1\n self._buffer_capacity:\n raise QuicPacketBuilderStop\n \n # determine ack epoch\n if packet_type == PACKET_TYPE_INITIAL:\n epoch = Epoch.INITIAL\n elif packet_type == PACKET_TYPE_HANDSHAKE:\n epoch = Epoch.HANDSHAKE\n else:\n epoch = Epoch.ONE_RTT\n \n self._header_size = header_size\n self._packet = QuicSentPacket(\n epoch=epoch,\n in_flight=False,\n is_ack_eliciting=False,\n is_crypto_packet=False,\n packet_number=self._packet_number,\n )\n self._packet_crypto = crypto\n self._packet_long_header = packet_long_header\n self._packet_start = packet_start\n self._packet_type = packet_type\n \n buf.seek(self._packet_start + self._header_size)\n \n===========changed ref 2===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 3===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - "}}},{"rowIdx":2988,"cells":{"path":{"kind":"string","value":"aioquic.connection/write_close_frame"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <6>: buf.push_uint_var(error_code)\n buf.push_uint16(error_code)\n<11>: buf.push_uint_var(error_code)\n buf.push_uint16(error_code)\n"},"main_code":{"kind":"string","value":" # module: aioquic.connection\n def write_close_frame(\n builder: QuicPacketBuilder,\n error_code: int,\n frame_type: Optional[int],\n reason_phrase: str,\n ) -> None:\n <0> buf = builder.buffer\n <1> \n <2> reason_bytes = reason_phrase.encode(\"utf8\")\n <3> \n <4> if frame_type is None:\n <5> builder.start_frame(QuicFrameType.APPLICATION_CLOSE)\n <6> buf.push_uint16(error_code)\n <7> buf.push_uint_var(len(reason_bytes))\n <8> buf.push_bytes(reason_bytes)\n <9> else:\n<10> builder.start_frame(QuicFrameType.TRANSPORT_CLOSE)\n<11> buf.push_uint16(error_code)\n<12> buf.push_uint_var(frame_type)\n<13> buf.push_uint_var(len(reason_bytes))\n<14> buf.push_bytes(reason_bytes)\n<15> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer.Buffer\n push_bytes(value: bytes) -> None\n \n push_uint16(value: int) -> None\n \n push_uint_var(value: int) -> None\n \n at: aioquic.packet\n QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n QuicFrameType(x: Union[str, bytes, bytearray], base: int)\n \n at: aioquic.packet_builder\n 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)\n \n at: aioquic.packet_builder.QuicPacketBuilder\n start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None\n \n at: aioquic.packet_builder.QuicPacketBuilder.__init__\n self.buffer = Buffer(PACKET_MAX_SIZE)\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 1===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - \n===========changed ref 2===========\n # module: aioquic.packet\n def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, reason_phrase)\n \n===========changed ref 3===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 4===========\n # module: aioquic.packet\n def push_new_connection_id_frame(\n buf: Buffer,\n sequence_number: int,\n + retire_prior_to: int,\n connection_id: bytes,\n stateless_reset_token: bytes,\n ) -> None:\n assert len(stateless_reset_token) == 16\n buf.push_uint_var(sequence_number)\n + buf.push_uint_var(retire_prior_to)\n buf.push_uint8(len(connection_id))\n buf.push_bytes(connection_id)\n buf.push_bytes(stateless_reset_token)\n \n===========changed ref 5===========\n # module: aioquic.packet\n def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n frame_type = buf.pull_uint_var()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, frame_type, reason_phrase)\n \n===========changed ref 6===========\n # module: aioquic.packet\n + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]:\n - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, bytes, bytes]:\n sequence_number = buf.pull_uint_var()\n + retire_prior_to = buf.pull_uint_var()\n length = buf.pull_uint8()\n connection_id = buf.pull_bytes(length)\n stateless_reset_token = buf.pull_bytes(16)\n + return (sequence_number, retire_prior_to, connection_id, stateless_reset_token)\n - return (sequence_number, connection_id, stateless_reset_token)\n \n===========changed ref 7===========\n # module: aioquic.configuration\n @dataclass\n class QuicConfiguration:\n alpn_protocols: Optional[List[str]] = None\n certificate: Any = None\n idle_timeout: float = 60.0\n is_client: bool = True\n private_key: Any = None\n secrets_log_file: TextIO = None\n server_name: Optional[str] = None\n session_ticket: Optional[tls.SessionTicket] = None\n supported_versions: List[QuicProtocolVersion] = field(\n - default_factory=lambda: [\n - QuicProtocolVersion.DRAFT_19,\n - QuicProtocolVersion.DRAFT_20,\n - ]\n + default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n===========changed ref 8===========\n # module: aioquic.packet\n PARAMS = [\n (\"original_connection_id\", bytes),\n (\"idle_timeout\", int),\n (\"stateless_reset_token\", bytes),\n (\"max_packet_size\", int),\n (\"initial_max_data\", int),\n (\"initial_max_stream_data_bidi_local\", int),\n (\"initial_max_stream_data_bidi_remote\", int),\n (\"initial_max_stream_data_uni\", int),\n (\"initial_max_streams_bidi\", int),\n (\"initial_max_streams_uni\", int),\n (\"ack_delay_exponent\", int),\n (\"max_ack_delay\", int),\n (\"disable_migration\", bool),\n (\"preferred_address\", bytes),\n + (\"active_connection_id_limit\", int),\n ]\n \n===========changed ref 9===========\n # module: aioquic.packet\n def encode_quic_version_negotiation(\n source_cid: bytes,\n destination_cid: bytes,\n supported_versions: List[QuicProtocolVersion],\n ) -> bytes:\n buf = Buffer(\n + capacity=7\n - capacity=6\n + len(destination_cid)\n + len(source_cid)\n + 4 * len(supported_versions)\n )\n buf.push_uint8(os.urandom(1)[0] | PACKET_LONG_HEADER)\n buf.push_uint32(QuicProtocolVersion.NEGOTIATION)\n - buf.push_uint8(\n - (encode_cid_length(len(destination_cid)) << 4)\n - | encode_cid_length(len(source_cid))\n - )\n + buf.push_uint8(len(destination_cid))\n buf.push_bytes(destination_cid)\n + buf.push_uint8(len(source_cid))\n buf.push_bytes(source_cid)\n for version in supported_versions:\n buf.push_uint32(version)\n return buf.data\n \n===========changed ref 10===========\n # module: aioquic.crypto\n CIPHER_SUITES = {\n CipherSuite.AES_128_GCM_SHA256: (b\"aes-128-ecb\", b\"aes-128-gcm\"),\n CipherSuite.AES_256_GCM_SHA384: (b\"aes-256-ecb\", b\"aes-256-gcm\"),\n CipherSuite.CHACHA20_POLY1305_SHA256: (b\"chacha20\", b\"chacha20-poly1305\"),\n }\n INITIAL_CIPHER_SUITE = CipherSuite.AES_128_GCM_SHA256\n + INITIAL_SALT = binascii.unhexlify(\"7fbcdb0e7c66bbe9193a96cd21519ebd7a02644a\")\n - INITIAL_SALT = binascii.unhexlify(\"ef4fb0abb47470c41befcf8031334fae485e09a0\")\n SAMPLE_SIZE = 16\n "}}},{"rowIdx":2989,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n original_connection_id: Optional[bytes] = None,\n session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,\n session_ticket_handler: Optional[tls.SessionTicketHandler] = None,\n ) -> None:\n <0> if configuration.is_client:\n <1> assert (\n <2> original_connection_id is None\n <3> ), \"Cannot set original_connection_id for a client\"\n <4> else:\n <5> assert (\n <6> configuration.certificate is not None\n <7> ), \"SSL certificate is required for a server\"\n <8> assert (\n <9> configuration.private_key is not None\n<10> ), \"SSL private key is required for a server\"\n<11> \n<12> # counters for debugging\n<13> self._stateless_retry_count = 0\n<14> self._version_negotiation_count = 0\n<15> \n<16> # configuration\n<17> self._configuration = configuration\n<18> self._is_client = configuration.is_client\n<19> \n<20> self._ack_delay = K_GRANULARITY\n<21> self._close_at: Optional[float] = None\n<22> self._close_event: Optional[events.ConnectionTerminated] = None\n<23> self._connect_called = False\n<24> self._cryptos: Dict[tls.Epoch, CryptoPair] = {}\n<25> self._crypto_buffers: Dict[tls.Epoch, Buffer] = {}\n<26> self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}\n<27> self._events: Deque[events.Event] = deque()\n<28> self._handshake_complete = False\n<29> self._handshake_confirmed = False\n<30> self._host_cids = [\n<31> QuicConnectionId(\n<32> cid=os.urandom(8),\n<33> sequence_number=0,\n<34> stateless_reset_token=os.urandom(16),\n<35> was_sent=True,\n<36> )\n<37> ]\n<38> self.host_cid = self._"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.connection\n class QuicConnection:\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n original_connection_id: Optional[bytes] = None,\n session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,\n session_ticket_handler: Optional[tls.SessionTicketHandler] = None,\n ) -> None:\n # offset: 1\n self._host_cid_seq = 1\n self._local_max_data = MAX_DATA_WINDOW\n self._local_max_data_sent = MAX_DATA_WINDOW\n self._local_max_data_used = 0\n self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW\n self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW\n self._local_max_stream_data_uni = MAX_DATA_WINDOW\n self._local_max_streams_bidi = 128\n self._local_max_streams_uni = 128\n self._logger = QuicConnectionAdapter(\n logger, {\"host_cid\": dump_cid(self.host_cid)}\n )\n self._loss = QuicPacketRecovery(\n is_client_without_1rtt=self._is_client, send_probe=self._send_probe\n )\n self._loss_at: Optional[float] = None\n self._network_paths: List[QuicNetworkPath] = []\n self._original_connection_id = original_connection_id\n self._packet_number = 0\n self._parameters_received = False\n self._peer_cid = os.urandom(8)\n self._peer_cid_seq: Optional[int] = None\n self._peer_cid_available: List[QuicConnectionId] = []\n self._peer_token = b\"\"\n self._remote_idle_timeout = 0.0 # seconds\n self._remote_max_data = 0\n self._remote_max_data_used = 0\n self._remote_max_stream_data_bidi_local = 0\n self._remote\n===========below chunk 1===========\n # module: aioquic.connection\n class QuicConnection:\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n original_connection_id: Optional[bytes] = None,\n session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,\n session_ticket_handler: Optional[tls.SessionTicketHandler] = None,\n ) -> None:\n # offset: 2\n max_data_used = 0\n self._remote_max_stream_data_bidi_local = 0\n self._remote_max_stream_data_bidi_remote = 0\n self._remote_max_stream_data_uni = 0\n self._remote_max_streams_bidi = 0\n self._remote_max_streams_uni = 0\n self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}\n self._spin_bit = False\n self._spin_bit_peer = False\n self._spin_highest_pn = 0\n self._state = QuicConnectionState.FIRSTFLIGHT\n self._streams: Dict[int, QuicStream] = {}\n self._streams_blocked_bidi: List[QuicStream] = []\n self._streams_blocked_uni: List[QuicStream] = []\n self._version: Optional[int] = None\n \n # things to send\n self._close_pending = False\n self._ping_pending: List[int] = []\n self._probe_pending = False\n self._retire_connection_ids: List[int] = []\n self._streams_blocked_pending = False\n \n # callbacks\n self._session_ticket_fetcher = session_ticket_fetcher\n self._session_ticket_handler = session_ticket_handler\n \n # frame handlers\n self.__frame_handlers = [\n (self._handle_padding_frame, EPOCHS(\"IZHO\")),\n (self._handle_padding_frame, EPOCHS(\"ZO\")),\n===========below chunk 2===========\n # module: aioquic.connection\n class QuicConnection:\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n original_connection_id: Optional[bytes] = None,\n session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,\n session_ticket_handler: Optional[tls.SessionTicketHandler] = None,\n ) -> None:\n # offset: 3\n (self._handle_ack_frame, EPOCHS(\"IHO\")),\n (self._handle_ack_frame, EPOCHS(\"IHO\")),\n (self._handle_reset_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stop_sending_frame, EPOCHS(\"ZO\")),\n (self._handle_crypto_frame, EPOCHS(\"IHO\")),\n (self._handle_new_token_frame, EPOCHS(\"O\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_max_data_frame, EPOCHS(\"ZO\")),\n (self._handle_max_stream_data_frame, EPOCHS(\"ZO\")),\n (self._handle_max_streams_bidi_frame, EPOCHS(\"ZO\")),\n (self._handle_max_streams_uni_frame, EPOCHS(\"ZO\")),\n (self._handle_data_blocked_frame,\n===========below chunk 3===========\n # module: aioquic.connection\n class QuicConnection:\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n original_connection_id: Optional[bytes] = None,\n session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,\n session_ticket_handler: Optional[tls.SessionTicketHandler] = None,\n ) -> None:\n # offset: 4\n S(\"ZO\")),\n (self._handle_stream_data_blocked_frame, EPOCHS(\"ZO\")),\n (self._handle_streams_blocked_frame, EPOCHS(\"ZO\")),\n (self._handle_streams_blocked_frame, EPOCHS(\"ZO\")),\n (self._handle_new_connection_id_frame, EPOCHS(\"ZO\")),\n (self._handle_retire_connection_id_frame, EPOCHS(\"O\")),\n (self._handle_path_challenge_frame, EPOCHS(\"ZO\")),\n (self._handle_path_response_frame, EPOCHS(\"O\")),\n (self._handle_connection_close_frame, EPOCHS(\"IZHO\")),\n (self._handle_connection_close_frame, EPOCHS(\"ZO\")),\n ]\n \n "}}},{"rowIdx":2990,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection._handle_new_connection_id_frame"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <3>: sequence_number, retire_prior_to, cid, stateless_reset_token = pull_new_connection_id_frame(\n sequence_number, cid, stateless_reset_token = pull_new_connection_id_frame(buf)\n <4>: buf\n )\n"},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def _handle_new_connection_id_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n <0> \"\"\"\n <1> Handle a NEW_CONNECTION_ID frame.\n <2> \"\"\"\n <3> sequence_number, cid, stateless_reset_token = pull_new_connection_id_frame(buf)\n <4> self._logger.debug(\n <5> \"New connection ID received %d %s\", sequence_number, dump_cid(cid)\n <6> )\n <7> self._peer_cid_available.append(\n <8> QuicConnectionId(\n <9> cid=cid,\n<10> sequence_number=sequence_number,\n<11> stateless_reset_token=stateless_reset_token,\n<12> )\n<13> )\n<14> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic.connection\n dump_cid(cid: bytes) -> str\n \n QuicConnectionId(cid: bytes, sequence_number: int, stateless_reset_token: bytes=b\"\", was_sent: bool=False)\n \n QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, time: float)\n \n at: aioquic.connection.QuicConnection.__init__\n self._logger = QuicConnectionAdapter(\n logger, {\"host_cid\": dump_cid(self.host_cid)}\n )\n \n self._peer_cid_available: List[QuicConnectionId] = []\n \n at: aioquic.packet\n pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]\n \n at: logging.LoggerAdapter\n logger: Logger\n \n extra: Mapping[str, Any]\n \n debug(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]:\n - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, bytes, bytes]:\n sequence_number = buf.pull_uint_var()\n + retire_prior_to = buf.pull_uint_var()\n length = buf.pull_uint8()\n connection_id = buf.pull_bytes(length)\n stateless_reset_token = buf.pull_bytes(16)\n + return (sequence_number, retire_prior_to, connection_id, stateless_reset_token)\n - return (sequence_number, connection_id, stateless_reset_token)\n \n===========changed ref 1===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 2===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - \n===========changed ref 3===========\n # module: aioquic.packet\n def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, reason_phrase)\n \n===========changed ref 4===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 5===========\n # module: aioquic.packet\n def push_new_connection_id_frame(\n buf: Buffer,\n sequence_number: int,\n + retire_prior_to: int,\n connection_id: bytes,\n stateless_reset_token: bytes,\n ) -> None:\n assert len(stateless_reset_token) == 16\n buf.push_uint_var(sequence_number)\n + buf.push_uint_var(retire_prior_to)\n buf.push_uint8(len(connection_id))\n buf.push_bytes(connection_id)\n buf.push_bytes(stateless_reset_token)\n \n===========changed ref 6===========\n # module: aioquic.packet\n def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n frame_type = buf.pull_uint_var()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, frame_type, reason_phrase)\n \n===========changed ref 7===========\n # module: aioquic.configuration\n @dataclass\n class QuicConfiguration:\n alpn_protocols: Optional[List[str]] = None\n certificate: Any = None\n idle_timeout: float = 60.0\n is_client: bool = True\n private_key: Any = None\n secrets_log_file: TextIO = None\n server_name: Optional[str] = None\n session_ticket: Optional[tls.SessionTicket] = None\n supported_versions: List[QuicProtocolVersion] = field(\n - default_factory=lambda: [\n - QuicProtocolVersion.DRAFT_19,\n - QuicProtocolVersion.DRAFT_20,\n - ]\n + default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n===========changed ref 8===========\n # module: aioquic.packet\n PARAMS = [\n (\"original_connection_id\", bytes),\n (\"idle_timeout\", int),\n (\"stateless_reset_token\", bytes),\n (\"max_packet_size\", int),\n (\"initial_max_data\", int),\n (\"initial_max_stream_data_bidi_local\", int),\n (\"initial_max_stream_data_bidi_remote\", int),\n (\"initial_max_stream_data_uni\", int),\n (\"initial_max_streams_bidi\", int),\n (\"initial_max_streams_uni\", int),\n (\"ack_delay_exponent\", int),\n (\"max_ack_delay\", int),\n (\"disable_migration\", bool),\n (\"preferred_address\", bytes),\n + (\"active_connection_id_limit\", int),\n ]\n \n===========changed ref 9===========\n # module: aioquic.connection\n def write_close_frame(\n builder: QuicPacketBuilder,\n error_code: int,\n frame_type: Optional[int],\n reason_phrase: str,\n ) -> None:\n buf = builder.buffer\n \n reason_bytes = reason_phrase.encode(\"utf8\")\n \n if frame_type is None:\n builder.start_frame(QuicFrameType.APPLICATION_CLOSE)\n + buf.push_uint_var(error_code)\n - buf.push_uint16(error_code)\n buf.push_uint_var(len(reason_bytes))\n buf.push_bytes(reason_bytes)\n else:\n builder.start_frame(QuicFrameType.TRANSPORT_CLOSE)\n + buf.push_uint_var(error_code)\n - buf.push_uint16(error_code)\n buf.push_uint_var(frame_type)\n buf.push_uint_var(len(reason_bytes))\n buf.push_bytes(reason_bytes)\n \n===========changed ref 10===========\n # module: aioquic.packet\n def encode_quic_version_negotiation(\n source_cid: bytes,\n destination_cid: bytes,\n supported_versions: List[QuicProtocolVersion],\n ) -> bytes:\n buf = Buffer(\n + capacity=7\n - capacity=6\n + len(destination_cid)\n + len(source_cid)\n + 4 * len(supported_versions)\n )\n buf.push_uint8(os.urandom(1)[0] | PACKET_LONG_HEADER)\n buf.push_uint32(QuicProtocolVersion.NEGOTIATION)\n - buf.push_uint8(\n - (encode_cid_length(len(destination_cid)) << 4)\n - | encode_cid_length(len(source_cid))\n - )\n + buf.push_uint8(len(destination_cid))\n buf.push_bytes(destination_cid)\n + buf.push_uint8(len(source_cid))\n buf.push_bytes(source_cid)\n for version in supported_versions:\n buf.push_uint32(version)\n return buf.data\n "}}},{"rowIdx":2991,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection._handle_reset_stream_frame"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <4>: error_code = buf.pull_uint_var()\n error_code = buf.pull_uint16()\n"},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def _handle_reset_stream_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n <0> \"\"\"\n <1> Handle a RESET_STREAM frame.\n <2> \"\"\"\n <3> stream_id = buf.pull_uint_var()\n <4> error_code = buf.pull_uint16()\n <5> final_size = buf.pull_uint_var()\n <6> \n <7> # check stream direction\n <8> self._assert_stream_can_receive(frame_type, stream_id)\n <9> \n<10> self._logger.info(\n<11> \"Stream %d reset by peer (error code %d, final size %d)\",\n<12> stream_id,\n<13> error_code,\n<14> final_size,\n<15> )\n<16> # stream = self._get_or_create_stream(frame_type, stream_id)\n<17> self._events.append(events.StreamReset(stream_id=stream_id))\n<18> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n pull_uint16() -> int\n \n pull_uint_var() -> int\n \n at: aioquic.connection\n QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, time: float)\n \n at: aioquic.connection.QuicConnection\n _assert_stream_can_receive(frame_type: int, stream_id: int) -> None\n \n at: aioquic.connection.QuicConnection.__init__\n self._events: Deque[events.Event] = deque()\n \n self._logger = QuicConnectionAdapter(\n logger, {\"host_cid\": dump_cid(self.host_cid)}\n )\n \n at: aioquic.events\n StreamReset(stream_id: int)\n \n at: aioquic.events.StreamReset\n stream_id: int\n \n at: collections.deque\n append(x: _T) -> None\n \n at: logging.LoggerAdapter\n info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_new_connection_id_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n \"\"\"\n Handle a NEW_CONNECTION_ID frame.\n \"\"\"\n + sequence_number, retire_prior_to, cid, stateless_reset_token = pull_new_connection_id_frame(\n - sequence_number, cid, stateless_reset_token = pull_new_connection_id_frame(buf)\n + buf\n + )\n self._logger.debug(\n \"New connection ID received %d %s\", sequence_number, dump_cid(cid)\n )\n self._peer_cid_available.append(\n QuicConnectionId(\n cid=cid,\n sequence_number=sequence_number,\n stateless_reset_token=stateless_reset_token,\n )\n )\n \n===========changed ref 1===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 2===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - \n===========changed ref 3===========\n # module: aioquic.packet\n def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, reason_phrase)\n \n===========changed ref 4===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 5===========\n # module: aioquic.packet\n def push_new_connection_id_frame(\n buf: Buffer,\n sequence_number: int,\n + retire_prior_to: int,\n connection_id: bytes,\n stateless_reset_token: bytes,\n ) -> None:\n assert len(stateless_reset_token) == 16\n buf.push_uint_var(sequence_number)\n + buf.push_uint_var(retire_prior_to)\n buf.push_uint8(len(connection_id))\n buf.push_bytes(connection_id)\n buf.push_bytes(stateless_reset_token)\n \n===========changed ref 6===========\n # module: aioquic.packet\n def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n frame_type = buf.pull_uint_var()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, frame_type, reason_phrase)\n \n===========changed ref 7===========\n # module: aioquic.packet\n + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]:\n - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, bytes, bytes]:\n sequence_number = buf.pull_uint_var()\n + retire_prior_to = buf.pull_uint_var()\n length = buf.pull_uint8()\n connection_id = buf.pull_bytes(length)\n stateless_reset_token = buf.pull_bytes(16)\n + return (sequence_number, retire_prior_to, connection_id, stateless_reset_token)\n - return (sequence_number, connection_id, stateless_reset_token)\n \n===========changed ref 8===========\n # module: aioquic.configuration\n @dataclass\n class QuicConfiguration:\n alpn_protocols: Optional[List[str]] = None\n certificate: Any = None\n idle_timeout: float = 60.0\n is_client: bool = True\n private_key: Any = None\n secrets_log_file: TextIO = None\n server_name: Optional[str] = None\n session_ticket: Optional[tls.SessionTicket] = None\n supported_versions: List[QuicProtocolVersion] = field(\n - default_factory=lambda: [\n - QuicProtocolVersion.DRAFT_19,\n - QuicProtocolVersion.DRAFT_20,\n - ]\n + default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n===========changed ref 9===========\n # module: aioquic.packet\n PARAMS = [\n (\"original_connection_id\", bytes),\n (\"idle_timeout\", int),\n (\"stateless_reset_token\", bytes),\n (\"max_packet_size\", int),\n (\"initial_max_data\", int),\n (\"initial_max_stream_data_bidi_local\", int),\n (\"initial_max_stream_data_bidi_remote\", int),\n (\"initial_max_stream_data_uni\", int),\n (\"initial_max_streams_bidi\", int),\n (\"initial_max_streams_uni\", int),\n (\"ack_delay_exponent\", int),\n (\"max_ack_delay\", int),\n (\"disable_migration\", bool),\n (\"preferred_address\", bytes),\n + (\"active_connection_id_limit\", int),\n ]\n \n===========changed ref 10===========\n # module: aioquic.connection\n def write_close_frame(\n builder: QuicPacketBuilder,\n error_code: int,\n frame_type: Optional[int],\n reason_phrase: str,\n ) -> None:\n buf = builder.buffer\n \n reason_bytes = reason_phrase.encode(\"utf8\")\n \n if frame_type is None:\n builder.start_frame(QuicFrameType.APPLICATION_CLOSE)\n + buf.push_uint_var(error_code)\n - buf.push_uint16(error_code)\n buf.push_uint_var(len(reason_bytes))\n buf.push_bytes(reason_bytes)\n else:\n builder.start_frame(QuicFrameType.TRANSPORT_CLOSE)\n + buf.push_uint_var(error_code)\n - buf.push_uint16(error_code)\n buf.push_uint_var(frame_type)\n buf.push_uint_var(len(reason_bytes))\n buf.push_bytes(reason_bytes)\n "}}},{"rowIdx":2992,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection._handle_stop_sending_frame"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <4>: buf.pull_uint_var() # application error code\n buf.pull_uint16() # application error code\n"},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def _handle_stop_sending_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n <0> \"\"\"\n <1> Handle a STOP_SENDING frame.\n <2> \"\"\"\n <3> stream_id = buf.pull_uint_var()\n <4> buf.pull_uint16() # application error code\n <5> \n <6> # check stream direction\n <7> self._assert_stream_can_send(frame_type, stream_id)\n <8> \n <9> self._get_or_create_stream(frame_type, stream_id)\n<10> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n pull_uint16() -> int\n \n pull_uint_var() -> int\n \n at: aioquic.connection\n QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, time: float)\n \n at: aioquic.connection.QuicConnection\n _assert_stream_can_send(frame_type: int, stream_id: int) -> None\n \n _get_or_create_stream(frame_type: int, stream_id: int) -> QuicStream\n \n \n===========changed ref 0===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_reset_stream_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n \"\"\"\n Handle a RESET_STREAM frame.\n \"\"\"\n stream_id = buf.pull_uint_var()\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n final_size = buf.pull_uint_var()\n \n # check stream direction\n self._assert_stream_can_receive(frame_type, stream_id)\n \n self._logger.info(\n \"Stream %d reset by peer (error code %d, final size %d)\",\n stream_id,\n error_code,\n final_size,\n )\n # stream = self._get_or_create_stream(frame_type, stream_id)\n self._events.append(events.StreamReset(stream_id=stream_id))\n \n===========changed ref 1===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_new_connection_id_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n \"\"\"\n Handle a NEW_CONNECTION_ID frame.\n \"\"\"\n + sequence_number, retire_prior_to, cid, stateless_reset_token = pull_new_connection_id_frame(\n - sequence_number, cid, stateless_reset_token = pull_new_connection_id_frame(buf)\n + buf\n + )\n self._logger.debug(\n \"New connection ID received %d %s\", sequence_number, dump_cid(cid)\n )\n self._peer_cid_available.append(\n QuicConnectionId(\n cid=cid,\n sequence_number=sequence_number,\n stateless_reset_token=stateless_reset_token,\n )\n )\n \n===========changed ref 2===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 3===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - \n===========changed ref 4===========\n # module: aioquic.packet\n def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, reason_phrase)\n \n===========changed ref 5===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 6===========\n # module: aioquic.packet\n def push_new_connection_id_frame(\n buf: Buffer,\n sequence_number: int,\n + retire_prior_to: int,\n connection_id: bytes,\n stateless_reset_token: bytes,\n ) -> None:\n assert len(stateless_reset_token) == 16\n buf.push_uint_var(sequence_number)\n + buf.push_uint_var(retire_prior_to)\n buf.push_uint8(len(connection_id))\n buf.push_bytes(connection_id)\n buf.push_bytes(stateless_reset_token)\n \n===========changed ref 7===========\n # module: aioquic.packet\n def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n frame_type = buf.pull_uint_var()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, frame_type, reason_phrase)\n \n===========changed ref 8===========\n # module: aioquic.packet\n + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]:\n - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, bytes, bytes]:\n sequence_number = buf.pull_uint_var()\n + retire_prior_to = buf.pull_uint_var()\n length = buf.pull_uint8()\n connection_id = buf.pull_bytes(length)\n stateless_reset_token = buf.pull_bytes(16)\n + return (sequence_number, retire_prior_to, connection_id, stateless_reset_token)\n - return (sequence_number, connection_id, stateless_reset_token)\n \n===========changed ref 9===========\n # module: aioquic.configuration\n @dataclass\n class QuicConfiguration:\n alpn_protocols: Optional[List[str]] = None\n certificate: Any = None\n idle_timeout: float = 60.0\n is_client: bool = True\n private_key: Any = None\n secrets_log_file: TextIO = None\n server_name: Optional[str] = None\n session_ticket: Optional[tls.SessionTicket] = None\n supported_versions: List[QuicProtocolVersion] = field(\n - default_factory=lambda: [\n - QuicProtocolVersion.DRAFT_19,\n - QuicProtocolVersion.DRAFT_20,\n - ]\n + default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n===========changed ref 10===========\n # module: aioquic.packet\n PARAMS = [\n (\"original_connection_id\", bytes),\n (\"idle_timeout\", int),\n (\"stateless_reset_token\", bytes),\n (\"max_packet_size\", int),\n (\"initial_max_data\", int),\n (\"initial_max_stream_data_bidi_local\", int),\n (\"initial_max_stream_data_bidi_remote\", int),\n (\"initial_max_stream_data_uni\", int),\n (\"initial_max_streams_bidi\", int),\n (\"initial_max_streams_uni\", int),\n (\"ack_delay_exponent\", int),\n (\"max_ack_delay\", int),\n (\"disable_migration\", bool),\n (\"preferred_address\", bytes),\n + (\"active_connection_id_limit\", int),\n ]\n "}}},{"rowIdx":2993,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection._replenish_connection_ids"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <3>: while len(self._host_cids) < self._remote_active_connection_id_limit:\n while len(self._host_cids) < 8:\n"},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def _replenish_connection_ids(self) -> None:\n <0> \"\"\"\n <1> Generate new connection IDs.\n <2> \"\"\"\n <3> while len(self._host_cids) < 8:\n <4> self._host_cids.append(\n <5> QuicConnectionId(\n <6> cid=os.urandom(8),\n <7> sequence_number=self._host_cid_seq,\n <8> stateless_reset_token=os.urandom(16),\n <9> )\n<10> )\n<11> self._host_cid_seq += 1\n<12> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.connection\n QuicConnectionId(cid: bytes, sequence_number: int, stateless_reset_token: bytes=b\"\", was_sent: bool=False)\n \n at: aioquic.connection.QuicConnection.__init__\n self._host_cids = [\n QuicConnectionId(\n cid=os.urandom(8),\n sequence_number=0,\n stateless_reset_token=os.urandom(16),\n was_sent=True,\n )\n ]\n \n self._host_cid_seq = 1\n \n at: os\n urandom(size: int, /) -> bytes\n \n \n===========changed ref 0===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_stop_sending_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n \"\"\"\n Handle a STOP_SENDING frame.\n \"\"\"\n stream_id = buf.pull_uint_var()\n + buf.pull_uint_var() # application error code\n - buf.pull_uint16() # application error code\n \n # check stream direction\n self._assert_stream_can_send(frame_type, stream_id)\n \n self._get_or_create_stream(frame_type, stream_id)\n \n===========changed ref 1===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_reset_stream_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n \"\"\"\n Handle a RESET_STREAM frame.\n \"\"\"\n stream_id = buf.pull_uint_var()\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n final_size = buf.pull_uint_var()\n \n # check stream direction\n self._assert_stream_can_receive(frame_type, stream_id)\n \n self._logger.info(\n \"Stream %d reset by peer (error code %d, final size %d)\",\n stream_id,\n error_code,\n final_size,\n )\n # stream = self._get_or_create_stream(frame_type, stream_id)\n self._events.append(events.StreamReset(stream_id=stream_id))\n \n===========changed ref 2===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_new_connection_id_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n \"\"\"\n Handle a NEW_CONNECTION_ID frame.\n \"\"\"\n + sequence_number, retire_prior_to, cid, stateless_reset_token = pull_new_connection_id_frame(\n - sequence_number, cid, stateless_reset_token = pull_new_connection_id_frame(buf)\n + buf\n + )\n self._logger.debug(\n \"New connection ID received %d %s\", sequence_number, dump_cid(cid)\n )\n self._peer_cid_available.append(\n QuicConnectionId(\n cid=cid,\n sequence_number=sequence_number,\n stateless_reset_token=stateless_reset_token,\n )\n )\n \n===========changed ref 3===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 4===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - \n===========changed ref 5===========\n # module: aioquic.packet\n def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, reason_phrase)\n \n===========changed ref 6===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 7===========\n # module: aioquic.packet\n def push_new_connection_id_frame(\n buf: Buffer,\n sequence_number: int,\n + retire_prior_to: int,\n connection_id: bytes,\n stateless_reset_token: bytes,\n ) -> None:\n assert len(stateless_reset_token) == 16\n buf.push_uint_var(sequence_number)\n + buf.push_uint_var(retire_prior_to)\n buf.push_uint8(len(connection_id))\n buf.push_bytes(connection_id)\n buf.push_bytes(stateless_reset_token)\n \n===========changed ref 8===========\n # module: aioquic.packet\n def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n frame_type = buf.pull_uint_var()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, frame_type, reason_phrase)\n \n===========changed ref 9===========\n # module: aioquic.packet\n + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]:\n - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, bytes, bytes]:\n sequence_number = buf.pull_uint_var()\n + retire_prior_to = buf.pull_uint_var()\n length = buf.pull_uint8()\n connection_id = buf.pull_bytes(length)\n stateless_reset_token = buf.pull_bytes(16)\n + return (sequence_number, retire_prior_to, connection_id, stateless_reset_token)\n - return (sequence_number, connection_id, stateless_reset_token)\n \n===========changed ref 10===========\n # module: aioquic.configuration\n @dataclass\n class QuicConfiguration:\n alpn_protocols: Optional[List[str]] = None\n certificate: Any = None\n idle_timeout: float = 60.0\n is_client: bool = True\n private_key: Any = None\n secrets_log_file: TextIO = None\n server_name: Optional[str] = None\n session_ticket: Optional[tls.SessionTicket] = None\n supported_versions: List[QuicProtocolVersion] = field(\n - default_factory=lambda: [\n - QuicProtocolVersion.DRAFT_19,\n - QuicProtocolVersion.DRAFT_20,\n - ]\n + default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n===========changed ref 11===========\n # module: aioquic.packet\n PARAMS = [\n (\"original_connection_id\", bytes),\n (\"idle_timeout\", int),\n (\"stateless_reset_token\", bytes),\n (\"max_packet_size\", int),\n (\"initial_max_data\", int),\n (\"initial_max_stream_data_bidi_local\", int),\n (\"initial_max_stream_data_bidi_remote\", int),\n (\"initial_max_stream_data_uni\", int),\n (\"initial_max_streams_bidi\", int),\n (\"initial_max_streams_uni\", int),\n (\"ack_delay_exponent\", int),\n (\"max_ack_delay\", int),\n (\"disable_migration\", bool),\n (\"preferred_address\", bytes),\n + (\"active_connection_id_limit\", int),\n ]\n "}}},{"rowIdx":2994,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection._parse_transport_parameters"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":"<18>: if quic_transport_parameters.active_connection_id_limit is not None:\n self._remote_active_connection_id_limit = (\n quic_transport_parameters.active_connection_id_limit\n )\n"},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def _parse_transport_parameters(\n self, data: bytes, from_session_ticket: bool = False\n ) -> None:\n <0> quic_transport_parameters = pull_quic_transport_parameters(Buffer(data=data))\n <1> \n <2> # validate remote parameters\n <3> if (\n <4> self._is_client\n <5> and not from_session_ticket\n <6> and (\n <7> quic_transport_parameters.original_connection_id\n <8> != self._original_connection_id\n <9> )\n<10> ):\n<11> raise QuicConnectionError(\n<12> error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR,\n<13> frame_type=QuicFrameType.CRYPTO,\n<14> reason_phrase=\"original_connection_id does not match\",\n<15> )\n<16> \n<17> # store remote parameters\n<18> if quic_transport_parameters.idle_timeout is not None:\n<19> self._remote_idle_timeout = quic_transport_parameters.idle_timeout / 1000.0\n<20> for param in [\"ack_delay_exponent\", \"max_ack_delay\"]:\n<21> value = getattr(quic_transport_parameters, param)\n<22> if value is not None:\n<23> setattr(self._loss, param, value)\n<24> for param in [\n<25> \"max_data\",\n<26> \"max_stream_data_bidi_local\",\n<27> \"max_stream_data_bidi_remote\",\n<28> \"max_stream_data_uni\",\n<29> \"max_streams_bidi\",\n<30> \"max_streams_uni\",\n<31> ]:\n<32> value = getattr(quic_transport_parameters, \"initial_\" + param)\n<33> if value is not None:\n<34> setattr(self, \"_remote_\" + param, value)\n<35> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic.connection\n QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str)\n \n at: aioquic.connection.QuicConnection.__init__\n self._is_client = configuration.is_client\n \n self._loss = QuicPacketRecovery(\n is_client_without_1rtt=self._is_client, send_probe=self._send_probe\n )\n \n self._original_connection_id = original_connection_id\n \n self._remote_idle_timeout = 0.0 # seconds\n \n at: aioquic.connection.QuicConnection.receive_datagram\n self._original_connection_id = self._peer_cid\n \n at: aioquic.packet\n QuicErrorCode(x: Union[str, bytes, bytearray], base: int)\n QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n pull_quic_transport_parameters(buf: Buffer) -> QuicTransportParameters\n \n QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n QuicFrameType(x: Union[str, bytes, bytearray], base: int)\n \n at: aioquic.packet.QuicTransportParameters\n initial_version: Optional[QuicProtocolVersion] = None\n \n negotiated_version: Optional[QuicProtocolVersion] = None\n \n supported_versions: List[QuicProtocolVersion] = field(default_factory=list)\n \n original_connection_id: Optional[bytes] = None\n \n idle_timeout: Optional[int] = None\n \n stateless_reset_token: Optional[bytes] = None\n \n max_packet_size: Optional[int] = None\n \n initial_max_data: Optional[int] = None\n \n initial_max_stream_data_bidi_local: Optional[int] = None\n \n initial_max_stream_data_bidi_remote: Optional[int] = None\n \n \n===========unchanged ref 1===========\n initial_max_stream_data_uni: Optional[int] = None\n \n initial_max_streams_bidi: Optional[int] = None\n \n initial_max_streams_uni: Optional[int] = None\n \n ack_delay_exponent: Optional[int] = None\n \n max_ack_delay: Optional[int] = None\n \n disable_migration: Optional[bool] = False\n \n preferred_address: Optional[bytes] = None\n \n active_connection_id_limit: Optional[int] = None\n \n \n===========changed ref 0===========\n # module: aioquic.connection\n class QuicConnection:\n def _replenish_connection_ids(self) -> None:\n \"\"\"\n Generate new connection IDs.\n \"\"\"\n + while len(self._host_cids) < self._remote_active_connection_id_limit:\n - while len(self._host_cids) < 8:\n self._host_cids.append(\n QuicConnectionId(\n cid=os.urandom(8),\n sequence_number=self._host_cid_seq,\n stateless_reset_token=os.urandom(16),\n )\n )\n self._host_cid_seq += 1\n \n===========changed ref 1===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_stop_sending_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n \"\"\"\n Handle a STOP_SENDING frame.\n \"\"\"\n stream_id = buf.pull_uint_var()\n + buf.pull_uint_var() # application error code\n - buf.pull_uint16() # application error code\n \n # check stream direction\n self._assert_stream_can_send(frame_type, stream_id)\n \n self._get_or_create_stream(frame_type, stream_id)\n \n===========changed ref 2===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_reset_stream_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n \"\"\"\n Handle a RESET_STREAM frame.\n \"\"\"\n stream_id = buf.pull_uint_var()\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n final_size = buf.pull_uint_var()\n \n # check stream direction\n self._assert_stream_can_receive(frame_type, stream_id)\n \n self._logger.info(\n \"Stream %d reset by peer (error code %d, final size %d)\",\n stream_id,\n error_code,\n final_size,\n )\n # stream = self._get_or_create_stream(frame_type, stream_id)\n self._events.append(events.StreamReset(stream_id=stream_id))\n \n===========changed ref 3===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_new_connection_id_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n \"\"\"\n Handle a NEW_CONNECTION_ID frame.\n \"\"\"\n + sequence_number, retire_prior_to, cid, stateless_reset_token = pull_new_connection_id_frame(\n - sequence_number, cid, stateless_reset_token = pull_new_connection_id_frame(buf)\n + buf\n + )\n self._logger.debug(\n \"New connection ID received %d %s\", sequence_number, dump_cid(cid)\n )\n self._peer_cid_available.append(\n QuicConnectionId(\n cid=cid,\n sequence_number=sequence_number,\n stateless_reset_token=stateless_reset_token,\n )\n )\n \n===========changed ref 4===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 5===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - \n===========changed ref 6===========\n # module: aioquic.packet\n def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, reason_phrase)\n \n===========changed ref 7===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 8===========\n # module: aioquic.packet\n def push_new_connection_id_frame(\n buf: Buffer,\n sequence_number: int,\n + retire_prior_to: int,\n connection_id: bytes,\n stateless_reset_token: bytes,\n ) -> None:\n assert len(stateless_reset_token) == 16\n buf.push_uint_var(sequence_number)\n + buf.push_uint_var(retire_prior_to)\n buf.push_uint8(len(connection_id))\n buf.push_bytes(connection_id)\n buf.push_bytes(stateless_reset_token)\n "}}},{"rowIdx":2995,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection._serialize_transport_parameters"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <1>: active_connection_id_limit=self._local_active_connection_id_limit,\n"},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def _serialize_transport_parameters(self) -> bytes:\n <0> quic_transport_parameters = QuicTransportParameters(\n <1> idle_timeout=int(self._configuration.idle_timeout * 1000),\n <2> initial_max_data=self._local_max_data,\n <3> initial_max_stream_data_bidi_local=self._local_max_stream_data_bidi_local,\n <4> initial_max_stream_data_bidi_remote=self._local_max_stream_data_bidi_remote,\n <5> initial_max_stream_data_uni=self._local_max_stream_data_uni,\n <6> initial_max_streams_bidi=self._local_max_streams_bidi,\n <7> initial_max_streams_uni=self._local_max_streams_uni,\n <8> ack_delay_exponent=10,\n <9> )\n<10> if not self._is_client:\n<11> quic_transport_parameters.original_connection_id = (\n<12> self._original_connection_id\n<13> )\n<14> \n<15> buf = Buffer(capacity=512)\n<16> push_quic_transport_parameters(buf, quic_transport_parameters)\n<17> return buf.data\n<18> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic.configuration.QuicConfiguration\n idle_timeout: float = 60.0\n \n at: aioquic.connection.QuicConnection.__init__\n self._configuration = configuration\n \n self._is_client = configuration.is_client\n \n self._local_max_data = MAX_DATA_WINDOW\n \n self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW\n \n self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW\n \n self._local_max_stream_data_uni = MAX_DATA_WINDOW\n \n self._local_max_streams_bidi = 128\n \n self._local_max_streams_uni = 128\n \n self._original_connection_id = original_connection_id\n \n at: aioquic.connection.QuicConnection._write_connection_limits\n self._local_max_data *= 2\n \n at: aioquic.connection.QuicConnection.receive_datagram\n self._original_connection_id = self._peer_cid\n \n \n===========unchanged ref 1===========\n at: aioquic.packet\n 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)\n \n push_quic_transport_parameters(buf: Buffer, params: QuicTransportParameters) -> None\n \n at: aioquic.packet.QuicTransportParameters\n original_connection_id: Optional[bytes] = None\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n # TLS EXTENSION\n \n \n @dataclass\n class QuicTransportParameters:\n initial_version: Optional[QuicProtocolVersion] = None\n negotiated_version: Optional[QuicProtocolVersion] = None\n supported_versions: List[QuicProtocolVersion] = field(default_factory=list)\n \n original_connection_id: Optional[bytes] = None\n idle_timeout: Optional[int] = None\n stateless_reset_token: Optional[bytes] = None\n max_packet_size: Optional[int] = None\n initial_max_data: Optional[int] = None\n initial_max_stream_data_bidi_local: Optional[int] = None\n initial_max_stream_data_bidi_remote: Optional[int] = None\n initial_max_stream_data_uni: Optional[int] = None\n initial_max_streams_bidi: Optional[int] = None\n initial_max_streams_uni: Optional[int] = None\n ack_delay_exponent: Optional[int] = None\n max_ack_delay: Optional[int] = None\n disable_migration: Optional[bool] = False\n preferred_address: Optional[bytes] = None\n + active_connection_id_limit: Optional[int] = None\n \n===========changed ref 1===========\n # module: aioquic.connection\n class QuicConnection:\n def _replenish_connection_ids(self) -> None:\n \"\"\"\n Generate new connection IDs.\n \"\"\"\n + while len(self._host_cids) < self._remote_active_connection_id_limit:\n - while len(self._host_cids) < 8:\n self._host_cids.append(\n QuicConnectionId(\n cid=os.urandom(8),\n sequence_number=self._host_cid_seq,\n stateless_reset_token=os.urandom(16),\n )\n )\n self._host_cid_seq += 1\n \n===========changed ref 2===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_stop_sending_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n \"\"\"\n Handle a STOP_SENDING frame.\n \"\"\"\n stream_id = buf.pull_uint_var()\n + buf.pull_uint_var() # application error code\n - buf.pull_uint16() # application error code\n \n # check stream direction\n self._assert_stream_can_send(frame_type, stream_id)\n \n self._get_or_create_stream(frame_type, stream_id)\n \n===========changed ref 3===========\n # module: aioquic.connection\n class QuicConnection:\n def _parse_transport_parameters(\n self, data: bytes, from_session_ticket: bool = False\n ) -> None:\n quic_transport_parameters = pull_quic_transport_parameters(Buffer(data=data))\n \n # validate remote parameters\n if (\n self._is_client\n and not from_session_ticket\n and (\n quic_transport_parameters.original_connection_id\n != self._original_connection_id\n )\n ):\n raise QuicConnectionError(\n error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR,\n frame_type=QuicFrameType.CRYPTO,\n reason_phrase=\"original_connection_id does not match\",\n )\n \n # store remote parameters\n + if quic_transport_parameters.active_connection_id_limit is not None:\n + self._remote_active_connection_id_limit = (\n + quic_transport_parameters.active_connection_id_limit\n + )\n if quic_transport_parameters.idle_timeout is not None:\n self._remote_idle_timeout = quic_transport_parameters.idle_timeout / 1000.0\n for param in [\"ack_delay_exponent\", \"max_ack_delay\"]:\n value = getattr(quic_transport_parameters, param)\n if value is not None:\n setattr(self._loss, param, value)\n for param in [\n \"max_data\",\n \"max_stream_data_bidi_local\",\n \"max_stream_data_bidi_remote\",\n \"max_stream_data_uni\",\n \"max_streams_bidi\",\n \"max_streams_uni\",\n ]:\n value = getattr(quic_transport_parameters, \"initial_\" + param)\n if value is not None:\n setattr(self, \"_remote_\" + param, value)\n \n===========changed ref 4===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_reset_stream_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n \"\"\"\n Handle a RESET_STREAM frame.\n \"\"\"\n stream_id = buf.pull_uint_var()\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n final_size = buf.pull_uint_var()\n \n # check stream direction\n self._assert_stream_can_receive(frame_type, stream_id)\n \n self._logger.info(\n \"Stream %d reset by peer (error code %d, final size %d)\",\n stream_id,\n error_code,\n final_size,\n )\n # stream = self._get_or_create_stream(frame_type, stream_id)\n self._events.append(events.StreamReset(stream_id=stream_id))\n "}}},{"rowIdx":2996,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection._write_application"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def _write_application(\n self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float\n ) -> None:\n <0> crypto_stream: Optional[QuicStream] = None\n <1> if self._cryptos[tls.Epoch.ONE_RTT].send.is_valid():\n <2> crypto = self._cryptos[tls.Epoch.ONE_RTT]\n <3> crypto_stream = self._crypto_streams[tls.Epoch.ONE_RTT]\n <4> packet_type = PACKET_TYPE_ONE_RTT\n <5> elif self._cryptos[tls.Epoch.ZERO_RTT].send.is_valid():\n <6> crypto = self._cryptos[tls.Epoch.ZERO_RTT]\n <7> packet_type = PACKET_TYPE_ZERO_RTT\n <8> else:\n <9> return\n<10> space = self._spaces[tls.Epoch.ONE_RTT]\n<11> \n<12> buf = builder.buffer\n<13> \n<14> while True:\n<15> # write header\n<16> builder.start_packet(packet_type, crypto)\n<17> \n<18> if self._handshake_complete:\n<19> # ACK\n<20> if space.ack_at is not None and space.ack_at <= now:\n<21> builder.start_frame(\n<22> QuicFrameType.ACK,\n<23> self._on_ack_delivery,\n<24> (space, space.largest_received_packet),\n<25> )\n<26> push_ack_frame(buf, space.ack_queue, 0)\n<27> space.ack_at = None\n<28> \n<29> # PATH CHALLENGE\n<30> if (\n<31> not network_path.is_validated\n<32> and network_path.local_challenge is None\n<33> ):\n<34> self._logger.info(\n<35> \"Network path %s sending challenge\", network_path.addr\n<36> )\n<37> network_path.local_challenge = os.urandom(8)\n<38> builder.start_frame(QuicFrameType.PATH_CHALLENGE)\n<39> buf.push_bytes"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.connection\n class QuicConnection:\n def _write_application(\n self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float\n ) -> None:\n # offset: 1\n \n # PATH RESPONSE\n if network_path.remote_challenge is not None:\n builder.start_frame(QuicFrameType.PATH_RESPONSE)\n buf.push_bytes(network_path.remote_challenge)\n network_path.remote_challenge = None\n \n # NEW_CONNECTION_ID\n for connection_id in self._host_cids:\n if not connection_id.was_sent:\n builder.start_frame(\n QuicFrameType.NEW_CONNECTION_ID,\n self._on_new_connection_id_delivery,\n (connection_id,),\n )\n push_new_connection_id_frame(\n buf,\n connection_id.sequence_number,\n connection_id.cid,\n connection_id.stateless_reset_token,\n )\n connection_id.was_sent = True\n self._events.append(\n events.ConnectionIdIssued(connection_id=connection_id.cid)\n )\n \n # RETIRE_CONNECTION_ID\n while self._retire_connection_ids:\n sequence_number = self._retire_connection_ids.pop(0)\n builder.start_frame(\n QuicFrameType.RETIRE_CONNECTION_ID,\n self._on_retire_connection_id_delivery,\n (sequence_number,),\n )\n buf.push_uint_var(sequence_number)\n \n # STREAMS_BLOCKED\n if self._streams_blocked_pending:\n if self._streams_blocked_bidi:\n builder.start_frame(QuicFrameType.STREAMS_BLOCKED_BIDI)\n buf.push_uint_var(self._remote_max_streams_bidi)\n if self._streams_blocked_uni:\n builder.start_frame(QuicFrameType.STREAMS_BLOCKED_UNI)\n buf.push_\n===========below chunk 1===========\n # module: aioquic.connection\n class QuicConnection:\n def _write_application(\n self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float\n ) -> None:\n # offset: 2\n uni:\n builder.start_frame(QuicFrameType.STREAMS_BLOCKED_UNI)\n buf.push_uint_var(self._remote_max_streams_uni)\n self._streams_blocked_pending = False\n \n # connection-level limits\n self._write_connection_limits(builder=builder, space=space)\n \n # stream-level limits\n for stream in self._streams.values():\n self._write_stream_limits(builder=builder, space=space, stream=stream)\n \n # PING (user-request)\n if self._ping_pending:\n self._logger.info(\"Sending PING in packet %d\", builder.packet_number)\n builder.start_frame(\n QuicFrameType.PING,\n self._on_ping_delivery,\n (tuple(self._ping_pending),),\n )\n self._ping_pending.clear()\n \n # PING (probe)\n if self._probe_pending:\n self._logger.info(\"Sending probe\")\n builder.start_frame(QuicFrameType.PING)\n self._probe_pending = False\n \n # CRYPTO\n if crypto_stream is not None and not crypto_stream.send_buffer_is_empty:\n write_crypto_frame(builder=builder, space=space, stream=crypto_stream)\n \n for stream in self._streams.values():\n # STREAM\n if not stream.is_blocked and not stream.send_buffer_is_empty:\n self._remote_max_data_used += write_stream_frame(\n builder=builder,\n space=space,\n stream=stream,\n max_offset=min(\n stream._send_highest\n + self._remote_max_data\n \n===========below chunk 2===========\n # module: aioquic.connection\n class QuicConnection:\n def _write_application(\n self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float\n ) -> None:\n # offset: 3\n self._remote_max_data_used,\n stream.max_stream_data_remote,\n ),\n )\n \n if not builder.end_packet():\n break\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer.Buffer\n push_bytes(value: bytes) -> None\n \n push_uint_var(value: int) -> None\n \n at: aioquic.connection\n write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None\n \n write_stream_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream, max_offset: int) -> int\n \n QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None)\n \n at: aioquic.connection.QuicConnection\n _on_ack_delivery(delivery: QuicDeliveryState, space: QuicPacketSpace, highest_acked: int) -> None\n \n _on_new_connection_id_delivery(delivery: QuicDeliveryState, connection_id: QuicConnectionId) -> None\n \n _on_ping_delivery(delivery: QuicDeliveryState, uids: Sequence[int]) -> None\n \n _on_retire_connection_id_delivery(delivery: QuicDeliveryState, sequence_number: int) -> None\n \n _write_connection_limits(builder: QuicPacketBuilder, space: QuicPacketSpace) -> None\n \n _write_stream_limits(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None\n \n at: aioquic.connection.QuicConnection.__init__\n self._cryptos: Dict[tls.Epoch, CryptoPair] = {}\n \n self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}\n \n self._events: Deque[events.Event] = deque()\n \n self._handshake_complete = False\n \n "}}},{"rowIdx":2997,"cells":{"path":{"kind":"string","value":"examples.http3-client/run"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":"<17>: alpn_protocols=[\"h3-22\"], is_client=True, server_name=server_name, **kwargs\n alpn_protocols=[\"h3-20\"], is_client=True, server_name=server_name, **kwargs\n"},"main_code":{"kind":"string","value":" # module: examples.http3-client\n def run(url: str, **kwargs) -> None:\n <0> # parse URL\n <1> parsed = urlparse(url)\n <2> assert parsed.scheme == \"https\", \"Only HTTPS URLs are supported.\"\n <3> if \":\" in parsed.netloc:\n <4> server_name, port_str = parsed.netloc.split(\":\")\n <5> port = int(port_str)\n <6> else:\n <7> server_name = parsed.netloc\n <8> port = 443\n <9> \n<10> # prepare socket\n<11> server_addr = (socket.gethostbyname(server_name), port)\n<12> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n<13> \n<14> # prepare QUIC connection\n<15> quic = QuicConnection(\n<16> configuration=QuicConfiguration(\n<17> alpn_protocols=[\"h3-20\"], is_client=True, server_name=server_name, **kwargs\n<18> ),\n<19> session_ticket_handler=save_session_ticket,\n<20> )\n<21> quic.connect(server_addr, now=time.time())\n<22> \n<23> # send request\n<24> http = H3Connection(quic)\n<25> stream_id = quic.get_next_available_stream_id()\n<26> http.send_headers(\n<27> stream_id=stream_id,\n<28> headers=[\n<29> (b\":method\", b\"GET\"),\n<30> (b\":scheme\", parsed.scheme.encode(\"utf8\")),\n<31> (b\":authority\", parsed.netloc.encode(\"utf8\")),\n<32> (b\":path\", parsed.path.encode(\"utf8\")),\n<33> ],\n<34> )\n<35> http.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n<36> for data, addr in quic.datagrams_to_send(now=time.time()):\n<37> sock.sendto(data, addr)\n<38> \n<39> # handle events\n<40> stream_ended = False\n<41> while not stream_ended:\n<42> "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: examples.http3-client\n def run(url: str, **kwargs) -> None:\n # offset: 1\n quic.receive_datagram(data, addr, now=time.time())\n for event in http.handle_events():\n print(event)\n if isinstance(event, (DataReceived, ResponseReceived)):\n stream_ended = event.stream_ended\n \n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n \n===========unchanged ref 0===========\n at: aioquic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n ))\n \n at: aioquic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n certificate: Any = None\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n private_key: Any = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[tls.SessionTicket] = None\n \n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n at: aioquic.connection\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.connection.QuicConnection\n connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None\n \n datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]]\n \n get_next_available_stream_id(is_unidirectional=False) -> int\n \n receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None\n \n at: aioquic.h3.connection\n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection\n handle_events() -> List[Event]\n \n \n===========unchanged ref 1===========\n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: Headers) -> None\n \n at: aioquic.h3.events\n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: examples.http3-client\n save_session_ticket(ticket)\n \n at: socket\n AF_INET: AddressFamily\n \n SOCK_DGRAM: SocketKind\n \n socket(family: int=..., type: int=..., proto: int=..., fileno: Optional[int]=...)\n \n gethostbyname(hostname: str) -> str\n \n at: socket.socket\n family: int\n \n type: int\n \n proto: int\n \n recvfrom(bufsize: int, flags: int=...) -> Tuple[bytes, _RetAddress]\n \n sendto(data: bytes, address: _Address) -> int\n sendto(data: bytes, flags: int, address: _Address) -> int\n \n at: time\n time() -> float\n \n at: urllib.parse\n urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult\n urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes\n \n \n===========changed ref 0===========\n # module: aioquic.configuration\n @dataclass\n class QuicConfiguration:\n alpn_protocols: Optional[List[str]] = None\n certificate: Any = None\n idle_timeout: float = 60.0\n is_client: bool = True\n private_key: Any = None\n secrets_log_file: TextIO = None\n server_name: Optional[str] = None\n session_ticket: Optional[tls.SessionTicket] = None\n supported_versions: List[QuicProtocolVersion] = field(\n - default_factory=lambda: [\n - QuicProtocolVersion.DRAFT_19,\n - QuicProtocolVersion.DRAFT_20,\n - ]\n + default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n===========changed ref 1===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 2===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - \n===========changed ref 3===========\n # module: aioquic.packet\n def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, reason_phrase)\n \n===========changed ref 4===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 5===========\n # module: aioquic.packet\n def push_new_connection_id_frame(\n buf: Buffer,\n sequence_number: int,\n + retire_prior_to: int,\n connection_id: bytes,\n stateless_reset_token: bytes,\n ) -> None:\n assert len(stateless_reset_token) == 16\n buf.push_uint_var(sequence_number)\n + buf.push_uint_var(retire_prior_to)\n buf.push_uint8(len(connection_id))\n buf.push_bytes(connection_id)\n buf.push_bytes(stateless_reset_token)\n \n===========changed ref 6===========\n # module: aioquic.packet\n def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n frame_type = buf.pull_uint_var()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, frame_type, reason_phrase)\n \n===========changed ref 7===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_stop_sending_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n \"\"\"\n Handle a STOP_SENDING frame.\n \"\"\"\n stream_id = buf.pull_uint_var()\n + buf.pull_uint_var() # application error code\n - buf.pull_uint16() # application error code\n \n # check stream direction\n self._assert_stream_can_send(frame_type, stream_id)\n \n self._get_or_create_stream(frame_type, stream_id)\n "}}},{"rowIdx":2998,"cells":{"path":{"kind":"string","value":"tests.test_connection/QuicConnectionTest.test_connect_with_alpn"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <1>: client_options={\"alpn_protocols\": [\"hq-22\", \"h3-22\"]},\n client_options={\"alpn_protocols\": [\"hq-20\", \"h3-20\"]},\n <2>: server_options={\"alpn_protocols\": [\"hq-22\"]},\n server_options={\"alpn_protocols\": [\"hq-20\"]},\n <7>: self.assertEqual(event.alpn_protocol, \"hq-22\")\n self.assertEqual(event.alpn_protocol, \"hq-20\")\n<14>: self.assertEqual(event.alpn_protocol, \"hq-22\")\n self.assertEqual(event.alpn_protocol, \"hq-20\")\n"},"main_code":{"kind":"string","value":" # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect_with_alpn(self):\n <0> with client_and_server(\n <1> client_options={\"alpn_protocols\": [\"hq-20\", \"h3-20\"]},\n <2> server_options={\"alpn_protocols\": [\"hq-20\"]},\n <3> ) as (client, server):\n <4> # check handshake completed\n <5> event = client.next_event()\n <6> self.assertEqual(type(event), events.HandshakeCompleted)\n <7> self.assertEqual(event.alpn_protocol, \"hq-20\")\n <8> for i in range(7):\n <9> self.assertEqual(type(client.next_event()), events.ConnectionIdIssued)\n<10> self.assertIsNone(client.next_event())\n<11> \n<12> event = server.next_event()\n<13> self.assertEqual(type(event), events.HandshakeCompleted)\n<14> self.assertEqual(event.alpn_protocol, \"hq-20\")\n<15> for i in range(7):\n<16> self.assertEqual(type(server.next_event()), events.ConnectionIdIssued)\n<17> self.assertIsNone(server.next_event())\n<18> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.events\n ConnectionIdIssued(connection_id: bytes)\n \n at: io\n StringIO(initial_value: Optional[str]=..., newline: Optional[str]=...)\n \n at: io.StringIO\n getvalue(self) -> str\n \n at: tests.test_connection\n client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={})\n \n at: tests.test_connection.QuicConnectionTest.test_connect_with_alpn\n event = server.next_event()\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n _testMethodDoc: str\n \n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertIsNone(obj: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n - def test_connect_draft_20(self):\n - self._test_connect_with_version(\n - client_versions=[QuicProtocolVersion.DRAFT_20],\n - server_versions=[QuicProtocolVersion.DRAFT_20],\n - )\n - \n===========changed ref 1===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n - def test_connect_draft_19(self):\n - self._test_connect_with_version(\n - client_versions=[QuicProtocolVersion.DRAFT_19],\n - server_versions=[QuicProtocolVersion.DRAFT_19],\n - )\n - \n===========changed ref 2===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n + def test_connect(self):\n + with client_and_server() as (client, server):\n + # check handshake completed\n + event = client.next_event()\n + self.assertEqual(type(event), events.HandshakeCompleted)\n + self.assertEqual(event.alpn_protocol, None)\n + self.assertEqual(event.early_data_accepted, False)\n + self.assertEqual(event.session_resumed, False)\n + for i in range(7):\n + self.assertEqual(type(client.next_event()), events.ConnectionIdIssued)\n + self.assertIsNone(client.next_event())\n + \n + event = server.next_event()\n + self.assertEqual(type(event), events.HandshakeCompleted)\n + self.assertEqual(event.alpn_protocol, None)\n + self.assertEqual(event.early_data_accepted, False)\n + self.assertEqual(event.session_resumed, False)\n + for i in range(7):\n + self.assertEqual(type(server.next_event()), events.ConnectionIdIssued)\n + self.assertIsNone(server.next_event())\n + \n + # check each endpoint has available connection IDs for the peer\n + self.assertEqual(\n + sequence_numbers(client._peer_cid_available), [1, 2, 3, 4, 5, 6, 7]\n + )\n + self.assertEqual(\n + sequence_numbers(server._peer_cid_available), [1, 2, 3, 4, 5, 6, 7]\n + )\n + \n + # client closes the connection\n + client.close()\n + self.assertEqual(transfer(client, server), 1)\n + \n + # check connection closes on the client side\n + client.handle_timer(client.get_timer())\n + event = client.next_event()\n + self.assertEqual(type(event), events.ConnectionTerminated)\n + self.assertEqual\n===========changed ref 3===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n + def test_connect(self):\n # offset: 1\n client.next_event()\n + self.assertEqual(type(event), events.ConnectionTerminated)\n + self.assertEqual(event.error_code, QuicErrorCode.NO_ERROR)\n + self.assertEqual(event.frame_type, None)\n + self.assertEqual(event.reason_phrase, \"\")\n + self.assertIsNone(client.next_event())\n + \n + # check connection closes on the server side\n + server.handle_timer(server.get_timer())\n + event = server.next_event()\n + self.assertEqual(type(event), events.ConnectionTerminated)\n + self.assertEqual(event.error_code, QuicErrorCode.NO_ERROR)\n + self.assertEqual(event.frame_type, None)\n + self.assertEqual(event.reason_phrase, \"\")\n + self.assertIsNone(server.next_event())\n + \n===========changed ref 4===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n - def _test_connect_with_version(self, client_versions, server_versions):\n - with client_and_server(\n - client_options={\"supported_versions\": client_versions},\n - server_options={\"supported_versions\": server_versions},\n - ) as (client, server):\n - # check handshake completed\n - event = client.next_event()\n - self.assertEqual(type(event), events.HandshakeCompleted)\n - self.assertEqual(event.alpn_protocol, None)\n - self.assertEqual(event.early_data_accepted, False)\n - self.assertEqual(event.session_resumed, False)\n - for i in range(7):\n - self.assertEqual(type(client.next_event()), events.ConnectionIdIssued)\n - self.assertIsNone(client.next_event())\n - \n - event = server.next_event()\n - self.assertEqual(type(event), events.HandshakeCompleted)\n - self.assertEqual(event.alpn_protocol, None)\n - self.assertEqual(event.early_data_accepted, False)\n - self.assertEqual(event.session_resumed, False)\n - for i in range(7):\n - self.assertEqual(type(server.next_event()), events.ConnectionIdIssued)\n - self.assertIsNone(server.next_event())\n - \n - # check each endpoint has available connection IDs for the peer\n - self.assertEqual(\n - sequence_numbers(client._peer_cid_available), [1, 2, 3, 4, 5, 6, 7]\n - )\n - self.assertEqual(\n - sequence_numbers(server._peer_cid_available), [1, 2, 3, 4, 5, 6, 7]\n - )\n - \n - # client closes the connection\n - client.close()\n - self.assertEqual(transfer(client, server), 1)\n - \n - # check connection closes on the client side\n "}}},{"rowIdx":2999,"cells":{"path":{"kind":"string","value":"tests.test_connection/QuicConnectionTest.test_connect_with_loss_1"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":"<37>: self.assertEqual(datagram_sizes(items), [1280, 1079])\n self.assertEqual(datagram_sizes(items), [1280, 1071])\n"},"main_code":{"kind":"string","value":" # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect_with_loss_1(self):\n <0> \"\"\"\n <1> Check connection is established even in the client's INITIAL is lost.\n <2> \"\"\"\n <3> \n <4> def datagram_sizes(items):\n <5> return [len(x[0]) for x in items]\n <6> \n <7> client = QuicConnection(configuration=QuicConfiguration(is_client=True))\n <8> client._ack_delay = 0\n <9> \n<10> server = QuicConnection(\n<11> configuration=QuicConfiguration(\n<12> is_client=False,\n<13> certificate=SERVER_CERTIFICATE,\n<14> private_key=SERVER_PRIVATE_KEY,\n<15> )\n<16> )\n<17> server._ack_delay = 0\n<18> \n<19> # client sends INITIAL\n<20> now = 0.0\n<21> client.connect(SERVER_ADDR, now=now)\n<22> items = client.datagrams_to_send(now=now)\n<23> self.assertEqual(datagram_sizes(items), [1280])\n<24> self.assertEqual(client.get_timer(), 1.0)\n<25> \n<26> # INITIAL is lost\n<27> now = 1.0\n<28> client.handle_timer(now=now)\n<29> items = client.datagrams_to_send(now=now)\n<30> self.assertEqual(datagram_sizes(items), [1280])\n<31> self.assertEqual(client.get_timer(), 3.0)\n<32> \n<33> # server receives INITIAL, sends INITIAL + HANDSHAKE\n<34> now = 1.1\n<35> server.receive_datagram(items[0][0], CLIENT_ADDR, now=now)\n<36> items = server.datagrams_to_send(now=now)\n<37> self.assertEqual(datagram_sizes(items), [1280, 1071])\n<38> self.assertEqual(server.get_timer(), 2.1)\n<39> self.assertEqual(len(server._loss.spaces[0].sent_packets), 1)\n<40> self.assertEqual(len(server._loss.spaces[1"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect_with_loss_1(self):\n # offset: 1\n \n # handshake continues normally\n now = 1.2\n client.receive_datagram(items[0][0], SERVER_ADDR, now=now)\n client.receive_datagram(items[1][0], SERVER_ADDR, now=now)\n items = client.datagrams_to_send(now=now)\n self.assertEqual(datagram_sizes(items), [1280, 216])\n self.assertAlmostEqual(client.get_timer(), 1.825)\n \n now = 1.3\n server.receive_datagram(items[0][0], CLIENT_ADDR, now=now)\n server.receive_datagram(items[1][0], CLIENT_ADDR, now=now)\n items = server.datagrams_to_send(now=now)\n self.assertEqual(datagram_sizes(items), [268])\n self.assertAlmostEqual(server.get_timer(), 1.825)\n self.assertEqual(len(server._loss.spaces[0].sent_packets), 0)\n self.assertEqual(len(server._loss.spaces[1].sent_packets), 1)\n \n now = 1.4\n client.receive_datagram(items[0][0], SERVER_ADDR, now=now)\n items = client.datagrams_to_send(now=now)\n self.assertEqual(datagram_sizes(items), [32])\n self.assertAlmostEqual(client.get_timer(), 61.4) # idle timeout\n self.assertTrue(isinstance(client.next_event(), events.HandshakeCompleted))\n \n now = 1.5\n server.receive_datagram(items[0][0], CLIENT_ADDR, now=now)\n items = server.datagrams_to_send(now=now)\n self.assertEqual(datagram_sizes(items), [])\n self.assertAlmostEqual(server.get_timer(), 61.5) # idle timeout\n===========below chunk 1===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect_with_loss_1(self):\n # offset: 2\n _sizes(items), [])\n self.assertAlmostEqual(server.get_timer(), 61.5) # idle timeout\n self.assertTrue(isinstance(server.next_event(), events.HandshakeCompleted))\n \n \n===========unchanged ref 0===========\n at: aioquic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n ))\n \n at: aioquic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n certificate: Any = None\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n private_key: Any = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[tls.SessionTicket] = None\n \n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n at: aioquic.connection\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.connection.QuicConnection\n connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None\n \n datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]]\n \n get_timer() -> Optional[float]\n \n handle_timer(now: float) -> None\n \n receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None\n \n at: aioquic.connection.QuicConnection.__init__\n self._ack_delay = K_GRANULARITY\n \n \n===========unchanged ref 1===========\n self._loss = QuicPacketRecovery(\n is_client_without_1rtt=self._is_client, send_probe=self._send_probe\n )\n \n at: aioquic.recovery.QuicPacketRecovery.__init__\n self.spaces: List[QuicPacketSpace] = []\n \n at: aioquic.recovery.QuicPacketSpace.__init__\n self.sent_packets: Dict[int, QuicSentPacket] = {}\n \n at: tests.test_connection\n CLIENT_ADDR = (\"1.2.3.4\", 1234)\n \n SERVER_ADDR = (\"2.3.4.5\", 4433)\n \n at: tests.test_connection.QuicConnectionTest.test_connect_with_loss_1\n datagram_sizes(items)\n \n client = QuicConnection(configuration=QuicConfiguration(is_client=True))\n \n server = QuicConnection(\n configuration=QuicConfiguration(\n is_client=False,\n certificate=SERVER_CERTIFICATE,\n private_key=SERVER_PRIVATE_KEY,\n )\n )\n \n at: tests.utils\n SERVER_CERTIFICATE = x509.load_pem_x509_certificate(\n load(\"ssl_cert.pem\"), backend=default_backend()\n )\n \n SERVER_PRIVATE_KEY = serialization.load_pem_private_key(\n load(\"ssl_key.pem\"), password=None, backend=default_backend()\n )\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertAlmostEqual(first: float, second: float, places: Optional[int]=..., msg: Any=..., delta: Optional[float]=...) -> None\n assertAlmostEqual(first: datetime.datetime, second: datetime.datetime, places: Optional[int]=..., msg: Any=..., delta: Optional[datetime.timedelta]=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.configuration\n @dataclass\n class QuicConfiguration:\n alpn_protocols: Optional[List[str]] = None\n certificate: Any = None\n idle_timeout: float = 60.0\n is_client: bool = True\n private_key: Any = None\n secrets_log_file: TextIO = None\n server_name: Optional[str] = None\n session_ticket: Optional[tls.SessionTicket] = None\n supported_versions: List[QuicProtocolVersion] = field(\n - default_factory=lambda: [\n - QuicProtocolVersion.DRAFT_19,\n - QuicProtocolVersion.DRAFT_20,\n - ]\n + default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n===========changed ref 1===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n - def test_connect_draft_20(self):\n - self._test_connect_with_version(\n - client_versions=[QuicProtocolVersion.DRAFT_20],\n - server_versions=[QuicProtocolVersion.DRAFT_20],\n - )\n - \n===========changed ref 2===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n - def test_connect_draft_19(self):\n - self._test_connect_with_version(\n - client_versions=[QuicProtocolVersion.DRAFT_19],\n - server_versions=[QuicProtocolVersion.DRAFT_19],\n - )\n - "}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":29,"numItemsPerPage":100,"numTotalItems":7800,"offset":2900,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NzY5MzE2OSwic3ViIjoiL2RhdGFzZXRzL2tyYWFsZmFyL0NvZWRpdG9yLXByb2Nlc3NlZC1kZW1vMiIsImV4cCI6MTc1NzY5Njc2OSwiaXNzIjoiaHR0cHM6Ly9odWdnaW5nZmFjZS5jbyJ9.Xdksr-m0D5b_I0pc08Apd1MFLI9nA4ajOIsqra6fpi7XTD1OIz9PFaNziwGFO8Fmo9nIJKaTVtTDKhIvNfKcBw","displayUrls":true},"discussionsStats":{"closed":0,"open":1,"total":1},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
path
stringlengths
9
117
type
stringclasses
2 values
project
stringclasses
10 values
commit_hash
stringlengths
40
40
commit_message
stringlengths
1
137
ground_truth
stringlengths
0
2.74k
main_code
stringlengths
102
3.37k
context
stringlengths
0
14.7k
aioquic.h3.connection/H3Connection.send_headers
Modified
aiortc~aioquic
8659358ef1848b547b3f4d4ae35757cb244b9a74
[http3] send SETTINGS frame on control stream
<8>:<add> self._send_stream_data( <add> stream_id, encode_frame(FrameType.HEADERS, header), False <add> ) <9>:<del> buf = Buffer(capacity=len(header) + 16) <10>:<del> buf.push_uint_var(FrameType.HEADERS) <11>:<del> buf.push_uint_var(len(header)) <12>:<del> buf.push_bytes(header) <13>:<del> <14>:<del> self._send_stream_data(stream_id, buf.data, False) <15>:<del>
# module: aioquic.h3.connection class H3Connection: def send_headers(self, stream_id: int, headers: Headers) -> None: <0> """ <1> Send headers on the given stream. <2> <3> To retrieve datagram which need to be sent over the network call the QUIC <4> connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send` <5> method. <6> """ <7> control, header = self._encoder.encode(stream_id, 0, headers) <8> <9> buf = Buffer(capacity=len(header) + 16) <10> buf.push_uint_var(FrameType.HEADERS) <11> buf.push_uint_var(len(header)) <12> buf.push_bytes(header) <13> <14> self._send_stream_data(stream_id, buf.data, False) <15>
===========unchanged ref 0=========== at: aioquic.connection.QuicConnection receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None at: aioquic.h3.connection.H3Connection _update() -> List[Event] _update(self) -> List[Event] at: aioquic.h3.connection.H3Connection.__init__ self._quic = quic at: aioquic.h3.connection.H3Connection._receive_stream_data self._peer_encoder_stream_id = stream_id at: aioquic.h3.events Event() at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.h3.connection + def encode_settings(settings: Dict[int, int]) -> bytes: + buf = Buffer(capacity=1024) + for setting, value in settings.items(): + buf.push_uint_var(setting) + buf.push_uint_var(value) + return buf.data + ===========changed ref 1=========== # module: aioquic.h3.connection + def encode_frame(frame_type: int, frame_data: bytes) -> bytes: + frame_length = len(frame_data) + buf = Buffer(capacity=frame_length + 16) + buf.push_uint_var(frame_type) + buf.push_uint_var(frame_length) + buf.push_bytes(frame_data) + return buf.data + ===========changed ref 2=========== # module: aioquic.h3.connection class H3Connection: def send_data(self, stream_id: int, data: bytes, end_stream: bool) -> None: """ Send data on the given stream. To retrieve datagram which need to be sent over the network call the QUIC connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send` method. """ - buf = Buffer(capacity=len(data) + 16) - buf.push_uint_var(FrameType.DATA) - buf.push_uint_var(len(data)) - buf.push_bytes(data) + self._send_stream_data( + stream_id, encode_frame(FrameType.DATA, data), end_stream + ) - self._send_stream_data(stream_id, buf.data, end_stream) - ===========changed ref 3=========== # module: aioquic.h3.connection class H3Connection: def __init__(self, quic: QuicConnection): + self._max_table_capacity = 0x100 + self._blocked_streams = 0x10 + self._handshake_completed = False self._is_client = quic.configuration.is_client self._quic = quic + self._decoder = Decoder(self._max_table_capacity, self._blocked_streams) - self._decoder = Decoder(0x100, 0x10) self._encoder = Encoder() self._pending: List[Tuple[int, bytes, bool]] = [] self._stream_buffers: Dict[int, bytes] = {} self._stream_types: Dict[int, int] = {} + self._local_control_stream_id: Optional[int] = None + self._local_decoder_stream_id: Optional[int] = None + self._local_encoder_stream_id: Optional[int] = None + self._peer_control_stream_id: Optional[int] = None self._peer_decoder_stream_id: Optional[int] = None self._peer_encoder_stream_id: Optional[int] = None
aioquic.h3.connection/H3Connection._receive_stream_data
Modified
aiortc~aioquic
8659358ef1848b547b3f4d4ae35757cb244b9a74
[http3] send SETTINGS frame on control stream
<11>:<add> if ( <add> stream_is_unidirectional(stream_id) <add> and stream_id not in self._stream_types <del> if (stream_id % 4) == 3 and stream_id not in self._stream_types: <12>:<add> ): <37>:<add> # client-initiated bidirectional streams carry requests and responses <del> # bidirectional streams carry requests and responses
# module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: <0> http_events: List[Event] = [] <1> <2> if stream_id in self._stream_buffers: <3> self._stream_buffers[stream_id] += data <4> else: <5> self._stream_buffers[stream_id] = data <6> consumed = 0 <7> <8> buf = Buffer(data=self._stream_buffers[stream_id]) <9> while not buf.eof(): <10> # fetch stream type for unidirectional streams <11> if (stream_id % 4) == 3 and stream_id not in self._stream_types: <12> try: <13> stream_type = buf.pull_uint_var() <14> except BufferReadError: <15> break <16> if stream_type == StreamType.CONTROL: <17> assert self._peer_control_stream_id is None <18> self._peer_control_stream_id = stream_id <19> elif stream_type == StreamType.QPACK_DECODER: <20> assert self._peer_decoder_stream_id is None <21> self._peer_decoder_stream_id = stream_id <22> elif stream_type == StreamType.QPACK_ENCODER: <23> assert self._peer_encoder_stream_id is None <24> self._peer_encoder_stream_id = stream_id <25> self._stream_types[stream_id] = stream_type <26> <27> # fetch next frame <28> try: <29> frame_type = buf.pull_uint_var() <30> frame_length = buf.pull_uint_var() <31> frame_data = buf.pull_bytes(frame_length) <32> except BufferReadError: <33> break <34> consumed = buf.tell() <35> <36> if (stream_id % 4) == 0: <37> # bidirectional streams carry requests and responses <38> if frame_type == FrameType.DATA: <39> http_events</s>
===========below chunk 0=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: # offset: 1 DataReceived( data=frame_data, stream_id=stream_id, stream_ended=stream_ended and buf.eof(), ) ) elif frame_type == FrameType.HEADERS: control, headers = self._decoder.feed_header(stream_id, frame_data) cls = ResponseReceived if self._is_client else RequestReceived http_events.append( cls( headers=headers, stream_id=stream_id, stream_ended=stream_ended and buf.eof(), ) ) else: logger.info( "Unhandled frame type %d on stream %d", frame_type, stream_id ) elif stream_id == self._peer_control_stream_id: # unidirectional control stream if frame_type == FrameType.SETTINGS: settings = parse_settings(frame_data) self._encoder.apply_settings( max_table_capacity=settings.get( Setting.QPACK_MAX_TABLE_CAPACITY, 0 ), blocked_streams=settings.get(Setting.QPACK_BLOCKED_STREAMS, 0), ) # remove processed data from buffer self._stream_buffers[stream_id] = self._stream_buffers[stream_id][consumed:] return http_events ===========unchanged ref 0=========== at: aioquic._buffer BufferReadError(*args: object) Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer eof() -> bool tell() -> int pull_bytes(length: int) -> bytes pull_uint_var() -> int at: aioquic.connection stream_is_unidirectional(stream_id: int) -> bool at: aioquic.h3.connection FrameType(x: Union[str, bytes, bytearray], base: int) FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, bytearray], base: int) encode_frame(frame_type: int, frame_data: bytes) -> bytes at: aioquic.h3.connection.H3Connection _send_stream_data(stream_id: int, data: bytes, end_stream: bool) -> None _send_stream_data(self, stream_id: int, data: bytes, end_stream: bool) -> None at: aioquic.h3.connection.H3Connection.__init__ self._is_client = quic.configuration.is_client self._decoder = Decoder(self._max_table_capacity, self._blocked_streams) self._encoder = Encoder() self._stream_buffers: Dict[int, bytes] = {} self._stream_types: Dict[int, int] = {} self._peer_control_stream_id: Optional[int] = None self._peer_decoder_stream_id: Optional[int] = None self._peer_encoder_stream_id: Optional[int] = None at: aioquic.h3.events Headers = List[Tuple[bytes, bytes]] Event() ===========unchanged ref 1=========== DataReceived(data: bytes, stream_id: int, stream_ended: bool) RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.h3.events.DataReceived data: bytes stream_id: int stream_ended: bool at: aioquic.h3.events.RequestReceived headers: Headers stream_id: int stream_ended: bool at: aioquic.h3.events.ResponseReceived headers: Headers stream_id: int stream_ended: bool at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.h3.connection + def encode_frame(frame_type: int, frame_data: bytes) -> bytes: + frame_length = len(frame_data) + buf = Buffer(capacity=frame_length + 16) + buf.push_uint_var(frame_type) + buf.push_uint_var(frame_length) + buf.push_bytes(frame_data) + return buf.data + ===========changed ref 1=========== # module: aioquic.h3.connection + def encode_settings(settings: Dict[int, int]) -> bytes: + buf = Buffer(capacity=1024) + for setting, value in settings.items(): + buf.push_uint_var(setting) + buf.push_uint_var(value) + return buf.data + ===========changed ref 2=========== # module: aioquic.h3.connection class H3Connection: def send_data(self, stream_id: int, data: bytes, end_stream: bool) -> None: """ Send data on the given stream. To retrieve datagram which need to be sent over the network call the QUIC connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send` method. """ - buf = Buffer(capacity=len(data) + 16) - buf.push_uint_var(FrameType.DATA) - buf.push_uint_var(len(data)) - buf.push_bytes(data) + self._send_stream_data( + stream_id, encode_frame(FrameType.DATA, data), end_stream + ) - self._send_stream_data(stream_id, buf.data, end_stream) - ===========changed ref 3=========== # module: aioquic.h3.connection class H3Connection: def send_headers(self, stream_id: int, headers: Headers) -> None: """ Send headers on the given stream. To retrieve datagram which need to be sent over the network call the QUIC connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send` method. """ control, header = self._encoder.encode(stream_id, 0, headers) + self._send_stream_data( + stream_id, encode_frame(FrameType.HEADERS, header), False + ) - buf = Buffer(capacity=len(header) + 16) - buf.push_uint_var(FrameType.HEADERS) - buf.push_uint_var(len(header)) - buf.push_bytes(header) - - self._send_stream_data(stream_id, buf.data, False) -
aioquic.h3.connection/H3Connection._update
Modified
aiortc~aioquic
8659358ef1848b547b3f4d4ae35757cb244b9a74
[http3] send SETTINGS frame on control stream
<7>:<add> <add> # send our settings <add> self._local_control_stream_id = self._quic.get_next_available_stream_id( <add> is_unidirectional=True <add> ) <add> buf = Buffer(capacity=1) <add> buf.push_uint_var(StreamType.CONTROL) <add> self._quic.send_stream_data(self._local_control_stream_id, buf.data) <add> <add> self._quic.send_stream_data( <add> self._local_control_stream_id, <add> encode_frame( <add> FrameType.SETTINGS, <add> encode_settings( <add> { <add> Setting.QPACK_MAX_TABLE_CAPACITY: self._max_table_capacity, <add> Setting.QPACK_BLOCKED_STREAMS: self._blocked_streams, <add> } <add> ), <add> ), <add> ) <add> <add> # send pending data
# module: aioquic.h3.connection class H3Connection: def _update(self) -> List[Event]: <0> http_events: List[Event] = [] <1> <2> # process QUIC events <3> event = self._quic.next_event() <4> while event is not None: <5> if isinstance(event, aioquic.events.HandshakeCompleted): <6> self._handshake_completed = True <7> for args in self._pending: <8> self._quic.send_stream_data(*args) <9> self._pending.clear() <10> elif isinstance(event, aioquic.events.StreamDataReceived): <11> http_events.extend( <12> self._receive_stream_data( <13> event.stream_id, event.data, event.end_stream <14> ) <15> ) <16> <17> event = self._quic.next_event() <18> <19> return http_events <20>
===========unchanged ref 0=========== at: aioquic.connection.QuicConnection next_event() -> Optional[events.Event] send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None at: aioquic.h3.connection Setting(x: Union[str, bytes, bytearray], base: int) Setting(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: aioquic.h3.connection.H3Connection.__init__ self._handshake_completed = False self._quic = quic self._pending: List[Tuple[int, bytes, bool]] = [] self._stream_buffers: Dict[int, bytes] = {} at: aioquic.h3.connection.H3Connection._receive_stream_data http_events: List[Event] = [] consumed = buf.tell() consumed = 0 settings = parse_settings(frame_data) at: aioquic.h3.connection.H3Connection._update self._handshake_completed = True at: aioquic.h3.events Event() at: typing List = _alias(list, 1, inst=False, name='List') at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co] ===========changed ref 0=========== # module: aioquic.h3.connection + def encode_settings(settings: Dict[int, int]) -> bytes: + buf = Buffer(capacity=1024) + for setting, value in settings.items(): + buf.push_uint_var(setting) + buf.push_uint_var(value) + return buf.data + ===========changed ref 1=========== # module: aioquic.h3.connection + def encode_frame(frame_type: int, frame_data: bytes) -> bytes: + frame_length = len(frame_data) + buf = Buffer(capacity=frame_length + 16) + buf.push_uint_var(frame_type) + buf.push_uint_var(frame_length) + buf.push_bytes(frame_data) + return buf.data + ===========changed ref 2=========== # module: aioquic.h3.connection class H3Connection: def send_data(self, stream_id: int, data: bytes, end_stream: bool) -> None: """ Send data on the given stream. To retrieve datagram which need to be sent over the network call the QUIC connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send` method. """ - buf = Buffer(capacity=len(data) + 16) - buf.push_uint_var(FrameType.DATA) - buf.push_uint_var(len(data)) - buf.push_bytes(data) + self._send_stream_data( + stream_id, encode_frame(FrameType.DATA, data), end_stream + ) - self._send_stream_data(stream_id, buf.data, end_stream) - ===========changed ref 3=========== # module: aioquic.h3.connection class H3Connection: def send_headers(self, stream_id: int, headers: Headers) -> None: """ Send headers on the given stream. To retrieve datagram which need to be sent over the network call the QUIC connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send` method. """ control, header = self._encoder.encode(stream_id, 0, headers) + self._send_stream_data( + stream_id, encode_frame(FrameType.HEADERS, header), False + ) - buf = Buffer(capacity=len(header) + 16) - buf.push_uint_var(FrameType.HEADERS) - buf.push_uint_var(len(header)) - buf.push_bytes(header) - - self._send_stream_data(stream_id, buf.data, False) - ===========changed ref 4=========== # module: aioquic.h3.connection class H3Connection: def __init__(self, quic: QuicConnection): + self._max_table_capacity = 0x100 + self._blocked_streams = 0x10 + self._handshake_completed = False self._is_client = quic.configuration.is_client self._quic = quic + self._decoder = Decoder(self._max_table_capacity, self._blocked_streams) - self._decoder = Decoder(0x100, 0x10) self._encoder = Encoder() self._pending: List[Tuple[int, bytes, bool]] = [] self._stream_buffers: Dict[int, bytes] = {} self._stream_types: Dict[int, int] = {} + self._local_control_stream_id: Optional[int] = None + self._local_decoder_stream_id: Optional[int] = None + self._local_encoder_stream_id: Optional[int] = None + self._peer_control_stream_id: Optional[int] = None self._peer_decoder_stream_id: Optional[int] = None self._peer_encoder_stream_id: Optional[int] = None ===========changed ref 5=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: http_events: List[Event] = [] if stream_id in self._stream_buffers: self._stream_buffers[stream_id] += data else: self._stream_buffers[stream_id] = data consumed = 0 buf = Buffer(data=self._stream_buffers[stream_id]) while not buf.eof(): # fetch stream type for unidirectional streams + if ( + stream_is_unidirectional(stream_id) + and stream_id not in self._stream_types - if (stream_id % 4) == 3 and stream_id not in self._stream_types: + ): try: stream_type = buf.pull_uint_var() except BufferReadError: break if stream_type == StreamType.CONTROL: assert self._peer_control_stream_id is None self._peer_control_stream_id = stream_id elif stream_type == StreamType.QPACK_DECODER: assert self._peer_decoder_stream_id is None self._peer_decoder_stream_id = stream_id elif stream_type == StreamType.QPACK_ENCODER: assert self._peer_encoder_stream_id is None self._peer_encoder_stream_id = stream_id self._stream_types[stream_id] = stream_type # fetch next frame try: frame_type = buf.pull_uint_var() frame_length = buf.pull_uint_var() frame_data = buf.pull_bytes(frame_length) except BufferReadError: break consumed = buf.tell() if (stream_id % 4) == 0: + # client-initiated bidirectional streams carry requests and responses - # bidirectional streams carry requests and responses </s>
aioquic.h3.connection/H3Connection._update
Modified
aiortc~aioquic
1580feff3b0e223d0c87a6dbad2b66b209114011
[http3] create local encoder and decoder streams
<9>:<add> self._local_control_stream_id = self._create_uni_stream( <del> self._local_control_stream_id = self._quic.get_next_available_stream_id( <10>:<add> StreamType.CONTROL <del> is_unidirectional=True <12>:<del> buf = Buffer(capacity=1) <13>:<del> buf.push_uint_var(StreamType.CONTROL) <14>:<del> self._quic.send_stream_data(self._local_control_stream_id, buf.data) <15>:<del> <27>:<add> ) <add> <add> # create encoder and decoder streams <add> self._local_encoder_stream_id = self._create_uni_stream( <add> StreamType.QPACK_ENCODER <add> ) <add> self._local_decoder_stream_id = self._create_uni_stream( <add> StreamType.QPACK_DECODER
# module: aioquic.h3.connection class H3Connection: def _update(self) -> List[Event]: <0> http_events: List[Event] = [] <1> <2> # process QUIC events <3> event = self._quic.next_event() <4> while event is not None: <5> if isinstance(event, aioquic.events.HandshakeCompleted): <6> self._handshake_completed = True <7> <8> # send our settings <9> self._local_control_stream_id = self._quic.get_next_available_stream_id( <10> is_unidirectional=True <11> ) <12> buf = Buffer(capacity=1) <13> buf.push_uint_var(StreamType.CONTROL) <14> self._quic.send_stream_data(self._local_control_stream_id, buf.data) <15> <16> self._quic.send_stream_data( <17> self._local_control_stream_id, <18> encode_frame( <19> FrameType.SETTINGS, <20> encode_settings( <21> { <22> Setting.QPACK_MAX_TABLE_CAPACITY: self._max_table_capacity, <23> Setting.QPACK_BLOCKED_STREAMS: self._blocked_streams, <24> } <25> ), <26> ), <27> ) <28> <29> # send pending data <30> for args in self._pending: <31> self._quic.send_stream_data(*args) <32> self._pending.clear() <33> elif isinstance(event, aioquic.events.StreamDataReceived): <34> http_events.extend( <35> self._receive_stream_data( <36> event.stream_id, event.data, event.end_stream <37> ) <38> ) <39> <40> event = self._quic.next_event() <41> <42> return http_events <43>
===========unchanged ref 0=========== at: aioquic.connection.QuicConnection next_event() -> Optional[events.Event] send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None at: aioquic.events HandshakeCompleted(alpn_protocol: Optional[str], early_data_accepted: bool, session_resumed: bool) at: aioquic.h3.connection FrameType(x: Union[str, bytes, bytearray], base: int) FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Setting(x: Union[str, bytes, bytearray], base: int) Setting(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, bytearray], base: int) encode_frame(frame_type: int, frame_data: bytes) -> bytes encode_settings(settings: Dict[int, int]) -> bytes at: aioquic.h3.connection.H3Connection _create_uni_stream(stream_type: int) -> int at: aioquic.h3.connection.H3Connection.__init__ self._max_table_capacity = 0x100 self._blocked_streams = 0x10 self._handshake_completed = False self._quic = quic self._pending: List[Tuple[int, bytes, bool]] = [] self._stream_buffers: Dict[int, bytes] = {} self._local_control_stream_id: Optional[int] = None self._local_decoder_stream_id: Optional[int] = None self._local_encoder_stream_id: Optional[int] = None at: aioquic.h3.connection.H3Connection._receive_stream_data http_events: List[Event] = [] ===========unchanged ref 1=========== consumed = buf.tell() consumed = 0 at: aioquic.h3.events Event() at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.h3.connection class H3Connection: + def _create_uni_stream(self, stream_type: int) -> int: + """ + Create an unidirectional stream of the given type. + """ + stream_id = self._quic.get_next_available_stream_id(is_unidirectional=True) + buf = Buffer(capacity=8) + buf.push_uint_var(stream_type) + self._quic.send_stream_data(stream_id, buf.data) + return stream_id +
aioquic.h3.connection/H3Connection._create_uni_stream
Modified
aiortc~aioquic
14fe109f5fe85afef4b802de9f835e6fff3a6450
[buffer] add encode_uint_var helper
<4>:<del> buf = Buffer(capacity=8) <5>:<del> buf.push_uint_var(stream_type) <6>:<add> self._quic.send_stream_data(stream_id, encode_uint_var(stream_type)) <del> self._quic.send_stream_data(stream_id, buf.data)
# module: aioquic.h3.connection class H3Connection: def _create_uni_stream(self, stream_type: int) -> int: <0> """ <1> Create an unidirectional stream of the given type. <2> """ <3> stream_id = self._quic.get_next_available_stream_id(is_unidirectional=True) <4> buf = Buffer(capacity=8) <5> buf.push_uint_var(stream_type) <6> self._quic.send_stream_data(stream_id, buf.data) <7> return stream_id <8>
===========unchanged ref 0=========== at: aioquic.buffer encode_uint_var(value: int) -> bytes at: aioquic.connection.QuicConnection get_next_available_stream_id(is_unidirectional=False) -> int send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None at: aioquic.h3.connection.H3Connection.__init__ self._quic = quic ===========changed ref 0=========== # module: aioquic.buffer + def encode_uint_var(value: int) -> bytes: + """ + Encode a variable-length unsigned integer. + """ + buf = Buffer(capacity=8) + buf.push_uint_var(value) + return buf.data +
aioquic.h3.connection/H3Connection._receive_stream_data
Modified
aiortc~aioquic
f0bd5ccb8f9ee0d55424b1b6c255557033983afa
[http3] remove stream type from buffer immediately
<19>:<add> consumed = buf.tell() <add>
# module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: <0> http_events: List[Event] = [] <1> <2> if stream_id in self._stream_buffers: <3> self._stream_buffers[stream_id] += data <4> else: <5> self._stream_buffers[stream_id] = data <6> consumed = 0 <7> <8> buf = Buffer(data=self._stream_buffers[stream_id]) <9> while not buf.eof(): <10> # fetch stream type for unidirectional streams <11> if ( <12> stream_is_unidirectional(stream_id) <13> and stream_id not in self._stream_types <14> ): <15> try: <16> stream_type = buf.pull_uint_var() <17> except BufferReadError: <18> break <19> if stream_type == StreamType.CONTROL: <20> assert self._peer_control_stream_id is None <21> self._peer_control_stream_id = stream_id <22> elif stream_type == StreamType.QPACK_DECODER: <23> assert self._peer_decoder_stream_id is None <24> self._peer_decoder_stream_id = stream_id <25> elif stream_type == StreamType.QPACK_ENCODER: <26> assert self._peer_encoder_stream_id is None <27> self._peer_encoder_stream_id = stream_id <28> self._stream_types[stream_id] = stream_type <29> <30> # fetch next frame <31> try: <32> frame_type = buf.pull_uint_var() <33> frame_length = buf.pull_uint_var() <34> frame_data = buf.pull_bytes(frame_length) <35> except BufferReadError: <36> break <37> consumed = buf.tell() <38> <39> if (stream_id % 4) == 0: <40> # client-initiated bidirectional streams carry requests and responses </s>
===========below chunk 0=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: # offset: 1 http_events.append( DataReceived( data=frame_data, stream_id=stream_id, stream_ended=stream_ended and buf.eof(), ) ) elif frame_type == FrameType.HEADERS: control, headers = self._decoder.feed_header(stream_id, frame_data) cls = ResponseReceived if self._is_client else RequestReceived http_events.append( cls( headers=headers, stream_id=stream_id, stream_ended=stream_ended and buf.eof(), ) ) elif stream_id == self._peer_control_stream_id: # unidirectional control stream if frame_type == FrameType.SETTINGS: settings = parse_settings(frame_data) self._encoder.apply_settings( max_table_capacity=settings.get( Setting.QPACK_MAX_TABLE_CAPACITY, 0 ), blocked_streams=settings.get(Setting.QPACK_BLOCKED_STREAMS, 0), ) # remove processed data from buffer self._stream_buffers[stream_id] = self._stream_buffers[stream_id][consumed:] return http_events ===========unchanged ref 0=========== at: aioquic._buffer BufferReadError(*args: object) Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer eof() -> bool tell() -> int pull_bytes(length: int) -> bytes pull_uint_var() -> int at: aioquic.connection stream_is_unidirectional(stream_id: int) -> bool at: aioquic.h3.connection FrameType(x: Union[str, bytes, bytearray], base: int) FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Setting(x: Union[str, bytes, bytearray], base: int) Setting(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, bytearray], base: int) parse_settings(data: bytes) -> Dict[int, int] at: aioquic.h3.connection.H3Connection.__init__ self._is_client = quic.configuration.is_client self._decoder = Decoder(self._max_table_capacity, self._blocked_streams) self._encoder = Encoder() self._stream_buffers: Dict[int, bytes] = {} self._stream_types: Dict[int, int] = {} self._peer_control_stream_id: Optional[int] = None self._peer_decoder_stream_id: Optional[int] = None self._peer_encoder_stream_id: Optional[int] = None at: aioquic.h3.events Event() DataReceived(data: bytes, stream_id: int, stream_ended: bool) RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) ===========unchanged ref 1=========== ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.h3.events.DataReceived data: bytes stream_id: int stream_ended: bool at: aioquic.h3.events.RequestReceived headers: Headers stream_id: int stream_ended: bool at: aioquic.h3.events.ResponseReceived headers: Headers stream_id: int stream_ended: bool at: typing List = _alias(list, 1, inst=False, name='List') at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co]
tests.test_h3/H3ConnectionTest.test_connect
Modified
aiortc~aioquic
45119d225558aab3246fbe63ea46dfcd90a96074
[http3] use :authority pseudo-header instead of Host header
<14>:<add> (b":authority", b"localhost"), <15>:<del> (b"host", b"localhost"), <32>:<add> (b":authority", b"localhost"), <33>:<del> (b"host", b"localhost"),
# module: tests.test_h3 class H3ConnectionTest(TestCase): def test_connect(self): <0> with client_and_server( <1> client_options={"alpn_protocols": ["h3-20"]}, <2> server_options={"alpn_protocols": ["h3-20"]}, <3> ) as (quic_client, quic_server): <4> h3_client = H3Connection(quic_client) <5> h3_server = H3Connection(quic_server) <6> <7> # send request <8> stream_id = quic_client.get_next_available_stream_id() <9> h3_client.send_headers( <10> stream_id=stream_id, <11> headers=[ <12> (b":method", b"GET"), <13> (b":scheme", b"https"), <14> (b":path", b"/"), <15> (b"host", b"localhost"), <16> ], <17> ) <18> h3_client.send_data(stream_id=stream_id, data=b"", end_stream=True) <19> self.assertEqual(h3_client._update(), []) <20> <21> # receive request <22> transfer(quic_client, quic_server) <23> events = h3_server._update() <24> self.assertEqual(len(events), 2) <25> <26> self.assertTrue(isinstance(events[0], RequestReceived)) <27> self.assertEqual( <28> events[0].headers, <29> [ <30> (b":method", b"GET"), <31> (b":scheme", b"https"), <32> (b":path", b"/"), <33> (b"host", b"localhost"), <34> ], <35> ) <36> self.assertEqual(events[0].stream_id, stream_id) <37> self.assertEqual(events[0].stream_ended, False) <38> <39> self.assertTrue(isinstance(events[1], DataReceived)) <40> self.assertEqual(events</s>
===========below chunk 0=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_connect(self): # offset: 1 self.assertEqual(events[1].stream_id, stream_id) self.assertEqual(events[1].stream_ended, True) # send response h3_server.send_headers( stream_id=stream_id, headers=[ (b":status", b"200"), (b"content-type", b"text/html; charset=utf-8"), ], ) h3_server.send_data( stream_id=stream_id, data=b"<html><body>hello</body></html>", end_stream=True, ) self.assertEqual(h3_server._update(), []) # receive response transfer(quic_server, quic_client) events = h3_client._update() self.assertEqual(len(events), 2) self.assertTrue(isinstance(events[0], ResponseReceived)) self.assertEqual( events[0].headers, [(b":status", b"200"), (b"content-type", b"text/html; charset=utf-8")], ) self.assertEqual(events[0].stream_id, stream_id) self.assertEqual(events[0].stream_ended, False) self.assertTrue(isinstance(events[1], DataReceived)) self.assertEqual(events[1].data, b"<html><body>hello</body></html>") self.assertEqual(events[1].stream_id, stream_id) self.assertEqual(events[1].stream_ended, True) ===========unchanged ref 0=========== 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 _update() -> List[Event] at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool) RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: tests.test_connection client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={}) transfer(sender, receiver) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None
examples.http3/run
Modified
aiortc~aioquic
45119d225558aab3246fbe63ea46dfcd90a96074
[http3] use :authority pseudo-header instead of Host header
<32>:<add> (b":scheme", parsed.scheme.encode("utf8")), <add> (b":authority", parsed.netloc.encode("utf8")), <del> (b":scheme", b"https"), <34>:<del> (b"host", server_name.encode("utf8")),
# module: examples.http3 def run(url: str) -> None: <0> # parse URL <1> parsed = urlparse(url) <2> assert parsed.scheme == "https", "Only HTTPS URLs are supported." <3> if ":" in parsed.netloc: <4> server_name, port_str = parsed.netloc.split(":") <5> port = int(port_str) <6> else: <7> server_name = parsed.netloc <8> port = 443 <9> <10> # prepare socket <11> server_addr = (socket.gethostbyname(server_name), port) <12> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <13> <14> # prepare QUIC connection <15> quic = QuicConnection( <16> configuration=QuicConfiguration( <17> alpn_protocols=["h3-20"], <18> is_client=True, <19> secrets_log_file=open("/tmp/ssl.log", "w"), <20> server_name=server_name, <21> ) <22> ) <23> quic.connect(server_addr, now=time.time()) <24> <25> # send request <26> conn = H3Connection(quic) <27> stream_id = quic.get_next_available_stream_id() <28> conn.send_headers( <29> stream_id=stream_id, <30> headers=[ <31> (b":method", b"GET"), <32> (b":scheme", b"https"), <33> (b":path", parsed.path.encode("utf8")), <34> (b"host", server_name.encode("utf8")), <35> ], <36> ) <37> conn.send_data(stream_id=stream_id, data=b"", end_stream=True) <38> for data, addr in quic.datagrams_to_send(now=time.time()): <39> sock.sendto(data, addr) <40> <41> # handle events <42> stream_ended = False <43> while not stream_ended: <44> data</s>
===========below chunk 0=========== # module: examples.http3 def run(url: str) -> None: # offset: 1 for event in conn.receive_datagram(data, addr, now=time.time()): print(event) if isinstance(event, (DataReceived, ResponseReceived)): stream_ended = event.stream_ended for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) ===========unchanged ref 0=========== at: aioquic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20, ] )) at: aioquic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20, ] ) at: aioquic.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.connection.QuicConnection connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_next_available_stream_id(is_unidirectional=False) -> int at: aioquic.h3.connection H3Connection(quic: QuicConnection) ===========unchanged ref 1=========== at: aioquic.h3.connection.H3Connection receive_datagram(data: bytes, addr: Any, now: float) -> List[Event] send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers) -> None at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: socket AF_INET: AddressFamily SOCK_DGRAM: SocketKind socket(family: int=..., type: int=..., proto: int=..., fileno: Optional[int]=...) gethostbyname(hostname: str) -> str at: socket.socket family: int type: int proto: int recvfrom(bufsize: int, flags: int=...) -> Tuple[bytes, _RetAddress] sendto(data: bytes, address: _Address) -> int sendto(data: bytes, flags: int, address: _Address) -> int at: time time() -> float 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: tests.test_h3 class H3ConnectionTest(TestCase): def test_connect(self): with client_and_server( client_options={"alpn_protocols": ["h3-20"]}, server_options={"alpn_protocols": ["h3-20"]}, ) as (quic_client, quic_server): h3_client = H3Connection(quic_client) h3_server = H3Connection(quic_server) # send request stream_id = quic_client.get_next_available_stream_id() h3_client.send_headers( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", b"https"), + (b":authority", b"localhost"), (b":path", b"/"), - (b"host", b"localhost"), ], ) h3_client.send_data(stream_id=stream_id, data=b"", end_stream=True) self.assertEqual(h3_client._update(), []) # receive request transfer(quic_client, quic_server) events = h3_server._update() self.assertEqual(len(events), 2) self.assertTrue(isinstance(events[0], RequestReceived)) self.assertEqual( events[0].headers, [ (b":method", b"GET"), (b":scheme", b"https"), + (b":authority", b"localhost"), (b":path", b"/"), - (b"host", b"localhost"), ], ) self.assertEqual(events[0].stream_id, stream_id) self.assertEqual(events[0].stream_ended, False) self.assertTrue(isinstance(events[1], DataReceived)) self.assertEqual(events[1].data, b"") self.assert</s> ===========changed ref 1=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_connect(self): # offset: 1 <s>instance(events[1], DataReceived)) self.assertEqual(events[1].data, b"") self.assertEqual(events[1].stream_id, stream_id) self.assertEqual(events[1].stream_ended, True) # send response h3_server.send_headers( stream_id=stream_id, headers=[ (b":status", b"200"), (b"content-type", b"text/html; charset=utf-8"), ], ) h3_server.send_data( stream_id=stream_id, data=b"<html><body>hello</body></html>", end_stream=True, ) self.assertEqual(h3_server._update(), []) # receive response transfer(quic_server, quic_client) events = h3_client._update() self.assertEqual(len(events), 2) self.assertTrue(isinstance(events[0], ResponseReceived)) self.assertEqual( events[0].headers, [(b":status", b"200"), (b"content-type", b"text/html; charset=utf-8")], ) self.assertEqual(events[0].stream_id, stream_id) self.assertEqual(events[0].stream_ended, False) self.assertTrue(isinstance(events[1], DataReceived)) self.assertEqual(events[1].data, b"<html><body>hello</body></html>") self.assertEqual(events[1].stream_id, stream_id) self.assertEqual(events[1].stream_ended, True)
aioquic.asyncio.compat/_AsyncGeneratorContextManager.__aexit__
Modified
aiortc~aioquic
7e32246f1b5d7512b3e87487a873417ae4b39537
[asyncio] drop some unused Python 3.6 compatibility code
<1>:<del> if value is None: <2>:<del> value = typ()
# module: aioquic.asyncio.compat class _AsyncGeneratorContextManager(ContextDecorator): def __aexit__(self, typ, value, traceback): <0> if typ is not None: <1> if value is None: <2> value = typ() <3> await self.gen.athrow(typ, value, traceback) <4>
===========unchanged ref 0=========== at: aioquic.asyncio.compat._AsyncGeneratorContextManager.__init__ self.gen = func(*args, **kwds)
tests.test_tls/ContextTest.test_handshake_with_x25519
Modified
aiortc~aioquic
c8c63e2a9b57451c7fcb1a9fc707300f3c710145
[travis] restore X25519 test
<4>:<add> try: <add> self._handshake(client, server) <del> self._handshake(client, server) <5>:<add> except UnsupportedAlgorithm as exc: <add> self.skipTest(str(exc))
# module: tests.test_tls class ContextTest(TestCase): - @skipIf(os.environ.get("TRAVIS") == "true", "travis lacks a modern OpenSSL") def test_handshake_with_x25519(self): <0> client = self.create_client() <1> client._supported_groups = [tls.Group.X25519] <2> server = self.create_server() <3> <4> self._handshake(client, server) <5>
===========unchanged ref 0=========== at: aioquic.tls Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: aioquic.tls.Context.__init__ self._supported_groups = [Group.SECP256R1] at: tests.test_tls.ContextTest create_client() create_server()
aioquic.tls/Context.handle_message
Modified
aiortc~aioquic
6039421f44fac3f2d5916b461b10fa6cac727867
[tls] remove an impossible code branch
# module: aioquic.tls class Context: def handle_message( self, input_data: bytes, output_buf: Dict[Epoch, Buffer] ) -> None: <0> if self.state == State.CLIENT_HANDSHAKE_START: <1> self._client_send_hello(output_buf[Epoch.INITIAL]) <2> return <3> <4> self._receive_buffer += input_data <5> while len(self._receive_buffer) >= 4: <6> # determine message length <7> message_type = self._receive_buffer[0] <8> message_length = 0 <9> for b in self._receive_buffer[1:4]: <10> message_length = (message_length << 8) | b <11> message_length += 4 <12> <13> # check message is complete <14> if len(self._receive_buffer) < message_length: <15> break <16> message = self._receive_buffer[:message_length] <17> self._receive_buffer = self._receive_buffer[message_length:] <18> <19> input_buf = Buffer(data=message) <20> <21> # client states <22> <23> if self.state == State.CLIENT_EXPECT_SERVER_HELLO: <24> if message_type == HandshakeType.SERVER_HELLO: <25> self._client_handle_hello(input_buf, output_buf[Epoch.INITIAL]) <26> else: <27> raise AlertUnexpectedMessage <28> elif self.state == State.CLIENT_EXPECT_ENCRYPTED_EXTENSIONS: <29> if message_type == HandshakeType.ENCRYPTED_EXTENSIONS: <30> self._client_handle_encrypted_extensions(input_buf) <31> else: <32> raise AlertUnexpectedMessage <33> elif self.state == State.CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE: <34> if message_type == HandshakeType.CERTIFICATE: <35> self._client_handle_certificate(input_buf) <36> else: <37> # FIXME: handle certificate request <38> raise AlertUnexpectedMessage <39> elif self.state == State.CLIENT_EXPECT_CERTIFICATE</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def handle_message( self, input_data: bytes, output_buf: Dict[Epoch, Buffer] ) -> None: # offset: 1 if message_type == HandshakeType.CERTIFICATE_VERIFY: self._client_handle_certificate_verify(input_buf) else: raise AlertUnexpectedMessage elif self.state == State.CLIENT_EXPECT_FINISHED: if message_type == HandshakeType.FINISHED: self._client_handle_finished(input_buf, output_buf[Epoch.HANDSHAKE]) else: raise AlertUnexpectedMessage elif self.state == State.CLIENT_POST_HANDSHAKE: if message_type == HandshakeType.NEW_SESSION_TICKET: self._client_handle_new_session_ticket(input_buf) else: raise AlertUnexpectedMessage # server states elif self.state == State.SERVER_EXPECT_CLIENT_HELLO: if message_type == HandshakeType.CLIENT_HELLO: self._server_handle_hello( input_buf, output_buf[Epoch.INITIAL], output_buf[Epoch.HANDSHAKE], output_buf[Epoch.ONE_RTT], ) else: raise AlertUnexpectedMessage elif self.state == State.SERVER_EXPECT_FINISHED: if message_type == HandshakeType.FINISHED: self._server_handle_finished(input_buf, output_buf[Epoch.ONE_RTT]) else: raise AlertUnexpectedMessage elif self.state == State.SERVER_POST_HANDSHAKE: raise AlertUnexpectedMessage # should not happen else: raise Exception("unhandled state") assert input_buf.eof() ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer eof() -> bool at: aioquic.tls AlertUnexpectedMessage(*args: object) Epoch() State() HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, bytearray], base: int) NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b"", ticket: bytes=b"", max_early_data_size: Optional[int]=None) SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) at: aioquic.tls.Context _client_send_hello(output_buf: Buffer) -> None _client_handle_hello(input_buf: Buffer, output_buf: Buffer) -> None _client_handle_encrypted_extensions(input_buf: Buffer) -> None _client_handle_certificate(input_buf: Buffer) -> None _client_handle_certificate_verify(input_buf: Buffer) -> None _client_handle_finished(input_buf: Buffer, output_buf: Buffer) -> None _client_handle_new_session_ticket(input_buf: Buffer) -> None _server_handle_hello(input_buf: Buffer, initial_buf: Buffer, handshake_buf: Buffer, onertt_buf: Buffer) -> None _server_handle_finished(input_buf: Buffer, output_buf: Buffer) -> None ===========unchanged ref 1=========== at: aioquic.tls.Context.__init__ self.key_schedule: Optional[KeySchedule] = None self._receive_buffer = b"" self.state = State.CLIENT_HANDSHAKE_START self.state = State.SERVER_EXPECT_CLIENT_HELLO at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) at: aioquic.tls.Context._server_handle_hello self.key_schedule = KeySchedule(cipher_suite) at: aioquic.tls.Context._set_state self.state = state at: aioquic.tls.KeySchedule derive_secret(label: bytes) -> bytes at: typing Dict = _alias(dict, 2, inst=False, name='Dict')
aioquic.tls/pull_server_hello
Modified
aiortc~aioquic
19b152cf33473ab435c21fc09d4980e7b490bb41
[tls] test NewSessionTicket and ServerHello with unknown extension
<23>:<add> hello.other_extensions.append( <add> (extension_type, buf.pull_bytes(extension_length)) <del> buf.pull_bytes(extension_length) <24>:<add> )
# module: aioquic.tls def pull_server_hello(buf: Buffer) -> ServerHello: <0> assert buf.pull_uint8() == HandshakeType.SERVER_HELLO <1> with pull_block(buf, 3): <2> assert buf.pull_uint16() == TLS_VERSION_1_2 <3> server_random = buf.pull_bytes(32) <4> <5> hello = ServerHello( <6> random=server_random, <7> session_id=pull_opaque(buf, 1), <8> cipher_suite=pull_cipher_suite(buf), <9> compression_method=pull_compression_method(buf), <10> ) <11> <12> # extensions <13> def pull_extension() -> None: <14> extension_type = buf.pull_uint16() <15> extension_length = buf.pull_uint16() <16> if extension_type == ExtensionType.SUPPORTED_VERSIONS: <17> hello.supported_version = buf.pull_uint16() <18> elif extension_type == ExtensionType.KEY_SHARE: <19> hello.key_share = pull_key_share(buf) <20> elif extension_type == ExtensionType.PRE_SHARED_KEY: <21> hello.pre_shared_key = buf.pull_uint16() <22> else: <23> buf.pull_bytes(extension_length) <24> <25> pull_list(buf, 2, pull_extension) <26> <27> return hello <28>
===========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_uint8() -> int pull_uint16() -> int at: aioquic.tls TLS_VERSION_1_2 = 0x0303 ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, bytearray], base: int) pull_cipher_suite(buf: Buffer) -> CipherSuite pull_compression_method(buf: Buffer) -> CompressionMethod pull_block(buf: Buffer, capacity: int) -> Generator pull_opaque(buf: Buffer, capacity: int) -> bytes pull_key_share(buf: Buffer) -> KeyShareEntry ServerHello(random: bytes, session_id: bytes, cipher_suite: CipherSuite, compression_method: CompressionMethod, key_share: Optional[KeyShareEntry]=None, pre_shared_key: Optional[int]=None, supported_version: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) at: aioquic.tls.ServerHello random: bytes session_id: bytes cipher_suite: CipherSuite compression_method: CompressionMethod key_share: Optional[KeyShareEntry] = None pre_shared_key: Optional[int] = None supported_version: Optional[int] = None other_extensions: List[Tuple[int, bytes]] = field(default_factory=list) ===========changed ref 0=========== # module: aioquic.tls @dataclass class ServerHello: random: bytes session_id: bytes cipher_suite: CipherSuite compression_method: CompressionMethod # extensions key_share: Optional[KeyShareEntry] = None pre_shared_key: Optional[int] = None supported_version: Optional[int] = None + other_extensions: List[Tuple[int, bytes]] = field(default_factory=list)
aioquic.tls/pull_new_session_ticket
Modified
aiortc~aioquic
19b152cf33473ab435c21fc09d4980e7b490bb41
[tls] test NewSessionTicket and ServerHello with unknown extension
<15>:<add> new_session_ticket.other_extensions.append( <add> (extension_type, buf.pull_bytes(extension_length)) <del> buf.pull_bytes(extension_length) <16>:<add> )
# module: aioquic.tls def pull_new_session_ticket(buf: Buffer) -> NewSessionTicket: <0> new_session_ticket = NewSessionTicket() <1> <2> assert buf.pull_uint8() == HandshakeType.NEW_SESSION_TICKET <3> with pull_block(buf, 3): <4> new_session_ticket.ticket_lifetime = buf.pull_uint32() <5> new_session_ticket.ticket_age_add = buf.pull_uint32() <6> new_session_ticket.ticket_nonce = pull_opaque(buf, 1) <7> new_session_ticket.ticket = pull_opaque(buf, 2) <8> <9> def pull_extension() -> None: <10> extension_type = buf.pull_uint16() <11> extension_length = buf.pull_uint16() <12> if extension_type == ExtensionType.EARLY_DATA: <13> new_session_ticket.max_early_data_size = buf.pull_uint32() <14> else: <15> buf.pull_bytes(extension_length) <16> <17> pull_list(buf, 2, pull_extension) <18> <19> return new_session_ticket <20>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer pull_uint8() -> int pull_uint16() -> int pull_uint32() -> int at: aioquic.tls HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, bytearray], base: int) pull_block(buf: Buffer, capacity: int) -> Generator pull_opaque(buf: Buffer, capacity: int) -> bytes NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b"", ticket: bytes=b"", max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) at: aioquic.tls.NewSessionTicket ticket_lifetime: int = 0 ticket_age_add: int = 0 at: dataclasses field(*, default_factory: Callable[[], _T], init: bool=..., repr: bool=..., hash: Optional[bool]=..., compare: bool=..., metadata: Optional[Mapping[str, Any]]=...) -> _T field(*, init: bool=..., repr: bool=..., hash: Optional[bool]=..., compare: bool=..., metadata: Optional[Mapping[str, Any]]=...) -> Any field(*, default: _T, init: bool=..., repr: bool=..., hash: Optional[bool]=..., compare: bool=..., metadata: Optional[Mapping[str, Any]]=...) -> _T at: typing Tuple = _TupleType(tuple, -1, inst=False, name='Tuple') List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.tls @dataclass class NewSessionTicket: ticket_lifetime: int = 0 ticket_age_add: int = 0 ticket_nonce: bytes = b"" ticket: bytes = b"" # extensions max_early_data_size: Optional[int] = None + other_extensions: List[Tuple[int, bytes]] = field(default_factory=list) ===========changed ref 1=========== # module: aioquic.tls @dataclass class ServerHello: random: bytes session_id: bytes cipher_suite: CipherSuite compression_method: CompressionMethod # extensions key_share: Optional[KeyShareEntry] = None pre_shared_key: Optional[int] = None supported_version: Optional[int] = None + other_extensions: List[Tuple[int, bytes]] = field(default_factory=list) ===========changed ref 2=========== # module: aioquic.tls def pull_server_hello(buf: Buffer) -> ServerHello: assert buf.pull_uint8() == HandshakeType.SERVER_HELLO with pull_block(buf, 3): assert buf.pull_uint16() == TLS_VERSION_1_2 server_random = buf.pull_bytes(32) hello = ServerHello( random=server_random, session_id=pull_opaque(buf, 1), cipher_suite=pull_cipher_suite(buf), compression_method=pull_compression_method(buf), ) # extensions def pull_extension() -> None: extension_type = buf.pull_uint16() extension_length = buf.pull_uint16() if extension_type == ExtensionType.SUPPORTED_VERSIONS: hello.supported_version = buf.pull_uint16() elif extension_type == ExtensionType.KEY_SHARE: hello.key_share = pull_key_share(buf) elif extension_type == ExtensionType.PRE_SHARED_KEY: hello.pre_shared_key = buf.pull_uint16() else: + hello.other_extensions.append( + (extension_type, buf.pull_bytes(extension_length)) - buf.pull_bytes(extension_length) + ) pull_list(buf, 2, pull_extension) return hello
tests.test_tls/ContextTest.test_server_unsupported_signature_algorithm
Modified
aiortc~aioquic
12350d38b9cdd4dcb161b70f9da74ca64b88563e
[tls] fix server-side support for EC certificate signatures
<1>:<add> client._signature_algorithms = [tls.SignatureAlgorithm.ED448] <del> client._signature_algorithms = [tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA256] <4>:<del> server._signature_algorithms = [tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA512]
# module: tests.test_tls class ContextTest(TestCase): def test_server_unsupported_signature_algorithm(self): <0> client = self.create_client() <1> client._signature_algorithms = [tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA256] <2> <3> server = self.create_server() <4> server._signature_algorithms = [tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA512] <5> <6> with self.assertRaises(tls.AlertHandshakeFailure) as cm: <7> self._server_fail_hello(client, server) <8> self.assertEqual(str(cm.exception), "No supported signature algorithm") <9>
===========unchanged ref 0=========== at: aioquic.tls State() at: aioquic.tls.Context handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None at: aioquic.tls.Context.__init__ self.state = State.CLIENT_HANDSHAKE_START self.state = State.SERVER_EXPECT_CLIENT_HELLO at: aioquic.tls.Context._set_state self.state = state at: tests.test_tls create_buffers() merge_buffers(buffers) reset_buffers(buffers) at: tests.test_tls.ContextTest.test_server_unexpected_message server = self.create_server() at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_tls + def generate_ec_certificate(curve): + key = ec.generate_private_key(backend=default_backend(), curve=curve) + + subject = issuer = x509.Name( + [x509.NameAttribute(x509.NameOID.COMMON_NAME, "example.com")] + ) + + cert = ( + x509.CertificateBuilder() + .subject_name(subject) + .issuer_name(issuer) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(datetime.datetime.utcnow()) + .not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=10)) + .sign(key, hashes.SHA256(), default_backend()) + ) + return cert, key + ===========changed ref 1=========== # module: aioquic.tls class Context: def _server_handle_hello( self, input_buf: Buffer, initial_buf: Buffer, handshake_buf: Buffer, onertt_buf: Buffer, ) -> None: peer_hello = pull_client_hello(input_buf) + + # determine applicable signature algorithms + signature_algorithms: List[SignatureAlgorithm] = [] + if isinstance(self.certificate_private_key, rsa.RSAPrivateKey): + signature_algorithms = [ + SignatureAlgorithm.RSA_PSS_RSAE_SHA256, + SignatureAlgorithm.RSA_PKCS1_SHA256, + SignatureAlgorithm.RSA_PKCS1_SHA1, + ] + elif isinstance( + self.certificate_private_key, ec.EllipticCurvePrivateKey + ) and isinstance(self.certificate_private_key.curve, ec.SECP256R1): + signature_algorithms = [SignatureAlgorithm.ECDSA_SECP256R1_SHA256] # negotiate parameters cipher_suite = negotiate( self._cipher_suites, peer_hello.cipher_suites, AlertHandshakeFailure("No supported cipher suite"), ) compression_method = negotiate( self._compression_methods, peer_hello.compression_methods, AlertHandshakeFailure("No supported compression method"), ) negotiate( self._key_exchange_modes, peer_hello.key_exchange_modes, AlertHandshakeFailure("No supported key exchange mode"), ) signature_algorithm = negotiate( + signature_algorithms, - self._signature_algorithms, peer_hello.signature_algorithms, AlertHandshakeFailure("No supported signature algorithm"), ) supported_version = negotiate( self._supported_versions, peer_hello.supported_versions, AlertProtocolVersion("No supported protocol version"), ) # negotiate ALPN if self.alpn_protocols is not None: self</s> ===========changed ref 2=========== # module: aioquic.tls class Context: def _server_handle_hello( self, input_buf: Buffer, initial_buf: Buffer, handshake_buf: Buffer, onertt_buf: Buffer, ) -> None: # offset: 1 <s> version"), ) # negotiate ALPN if self.alpn_protocols is not None: self.alpn_negotiated = negotiate( self.alpn_protocols, peer_hello.alpn_protocols, AlertHandshakeFailure("No common ALPN protocols"), ) self.client_random = peer_hello.random self.server_random = os.urandom(32) self.session_id = peer_hello.session_id self.received_extensions = peer_hello.other_extensions # select key schedule pre_shared_key = None if ( self.get_session_ticket_cb is not None and peer_hello.pre_shared_key is not None and len(peer_hello.pre_shared_key.identities) == 1 and len(peer_hello.pre_shared_key.binders) == 1 ): # ask application to find session ticket identity = peer_hello.pre_shared_key.identities[0] session_ticket = self.get_session_ticket_cb(identity[0]) # validate session ticket if ( session_ticket is not None and session_ticket.is_valid and session_ticket.cipher_suite == cipher_suite ): self.key_schedule = KeySchedule(cipher_suite) self.key_schedule.extract(session_ticket.resumption_secret) binder_key = self.key_schedule.derive_secret(b"res binder") binder_length = self.key_schedule.algorithm.digest_size hash_offset =</s> ===========changed ref 3=========== # module: aioquic.tls class Context: def _server_handle_hello( self, input_buf: Buffer, initial_buf: Buffer, handshake_buf: Buffer, onertt_buf: Buffer, ) -> None: # offset: 2 <s>buf.tell() - binder_length - 3 binder = input_buf.data_slice( hash_offset + 3, hash_offset + 3 + binder_length ) self.key_schedule.update_hash(input_buf.data_slice(0, hash_offset)) expected_binder = self.key_schedule.finished_verify_data(binder_key) if binder != expected_binder: raise AlertHandshakeFailure("PSK validation failed") self.key_schedule.update_hash( input_buf.data_slice(hash_offset, hash_offset + 3 + binder_length) ) self._session_resumed = True # calculate early data key if peer_hello.early_data: early_key = self.key_schedule.derive_secret(b"c e traffic") self.early_data_accepted = True self.update_traffic_key_cb( Direction.DECRYPT, Epoch.ZERO_RTT, self.key_schedule.cipher_suite, early_key, ) pre_shared_key = 0 # if PSK is not used, initialize key schedule if pre_shared_key is None: self.key_schedule = KeySchedule(cipher_suite) self.key_schedule.extract(None) self.key_schedule.update_hash(input_buf.data) # perform key exchange public_key: Union[ec.EllipticCurvePublicKey, x25519.X25519PublicKey] shared_key: Optional[bytes] = None for key_share in peer_hello.</s>
tests.test_tls/ContextTest._handshake
Modified
aiortc~aioquic
12350d38b9cdd4dcb161b70f9da74ca64b88563e
[tls] fix server-side support for EC certificate signatures
<15>:<add> self.assertGreaterEqual(len(client_input), 600) <del> self.assertGreaterEqual(len(client_input), 2194)
# module: tests.test_tls class ContextTest(TestCase): def _handshake(self, client, server): <0> # send client hello <1> client_buf = create_buffers() <2> client.handle_message(b"", client_buf) <3> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) <4> server_input = merge_buffers(client_buf) <5> self.assertGreaterEqual(len(server_input), 219) <6> self.assertLessEqual(len(server_input), 264) <7> reset_buffers(client_buf) <8> <9> # handle client hello <10> # send server hello, encrypted extensions, certificate, certificate verify, finished, (session ticket) <11> server_buf = create_buffers() <12> server.handle_message(server_input, server_buf) <13> self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) <14> client_input = merge_buffers(server_buf) <15> self.assertGreaterEqual(len(client_input), 2194) <16> self.assertLessEqual(len(client_input), 2316) <17> <18> reset_buffers(server_buf) <19> <20> # handle server hello, encrypted extensions, certificate, certificate verify, finished, (session ticket) <21> # send finished <22> client.handle_message(client_input, client_buf) <23> self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) <24> server_input = merge_buffers(client_buf) <25> self.assertEqual(len(server_input), 52) <26> reset_buffers(client_buf) <27> <28> # handle finished <29> server.handle_message(server_input, server_buf) <30> self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) <31> client_input = merge_buffers(server_buf) <32> self.assertEqual(len(client_input), 0) <33> <34> # check keys match <35> self.assertEqual(client._dec_key, server._enc</s>
===========below chunk 0=========== # module: tests.test_tls class ContextTest(TestCase): def _handshake(self, client, server): # offset: 1 self.assertEqual(client._enc_key, server._dec_key) # check cipher suite self.assertEqual( client.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384 ) self.assertEqual( server.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384 ) ===========unchanged ref 0=========== at: aioquic.tls AlertDecryptError(*args: object) State() at: aioquic.tls.Context handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None at: aioquic.tls.Context.__init__ self.state = State.CLIENT_HANDSHAKE_START self.state = State.SERVER_EXPECT_CLIENT_HELLO at: aioquic.tls.Context._set_state self.state = state at: tests.test_tls create_buffers() merge_buffers(buffers) reset_buffers(buffers) at: tests.test_tls.ContextTest.test_server_bad_finished_verify_data client = self.create_client() server = self.create_server() client_buf = create_buffers() at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertGreaterEqual(a: Any, b: Any, msg: Any=...) -> None assertLessEqual(a: Any, b: Any, msg: Any=...) -> None assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None ===========changed ref 0=========== # module: tests.test_tls class ContextTest(TestCase): def test_server_unsupported_signature_algorithm(self): client = self.create_client() + client._signature_algorithms = [tls.SignatureAlgorithm.ED448] - client._signature_algorithms = [tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA256] server = self.create_server() - server._signature_algorithms = [tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA512] with self.assertRaises(tls.AlertHandshakeFailure) as cm: self._server_fail_hello(client, server) self.assertEqual(str(cm.exception), "No supported signature algorithm") ===========changed ref 1=========== # module: tests.test_tls + def generate_ec_certificate(curve): + key = ec.generate_private_key(backend=default_backend(), curve=curve) + + subject = issuer = x509.Name( + [x509.NameAttribute(x509.NameOID.COMMON_NAME, "example.com")] + ) + + cert = ( + x509.CertificateBuilder() + .subject_name(subject) + .issuer_name(issuer) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(datetime.datetime.utcnow()) + .not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=10)) + .sign(key, hashes.SHA256(), default_backend()) + ) + return cert, key + ===========changed ref 2=========== # module: aioquic.tls class Context: def _server_handle_hello( self, input_buf: Buffer, initial_buf: Buffer, handshake_buf: Buffer, onertt_buf: Buffer, ) -> None: peer_hello = pull_client_hello(input_buf) + + # determine applicable signature algorithms + signature_algorithms: List[SignatureAlgorithm] = [] + if isinstance(self.certificate_private_key, rsa.RSAPrivateKey): + signature_algorithms = [ + SignatureAlgorithm.RSA_PSS_RSAE_SHA256, + SignatureAlgorithm.RSA_PKCS1_SHA256, + SignatureAlgorithm.RSA_PKCS1_SHA1, + ] + elif isinstance( + self.certificate_private_key, ec.EllipticCurvePrivateKey + ) and isinstance(self.certificate_private_key.curve, ec.SECP256R1): + signature_algorithms = [SignatureAlgorithm.ECDSA_SECP256R1_SHA256] # negotiate parameters cipher_suite = negotiate( self._cipher_suites, peer_hello.cipher_suites, AlertHandshakeFailure("No supported cipher suite"), ) compression_method = negotiate( self._compression_methods, peer_hello.compression_methods, AlertHandshakeFailure("No supported compression method"), ) negotiate( self._key_exchange_modes, peer_hello.key_exchange_modes, AlertHandshakeFailure("No supported key exchange mode"), ) signature_algorithm = negotiate( + signature_algorithms, - self._signature_algorithms, peer_hello.signature_algorithms, AlertHandshakeFailure("No supported signature algorithm"), ) supported_version = negotiate( self._supported_versions, peer_hello.supported_versions, AlertProtocolVersion("No supported protocol version"), ) # negotiate ALPN if self.alpn_protocols is not None: self</s> ===========changed ref 3=========== # module: aioquic.tls class Context: def _server_handle_hello( self, input_buf: Buffer, initial_buf: Buffer, handshake_buf: Buffer, onertt_buf: Buffer, ) -> None: # offset: 1 <s> version"), ) # negotiate ALPN if self.alpn_protocols is not None: self.alpn_negotiated = negotiate( self.alpn_protocols, peer_hello.alpn_protocols, AlertHandshakeFailure("No common ALPN protocols"), ) self.client_random = peer_hello.random self.server_random = os.urandom(32) self.session_id = peer_hello.session_id self.received_extensions = peer_hello.other_extensions # select key schedule pre_shared_key = None if ( self.get_session_ticket_cb is not None and peer_hello.pre_shared_key is not None and len(peer_hello.pre_shared_key.identities) == 1 and len(peer_hello.pre_shared_key.binders) == 1 ): # ask application to find session ticket identity = peer_hello.pre_shared_key.identities[0] session_ticket = self.get_session_ticket_cb(identity[0]) # validate session ticket if ( session_ticket is not None and session_ticket.is_valid and session_ticket.cipher_suite == cipher_suite ): self.key_schedule = KeySchedule(cipher_suite) self.key_schedule.extract(session_ticket.resumption_secret) binder_key = self.key_schedule.derive_secret(b"res binder") binder_length = self.key_schedule.algorithm.digest_size hash_offset =</s>
aioquic.connection/QuicConnection.send_stream_data
Modified
aiortc~aioquic
44eb23c0f36f402b68bd4d7d9fe549146d697db9
[connection] check send_stream_data is called on valid streams
<6>:<add> if stream_is_client_initiated(stream_id) != self._is_client: <add> if stream_id not in self._streams: <add> raise ValueError("Cannot send data on unknown peer-initiated stream") <add> if stream_is_unidirectional(stream_id): <add> raise ValueError( <add> "Cannot send data on peer-initiated unidirectional stream" <add> ) <add>
# module: aioquic.connection class QuicConnection: def send_stream_data( self, stream_id: int, data: bytes, end_stream: bool = False ) -> None: <0> """ <1> Send data on the specific stream. <2> <3> :param data: The data to be sent. <4> :param end_stream: If set to `True`, the FIN bit will be set. <5> """ <6> try: <7> stream = self._streams[stream_id] <8> except KeyError: <9> self._create_stream(stream_id=stream_id) <10> stream = self._streams[stream_id] <11> stream.write(data, end_stream=end_stream) <12>
===========unchanged ref 0=========== at: aioquic.connection stream_is_client_initiated(stream_id: int) -> bool stream_is_unidirectional(stream_id: int) -> bool at: aioquic.connection.QuicConnection.__init__ self._is_client = configuration.is_client self._streams: Dict[int, QuicStream] = {}
aioquic.stream/QuicStream.__init__
Modified
aiortc~aioquic
1f48726433a6b5d4abc34758228516aaa2432269
[streams] send STREAMS_BLOCKED if stream limit is exceeded
<1>:<add> self.is_blocked = False
# module: aioquic.stream class QuicStream: def __init__( self, stream_id: Optional[int] = None, connection: Optional[Any] = None, max_stream_data_local: int = 0, max_stream_data_remote: int = 0, ) -> None: <0> self._connection = connection <1> self.max_stream_data_local = max_stream_data_local <2> self.max_stream_data_local_sent = max_stream_data_local <3> self.max_stream_data_remote = max_stream_data_remote <4> self.send_buffer_is_empty = True <5> <6> self._recv_buffer = bytearray() <7> self._recv_buffer_fin: Optional[int] = None <8> self._recv_buffer_start = 0 # the offset for the start of the buffer <9> self._recv_highest = 0 # the highest offset ever seen <10> self._recv_ranges = RangeSet() <11> <12> self._send_acked = RangeSet() <13> self._send_buffer = bytearray() <14> self._send_buffer_fin: Optional[int] = None <15> self._send_buffer_start = 0 # the offset for the start of the buffer <16> self._send_buffer_stop = 0 # the offset for the stop of the buffer <17> self._send_highest = 0 <18> self._send_pending = RangeSet() <19> self._send_pending_eof = False <20> <21> self.__stream_id = stream_id <22>
===========unchanged ref 0=========== at: aioquic.rangeset RangeSet(ranges: Iterable[range]=[]) at: aioquic.stream.QuicStream.add_frame self._recv_highest = frame_end self._recv_buffer += bytearray(gap) self._recv_buffer_fin = frame_end at: aioquic.stream.QuicStream.get_frame self._send_pending_eof = False self.send_buffer_is_empty = True self._send_highest = stop at: aioquic.stream.QuicStream.on_data_delivery self.send_buffer_is_empty = False self._send_buffer_start += size self._send_pending_eof = True at: aioquic.stream.QuicStream.pull_data self._recv_buffer_start = r.stop at: aioquic.stream.QuicStream.write self.send_buffer_is_empty = False self._send_buffer += data self._send_buffer_stop += size self._send_buffer_fin = self._send_buffer_stop self._send_pending_eof = True
aioquic.connection/QuicConnection.__init__
Modified
aiortc~aioquic
1f48726433a6b5d4abc34758228516aaa2432269
[streams] send STREAMS_BLOCKED if stream limit is exceeded
# module: aioquic.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._stateless_retry_count = 0 <14> self._version_negotiation_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.Event] = 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.host_cid = self._</s>
===========below chunk 0=========== # module: aioquic.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_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(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_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</s> ===========below chunk 1=========== # module: aioquic.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>i_local = 0 self._remote_max_stream_data_bidi_remote = 0 self._remote_max_stream_data_uni = 0 self._remote_max_streams_bidi = 0 self._remote_max_streams_uni = 0 self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._spin_bit = False self._spin_bit_peer = False self._spin_highest_pn = 0 self._state = QuicConnectionState.FIRSTFLIGHT self._streams: Dict[int, QuicStream] = {} self._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] = [] # callbacks self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler # frame handlers self.__frame_handlers = [ (self._handle_padding_frame, EPOCHS("IZHO")), (self._handle_padding_frame, EPOCHS("ZO")), (self._handle_ack_frame, EPOCHS("IHO")), (self._handle_ack_frame, EPOCHS("IHO")), (self._handle_reset_stream_frame, EPOCHS("ZO")), (self._handle_stop_s</s> ===========below chunk 2=========== # module: aioquic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 3 <s>frame, 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, 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("</s> ===========below chunk 3=========== # module: aioquic.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>")), (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.connection/QuicConnection._create_stream
Modified
aiortc~aioquic
1f48726433a6b5d4abc34758228516aaa2432269
[streams] send STREAMS_BLOCKED if stream limit is exceeded
<8>:<add> streams_blocked = self._streams_blocked_uni <12>:<del> <13>:<del> # check max streams <14>:<del> if stream_id // 4 >= max_streams: <15>:<del> raise ValueError("Too many streams open") <16>:<add> streams_blocked = self._streams_blocked_bidi <24>:<add> <add> # mark stream as blocked if needed <add> if stream_id // 4 >= max_streams: <add> stream.is_blocked = True <add> streams_blocked.append(stream) <add> self._streams_blocked_pending = True <add>
# module: aioquic.connection class QuicConnection: def _create_stream(self, stream_id: int) -> QuicStream: <0> """ <1> Create a QUIC stream in order to send data to the peer. <2> """ <3> # determine limits <4> if stream_is_unidirectional(stream_id): <5> max_stream_data_local = 0 <6> max_stream_data_remote = self._remote_max_stream_data_uni <7> max_streams = self._remote_max_streams_uni <8> else: <9> max_stream_data_local = self._local_max_stream_data_bidi_local <10> max_stream_data_remote = self._remote_max_stream_data_bidi_remote <11> max_streams = self._remote_max_streams_bidi <12> <13> # check max streams <14> if stream_id // 4 >= max_streams: <15> raise ValueError("Too many streams open") <16> <17> # create stream <18> stream = self._streams[stream_id] = QuicStream( <19> connection=self, <20> stream_id=stream_id, <21> max_stream_data_local=max_stream_data_local, <22> max_stream_data_remote=max_stream_data_remote, <23> ) <24> return stream <25>
===========unchanged ref 0=========== at: aioquic.connection stream_is_unidirectional(stream_id: int) -> bool at: aioquic.connection.QuicConnection _push_crypto_data() -> None at: aioquic.connection.QuicConnection.__init__ self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW 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._streams: Dict[int, QuicStream] = {} self._streams_blocked_bidi: List[QuicStream] = [] self._streams_blocked_uni: List[QuicStream] = [] at: aioquic.connection.QuicConnection._handle_max_streams_bidi_frame self._remote_max_streams_bidi = max_streams at: aioquic.connection.QuicConnection._handle_max_streams_uni_frame self._remote_max_streams_uni = max_streams at: aioquic.connection.QuicConnection._initialize self.tls = tls.Context(is_client=self._is_client, logger=self._logger) self._crypto_buffers = { tls.Epoch.INITIAL: Buffer(capacity=4096), tls.Epoch.HANDSHAKE: Buffer(capacity=4096), tls.Epoch.ONE_RTT: Buffer(capacity=4096), } at: aioquic.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.Context handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None ===========changed ref 0=========== # module: aioquic.stream class QuicStream: def __init__( self, stream_id: Optional[int] = None, connection: Optional[Any] = None, max_stream_data_local: int = 0, max_stream_data_remote: int = 0, ) -> None: self._connection = connection + self.is_blocked = False self.max_stream_data_local = max_stream_data_local self.max_stream_data_local_sent = max_stream_data_local self.max_stream_data_remote = max_stream_data_remote self.send_buffer_is_empty = True self._recv_buffer = bytearray() self._recv_buffer_fin: Optional[int] = None self._recv_buffer_start = 0 # the offset for the start of the buffer self._recv_highest = 0 # the highest offset ever seen self._recv_ranges = RangeSet() self._send_acked = RangeSet() self._send_buffer = bytearray() self._send_buffer_fin: Optional[int] = None self._send_buffer_start = 0 # the offset for the start of the buffer self._send_buffer_stop = 0 # the offset for the stop of the buffer self._send_highest = 0 self._send_pending = RangeSet() self._send_pending_eof = False self.__stream_id = stream_id ===========changed ref 1=========== # module: aioquic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: if configuration.is_client: assert ( original_connection_id is None ), "Cannot set original_connection_id for a client" else: assert ( configuration.certificate is not None ), "SSL certificate is required for a server" assert ( configuration.private_key is not None ), "SSL private key is required for a server" # counters for debugging self._stateless_retry_count = 0 self._version_negotiation_count = 0 # configuration self._configuration = configuration self._is_client = configuration.is_client self._ack_delay = K_GRANULARITY self._close_at: Optional[float] = None self._close_event: Optional[events.ConnectionTerminated] = None self._connect_called = False self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} self._events: Deque[events.Event] = deque() self._handshake_complete = False self._handshake_confirmed = False self._host_cids = [ QuicConnectionId( cid=os.urandom(8), sequence_number=0, stateless_reset_token=os.urandom(16), was_sent=True, ) ] self.host_cid = self._host_cids[0].cid self._host_cid_seq = 1 self._local_max_data = MAX_DATA_WINDOW self._local</s> ===========changed ref 2=========== # module: aioquic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 1 <s> self._host_cid_seq = 1 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(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_idle_timeout = 0.0 # seconds self._remote_max_data = 0 self._remote_max_data_used = 0 self._remote_max_stream_</s>
aioquic.connection/QuicConnection._handle_crypto_frame
Modified
aiortc~aioquic
1f48726433a6b5d4abc34758228516aaa2432269
[streams] send STREAMS_BLOCKED if stream limit is exceeded
# module: aioquic.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._replenish_connection_ids() <39> self._events.append( <40> events.HandshakeCompleted( <41> alpn_protocol=self.tls.alpn_negotiated, <42> early_data_accepted=self.tls.early_data_accepted,</s>
===========below chunk 0=========== # module: aioquic.connection class QuicConnection: def _handle_crypto_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: # offset: 1 ) ) 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.connection QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, time: float) at: aioquic.connection.QuicConnection _close_begin(is_initiator: bool, now: float) -> None _replenish_connection_ids() -> None _push_crypto_data() -> None _parse_transport_parameters(data: bytes, from_session_ticket: bool=False) -> None at: aioquic.connection.QuicConnection.__init__ self._close_event: Optional[events.ConnectionTerminated] = None self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} self._events: Deque[events.Event] = deque() self._handshake_complete = False self._logger = QuicConnectionAdapter( logger, {"host_cid": dump_cid(self.host_cid)} ) self._parameters_received = False at: aioquic.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.connection.QuicConnection._initialize self.tls = tls.Context(is_client=self._is_client, logger=self._logger) ===========unchanged ref 1=========== 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.connection.QuicConnection.close self._close_event = events.ConnectionTerminated( error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase, ) at: aioquic.connection.QuicConnection.handle_timer self._close_event = events.ConnectionTerminated( error_code=QuicErrorCode.INTERNAL_ERROR, frame_type=None, reason_phrase="Idle timeout", ) at: aioquic.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.connection.QuicReceiveContext epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath time: float at: aioquic.events ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str) HandshakeCompleted(alpn_protocol: Optional[str], early_data_accepted: bool, session_resumed: bool) at: aioquic.events.ConnectionTerminated error_code: int frame_type: Optional[int] reason_phrase: str ===========unchanged ref 2=========== at: aioquic.packet QuicErrorCode(x: Union[str, bytes, bytearray], base: int) QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) pull_crypto_frame(buf: Buffer) -> QuicStreamFrame at: aioquic.stream.QuicStream add_frame(frame: QuicStreamFrame) -> None pull_data() -> bytes at: aioquic.tls Alert(*args: object) State() ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: aioquic.tls.Alert description: AlertDescription at: aioquic.tls.Context handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None at: aioquic.tls.Context.__init__ self.received_extensions: Optional[List[Extension]] = None self.state = State.CLIENT_HANDSHAKE_START self.state = State.SERVER_EXPECT_CLIENT_HELLO at: aioquic.tls.Context._client_handle_encrypted_extensions self.received_extensions = encrypted_extensions.other_extensions at: aioquic.tls.Context._server_handle_hello self.received_extensions = peer_hello.other_extensions at: aioquic.tls.Context._set_state self.state = state at: collections.deque append(x: _T) -> None at: logging.LoggerAdapter logger: Logger extra: Mapping[str, Any] ===========unchanged ref 3=========== info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None ===========changed ref 0=========== # module: aioquic.connection class QuicConnection: def _create_stream(self, stream_id: int) -> QuicStream: """ Create a QUIC stream in order to send data to the peer. """ # determine limits if stream_is_unidirectional(stream_id): max_stream_data_local = 0 max_stream_data_remote = self._remote_max_stream_data_uni max_streams = self._remote_max_streams_uni + streams_blocked = self._streams_blocked_uni else: max_stream_data_local = self._local_max_stream_data_bidi_local max_stream_data_remote = self._remote_max_stream_data_bidi_remote max_streams = self._remote_max_streams_bidi - - # check max streams - if stream_id // 4 >= max_streams: - raise ValueError("Too many streams open") + streams_blocked = self._streams_blocked_bidi # create stream stream = self._streams[stream_id] = QuicStream( connection=self, stream_id=stream_id, max_stream_data_local=max_stream_data_local, max_stream_data_remote=max_stream_data_remote, ) + + # mark stream as blocked if needed + if stream_id // 4 >= max_streams: + stream.is_blocked = True + streams_blocked.append(stream) + self._streams_blocked_pending = True + return stream
aioquic.connection/QuicConnection._handle_max_streams_bidi_frame
Modified
aiortc~aioquic
1f48726433a6b5d4abc34758228516aaa2432269
[streams] send STREAMS_BLOCKED if stream limit is exceeded
<9>:<add> self._unblock_streams(is_unidirectional=False)
# module: aioquic.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>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.connection QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, time: float) at: aioquic.connection.QuicConnection _get_or_create_stream(frame_type: int, stream_id: int) -> QuicStream at: aioquic.connection.QuicConnection.__init__ self._logger = QuicConnectionAdapter( logger, {"host_cid": dump_cid(self.host_cid)} ) at: aioquic.connection.QuicConnection._handle_max_stream_data_frame stream_id = buf.pull_uint_var() max_stream_data = buf.pull_uint_var() at: aioquic.stream.QuicStream.__init__ self.max_stream_data_remote = max_stream_data_remote 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.connection class QuicConnection: def _handle_crypto_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a CRYPTO frame. """ stream = self._crypto_streams[context.epoch] 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_HANDSHAKE, ]: self._handshake_complete = True 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) </s> ===========changed ref 1=========== # module: aioquic.connection class QuicConnection: def _handle_crypto_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: # offset: 1 <s>_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 2=========== # module: aioquic.connection class QuicConnection: def _create_stream(self, stream_id: int) -> QuicStream: """ Create a QUIC stream in order to send data to the peer. """ # determine limits if stream_is_unidirectional(stream_id): max_stream_data_local = 0 max_stream_data_remote = self._remote_max_stream_data_uni max_streams = self._remote_max_streams_uni + streams_blocked = self._streams_blocked_uni else: max_stream_data_local = self._local_max_stream_data_bidi_local max_stream_data_remote = self._remote_max_stream_data_bidi_remote max_streams = self._remote_max_streams_bidi - - # check max streams - if stream_id // 4 >= max_streams: - raise ValueError("Too many streams open") + streams_blocked = self._streams_blocked_bidi # create stream stream = self._streams[stream_id] = QuicStream( connection=self, stream_id=stream_id, max_stream_data_local=max_stream_data_local, max_stream_data_remote=max_stream_data_remote, ) + + # mark stream as blocked if needed + if stream_id // 4 >= max_streams: + stream.is_blocked = True + streams_blocked.append(stream) + self._streams_blocked_pending = True + return stream ===========changed ref 3=========== # module: aioquic.stream class QuicStream: def __init__( self, stream_id: Optional[int] = None, connection: Optional[Any] = None, max_stream_data_local: int = 0, max_stream_data_remote: int = 0, ) -> None: self._connection = connection + self.is_blocked = False self.max_stream_data_local = max_stream_data_local self.max_stream_data_local_sent = max_stream_data_local self.max_stream_data_remote = max_stream_data_remote self.send_buffer_is_empty = True self._recv_buffer = bytearray() self._recv_buffer_fin: Optional[int] = None self._recv_buffer_start = 0 # the offset for the start of the buffer self._recv_highest = 0 # the highest offset ever seen self._recv_ranges = RangeSet() self._send_acked = RangeSet() self._send_buffer = bytearray() self._send_buffer_fin: Optional[int] = None self._send_buffer_start = 0 # the offset for the start of the buffer self._send_buffer_stop = 0 # the offset for the stop of the buffer self._send_highest = 0 self._send_pending = RangeSet() self._send_pending_eof = False self.__stream_id = stream_id
aioquic.connection/QuicConnection._handle_max_streams_uni_frame
Modified
aiortc~aioquic
1f48726433a6b5d4abc34758228516aaa2432269
[streams] send STREAMS_BLOCKED if stream limit is exceeded
<9>:<add> self._unblock_streams(is_unidirectional=True)
# module: aioquic.connection class QuicConnection: def _handle_max_streams_uni_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: <0> """ <1> Handle a MAX_STREAMS_UNI frame. <2> <3> This raises number of unidirectional streams we can initiate to the peer. <4> """ <5> max_streams = buf.pull_uint_var() <6> if max_streams > self._remote_max_streams_uni: <7> self._logger.debug("Remote max_streams_uni raised to %d", max_streams) <8> self._remote_max_streams_uni = max_streams <9>
===========unchanged ref 0=========== at: aioquic._buffer.Buffer pull_uint_var() -> int at: aioquic.connection.QuicConnection _unblock_streams(is_unidirectional: bool) -> None at: aioquic.connection.QuicConnection.__init__ self._logger = QuicConnectionAdapter( logger, {"host_cid": dump_cid(self.host_cid)} ) self._remote_max_streams_bidi = 0 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.connection class QuicConnection: def _handle_max_streams_bidi_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a MAX_STREAMS_BIDI frame. This raises number of bidirectional streams we can initiate to the peer. """ max_streams = buf.pull_uint_var() if max_streams > self._remote_max_streams_bidi: self._logger.debug("Remote max_streams_bidi raised to %d", max_streams) self._remote_max_streams_bidi = max_streams + self._unblock_streams(is_unidirectional=False) ===========changed ref 1=========== # module: aioquic.connection class QuicConnection: def _handle_crypto_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a CRYPTO frame. """ stream = self._crypto_streams[context.epoch] 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_HANDSHAKE, ]: self._handshake_complete = True 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) </s> ===========changed ref 2=========== # module: aioquic.connection class QuicConnection: def _handle_crypto_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: # offset: 1 <s>_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.connection class QuicConnection: def _create_stream(self, stream_id: int) -> QuicStream: """ Create a QUIC stream in order to send data to the peer. """ # determine limits if stream_is_unidirectional(stream_id): max_stream_data_local = 0 max_stream_data_remote = self._remote_max_stream_data_uni max_streams = self._remote_max_streams_uni + streams_blocked = self._streams_blocked_uni else: max_stream_data_local = self._local_max_stream_data_bidi_local max_stream_data_remote = self._remote_max_stream_data_bidi_remote max_streams = self._remote_max_streams_bidi - - # check max streams - if stream_id // 4 >= max_streams: - raise ValueError("Too many streams open") + streams_blocked = self._streams_blocked_bidi # create stream stream = self._streams[stream_id] = QuicStream( connection=self, stream_id=stream_id, max_stream_data_local=max_stream_data_local, max_stream_data_remote=max_stream_data_remote, ) + + # mark stream as blocked if needed + if stream_id // 4 >= max_streams: + stream.is_blocked = True + streams_blocked.append(stream) + self._streams_blocked_pending = True + return stream ===========changed ref 4=========== # module: aioquic.stream class QuicStream: def __init__( self, stream_id: Optional[int] = None, connection: Optional[Any] = None, max_stream_data_local: int = 0, max_stream_data_remote: int = 0, ) -> None: self._connection = connection + self.is_blocked = False self.max_stream_data_local = max_stream_data_local self.max_stream_data_local_sent = max_stream_data_local self.max_stream_data_remote = max_stream_data_remote self.send_buffer_is_empty = True self._recv_buffer = bytearray() self._recv_buffer_fin: Optional[int] = None self._recv_buffer_start = 0 # the offset for the start of the buffer self._recv_highest = 0 # the highest offset ever seen self._recv_ranges = RangeSet() self._send_acked = RangeSet() self._send_buffer = bytearray() self._send_buffer_fin: Optional[int] = None self._send_buffer_start = 0 # the offset for the start of the buffer self._send_buffer_stop = 0 # the offset for the stop of the buffer self._send_highest = 0 self._send_pending = RangeSet() self._send_pending_eof = False self.__stream_id = stream_id
aioquic.connection/QuicConnection._write_application
Modified
aiortc~aioquic
1f48726433a6b5d4abc34758228516aaa2432269
[streams] send STREAMS_BLOCKED if stream limit is exceeded
# module: aioquic.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, is_probe=self._probe_pending) <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> # PATH CHALLENGE <30> if ( <31> not network_path.is_validated <32> and network_path.local_challenge is None <33> ): <34> self._logger.info( <35> "Network path %s sending challenge", network_path.addr <36> ) <37> network_path.local_challenge = os.urandom(8) <38> builder.start_frame(QuicFrameType.PATH_CHALLENG</s>
===========below chunk 0=========== # module: aioquic.connection class QuicConnection: def _write_application( self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float ) -> None: # offset: 1 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, 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) # 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</s> ===========below chunk 1=========== # module: aioquic.connection class QuicConnection: def _write_application( self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float ) -> None: # offset: 2 <s> # 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.values(): # STREAM if 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.configuration.QuicConfiguration secrets_log_file: TextIO = None at: aioquic.connection SECRETS_LABELS = [ [ None, "QUIC_CLIENT_EARLY_TRAFFIC_SECRET", "QUIC_CLIENT_HANDSHAKE_TRAFFIC_SECRET", "QUIC_CLIENT_TRAFFIC_SECRET_0", ], [ None, None, "QUIC_SERVER_HANDSHAKE_TRAFFIC_SECRET", "QUIC_SERVER_TRAFFIC_SECRET_0", ], ] QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None) at: aioquic.connection.QuicConnection _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(builder: QuicPacketBuilder, space: QuicPacketSpace) -> None at: aioquic.connection.QuicConnection.__init__ self._configuration = configuration self._is_client = configuration.is_client self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} self._events: Deque[events.Event] = deque() self._handshake_complete = False ===========unchanged ref 1=========== self._host_cids = [ QuicConnectionId( cid=os.urandom(8), sequence_number=0, stateless_reset_token=os.urandom(16), was_sent=True, ) ] self._logger = QuicConnectionAdapter( logger, {"host_cid": dump_cid(self.host_cid)} ) self._remote_max_streams_bidi = 0 self._remote_max_streams_uni = 0 self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._streams_blocked_bidi: List[QuicStream] = [] self._streams_blocked_uni: List[QuicStream] = [] self._probe_pending = False self._retire_connection_ids: List[int] = [] self._streams_blocked_pending = False at: aioquic.connection.QuicConnection._create_stream self._streams_blocked_pending = True at: aioquic.connection.QuicConnection._handle_crypto_frame self._handshake_complete = True at: aioquic.connection.QuicConnection._handle_max_streams_bidi_frame self._remote_max_streams_bidi = max_streams at: aioquic.connection.QuicConnection._handle_max_streams_uni_frame self._remote_max_streams_uni = max_streams at: aioquic.connection.QuicConnection._initialize self.tls = tls.Context(is_client=self._is_client, logger=self._logger) self._cryptos = { tls.Epoch.INITIAL: CryptoPair(), tls.Epoch.ZERO_RTT: CryptoPair(), tls.Epoch.HANDSHAKE: CryptoPair(), tls.Epoch.ONE_RTT: CryptoPair(), }
aioquic.h3.connection/H3Connection.__init__
Modified
aiortc~aioquic
fb53b77f38b7a1448b11f94d1bb0a37fae3b1e08
[http3] don't buffer data, pass it to the QUIC layer
<3>:<del> self._handshake_completed = False <8>:<del> self._pending: List[Tuple[int, bytes, bool]] = []
# module: aioquic.h3.connection class H3Connection: def __init__(self, quic: QuicConnection): <0> self._max_table_capacity = 0x100 <1> self._blocked_streams = 0x10 <2> <3> self._handshake_completed = False <4> self._is_client = quic.configuration.is_client <5> self._quic = quic <6> self._decoder = Decoder(self._max_table_capacity, self._blocked_streams) <7> self._encoder = Encoder() <8> self._pending: List[Tuple[int, bytes, bool]] = [] <9> self._stream_buffers: Dict[int, bytes] = {} <10> self._stream_types: Dict[int, int] = {} <11> <12> self._local_control_stream_id: Optional[int] = None <13> self._local_decoder_stream_id: Optional[int] = None <14> self._local_encoder_stream_id: Optional[int] = None <15> <16> self._peer_control_stream_id: Optional[int] = None <17> self._peer_decoder_stream_id: Optional[int] = None <18> self._peer_encoder_stream_id: Optional[int] = None <19>
===========unchanged ref 0=========== at: aioquic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20, ] ) at: aioquic.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.h3.connection.H3Connection._receive_stream_data self._peer_control_stream_id = stream_id self._peer_decoder_stream_id = stream_id self._peer_encoder_stream_id = stream_id at: aioquic.h3.connection.H3Connection._update self._local_control_stream_id = self._create_uni_stream( StreamType.CONTROL ) self._local_encoder_stream_id = self._create_uni_stream( StreamType.QPACK_ENCODER ) self._local_decoder_stream_id = self._create_uni_stream( StreamType.QPACK_DECODER ) at: aioquic.h3.events Event() at: typing List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict')
aioquic.h3.connection/H3Connection.send_data
Modified
aiortc~aioquic
fb53b77f38b7a1448b11f94d1bb0a37fae3b1e08
[http3] don't buffer data, pass it to the QUIC layer
<7>:<add> self._quic.send_stream_data( <del> self._send_stream_data(
# module: aioquic.h3.connection class H3Connection: def send_data(self, stream_id: int, data: bytes, end_stream: bool) -> None: <0> """ <1> Send data on the given stream. <2> <3> To retrieve datagram which need to be sent over the network call the QUIC <4> connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send` <5> method. <6> """ <7> self._send_stream_data( <8> stream_id, encode_frame(FrameType.DATA, data), end_stream <9> ) <10>
===========unchanged ref 0=========== at: aioquic.connection.QuicConnection send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None at: aioquic.h3.connection FrameType(x: Union[str, bytes, bytearray], base: int) FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) encode_frame(frame_type: int, frame_data: bytes) -> bytes at: aioquic.h3.connection.H3Connection.__init__ self._quic = quic at: aioquic.h3.events Headers = List[Tuple[bytes, bytes]] ===========changed ref 0=========== # module: aioquic.h3.connection class H3Connection: def __init__(self, quic: QuicConnection): self._max_table_capacity = 0x100 self._blocked_streams = 0x10 - self._handshake_completed = False self._is_client = quic.configuration.is_client self._quic = quic self._decoder = Decoder(self._max_table_capacity, self._blocked_streams) self._encoder = Encoder() - self._pending: List[Tuple[int, bytes, bool]] = [] self._stream_buffers: Dict[int, bytes] = {} self._stream_types: Dict[int, int] = {} self._local_control_stream_id: Optional[int] = None self._local_decoder_stream_id: Optional[int] = None self._local_encoder_stream_id: Optional[int] = None self._peer_control_stream_id: Optional[int] = None self._peer_decoder_stream_id: Optional[int] = None self._peer_encoder_stream_id: Optional[int] = None
aioquic.h3.connection/H3Connection.send_headers
Modified
aiortc~aioquic
fb53b77f38b7a1448b11f94d1bb0a37fae3b1e08
[http3] don't buffer data, pass it to the QUIC layer
<8>:<add> self._quic.send_stream_data( <del> self._send_stream_data(
# module: aioquic.h3.connection class H3Connection: def send_headers(self, stream_id: int, headers: Headers) -> None: <0> """ <1> Send headers on the given stream. <2> <3> To retrieve datagram which need to be sent over the network call the QUIC <4> connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send` <5> method. <6> """ <7> control, header = self._encoder.encode(stream_id, 0, headers) <8> self._send_stream_data( <9> stream_id, encode_frame(FrameType.HEADERS, header), False <10> ) <11>
===========unchanged ref 0=========== at: aioquic.connection.QuicConnection send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None at: aioquic.h3.connection FrameType(x: Union[str, bytes, bytearray], base: int) FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) encode_frame(frame_type: int, frame_data: bytes) -> bytes at: aioquic.h3.connection.H3Connection.__init__ self._quic = quic self._encoder = Encoder() ===========changed ref 0=========== # module: aioquic.h3.connection class H3Connection: def send_data(self, stream_id: int, data: bytes, end_stream: bool) -> None: """ Send data on the given stream. To retrieve datagram which need to be sent over the network call the QUIC connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send` method. """ + self._quic.send_stream_data( - self._send_stream_data( stream_id, encode_frame(FrameType.DATA, data), end_stream ) ===========changed ref 1=========== # module: aioquic.h3.connection class H3Connection: def __init__(self, quic: QuicConnection): self._max_table_capacity = 0x100 self._blocked_streams = 0x10 - self._handshake_completed = False self._is_client = quic.configuration.is_client self._quic = quic self._decoder = Decoder(self._max_table_capacity, self._blocked_streams) self._encoder = Encoder() - self._pending: List[Tuple[int, bytes, bool]] = [] self._stream_buffers: Dict[int, bytes] = {} self._stream_types: Dict[int, int] = {} self._local_control_stream_id: Optional[int] = None self._local_decoder_stream_id: Optional[int] = None self._local_encoder_stream_id: Optional[int] = None self._peer_control_stream_id: Optional[int] = None self._peer_decoder_stream_id: Optional[int] = None self._peer_encoder_stream_id: Optional[int] = None
aioquic.h3.connection/H3Connection._update
Modified
aiortc~aioquic
fb53b77f38b7a1448b11f94d1bb0a37fae3b1e08
[http3] don't buffer data, pass it to the QUIC layer
<6>:<del> self._handshake_completed = True <7>:<del> <32>:<del> <33>:<del> # send pending data <34>:<del> for args in self._pending: <35>:<del> self._quic.send_stream_data(*args) <36>:<del> self._pending.clear()
# module: aioquic.h3.connection class H3Connection: def _update(self) -> List[Event]: <0> http_events: List[Event] = [] <1> <2> # process QUIC events <3> event = self._quic.next_event() <4> while event is not None: <5> if isinstance(event, aioquic.events.HandshakeCompleted): <6> self._handshake_completed = True <7> <8> # send our settings <9> self._local_control_stream_id = self._create_uni_stream( <10> StreamType.CONTROL <11> ) <12> self._quic.send_stream_data( <13> self._local_control_stream_id, <14> encode_frame( <15> FrameType.SETTINGS, <16> encode_settings( <17> { <18> Setting.QPACK_MAX_TABLE_CAPACITY: self._max_table_capacity, <19> Setting.QPACK_BLOCKED_STREAMS: self._blocked_streams, <20> } <21> ), <22> ), <23> ) <24> <25> # create encoder and decoder streams <26> self._local_encoder_stream_id = self._create_uni_stream( <27> StreamType.QPACK_ENCODER <28> ) <29> self._local_decoder_stream_id = self._create_uni_stream( <30> StreamType.QPACK_DECODER <31> ) <32> <33> # send pending data <34> for args in self._pending: <35> self._quic.send_stream_data(*args) <36> self._pending.clear() <37> elif isinstance(event, aioquic.events.StreamDataReceived): <38> http_events.extend( <39> self._receive_stream_data( <40> event.stream_id, event.data, event.end_stream <41> ) <42> ) <43> <44> event = self._quic.next_event() <45> <46> return http_events <47>
===========unchanged ref 0=========== at: aioquic.connection.QuicConnection next_event() -> Optional[events.Event] send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None at: aioquic.events StreamDataReceived(data: bytes, end_stream: bool, stream_id: int) at: aioquic.h3.connection FrameType(x: Union[str, bytes, bytearray], base: int) FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Setting(x: Union[str, bytes, bytearray], base: int) Setting(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, bytearray], base: int) encode_frame(frame_type: int, frame_data: bytes) -> bytes encode_settings(settings: Dict[int, int]) -> bytes at: aioquic.h3.connection.H3Connection _create_uni_stream(stream_type: int) -> int _create_uni_stream(self, stream_type: int) -> int _receive_stream_data(stream_id: int, data: bytes, stream_ended: bool) -> List[Event] at: aioquic.h3.connection.H3Connection.__init__ self._max_table_capacity = 0x100 self._blocked_streams = 0x10 self._quic = quic self._local_control_stream_id: Optional[int] = None self._local_decoder_stream_id: Optional[int] = None self._local_encoder_stream_id: Optional[int] = None at: aioquic.h3.connection.H3Connection._update http_events: List[Event] = [] ===========changed ref 0=========== # module: aioquic.h3.connection class H3Connection: - def _send_stream_data(self, stream_id: int, data: bytes, end_stream: bool) -> None: - if self._handshake_completed: - self._quic.send_stream_data(stream_id, data, end_stream) - else: - self._pending.append((stream_id, data, end_stream)) - ===========changed ref 1=========== # module: aioquic.h3.connection class H3Connection: def send_data(self, stream_id: int, data: bytes, end_stream: bool) -> None: """ Send data on the given stream. To retrieve datagram which need to be sent over the network call the QUIC connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send` method. """ + self._quic.send_stream_data( - self._send_stream_data( stream_id, encode_frame(FrameType.DATA, data), end_stream ) ===========changed ref 2=========== # module: aioquic.h3.connection class H3Connection: def send_headers(self, stream_id: int, headers: Headers) -> None: """ Send headers on the given stream. To retrieve datagram which need to be sent over the network call the QUIC connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send` method. """ control, header = self._encoder.encode(stream_id, 0, headers) + self._quic.send_stream_data( - self._send_stream_data( stream_id, encode_frame(FrameType.HEADERS, header), False ) ===========changed ref 3=========== # module: aioquic.h3.connection class H3Connection: def __init__(self, quic: QuicConnection): self._max_table_capacity = 0x100 self._blocked_streams = 0x10 - self._handshake_completed = False self._is_client = quic.configuration.is_client self._quic = quic self._decoder = Decoder(self._max_table_capacity, self._blocked_streams) self._encoder = Encoder() - self._pending: List[Tuple[int, bytes, bool]] = [] self._stream_buffers: Dict[int, bytes] = {} self._stream_types: Dict[int, int] = {} self._local_control_stream_id: Optional[int] = None self._local_decoder_stream_id: Optional[int] = None self._local_encoder_stream_id: Optional[int] = None self._peer_control_stream_id: Optional[int] = None self._peer_decoder_stream_id: Optional[int] = None self._peer_encoder_stream_id: Optional[int] = None
tests.test_h3/H3ConnectionTest.test_connect
Modified
aiortc~aioquic
07df8b382bd5ea1f34f109a06374b52852cf4b88
[tests] rework HTTP/3 tests
<19>:<del> self.assertEqual(h3_client._update(), []) <22>:<add> events = h3_transfer(quic_client, h3_server) <del> transfer(quic_client, quic_server) <23>:<del> events = h3_server._update()
# module: tests.test_h3 class H3ConnectionTest(TestCase): def test_connect(self): <0> with client_and_server( <1> client_options={"alpn_protocols": ["h3-20"]}, <2> server_options={"alpn_protocols": ["h3-20"]}, <3> ) as (quic_client, quic_server): <4> h3_client = H3Connection(quic_client) <5> h3_server = H3Connection(quic_server) <6> <7> # send request <8> stream_id = quic_client.get_next_available_stream_id() <9> h3_client.send_headers( <10> stream_id=stream_id, <11> headers=[ <12> (b":method", b"GET"), <13> (b":scheme", b"https"), <14> (b":authority", b"localhost"), <15> (b":path", b"/"), <16> ], <17> ) <18> h3_client.send_data(stream_id=stream_id, data=b"", end_stream=True) <19> self.assertEqual(h3_client._update(), []) <20> <21> # receive request <22> transfer(quic_client, quic_server) <23> events = h3_server._update() <24> self.assertEqual(len(events), 2) <25> <26> self.assertTrue(isinstance(events[0], RequestReceived)) <27> self.assertEqual( <28> events[0].headers, <29> [ <30> (b":method", b"GET"), <31> (b":scheme", b"https"), <32> (b":authority", b"localhost"), <33> (b":path", b"/"), <34> ], <35> ) <36> self.assertEqual(events[0].stream_id, stream_id) <37> self.assertEqual(events[0].stream_ended, False) <38> <39> self.assertTrue(isinstance(events[1], DataReceived)) <40> self.assertEqual(events</s>
===========below chunk 0=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_connect(self): # offset: 1 self.assertEqual(events[1].stream_id, stream_id) self.assertEqual(events[1].stream_ended, True) # send response h3_server.send_headers( stream_id=stream_id, headers=[ (b":status", b"200"), (b"content-type", b"text/html; charset=utf-8"), ], ) h3_server.send_data( stream_id=stream_id, data=b"<html><body>hello</body></html>", end_stream=True, ) self.assertEqual(h3_server._update(), []) # receive response transfer(quic_server, quic_client) events = h3_client._update() self.assertEqual(len(events), 2) self.assertTrue(isinstance(events[0], ResponseReceived)) self.assertEqual( events[0].headers, [(b":status", b"200"), (b"content-type", b"text/html; charset=utf-8")], ) self.assertEqual(events[0].stream_id, stream_id) self.assertEqual(events[0].stream_ended, False) self.assertTrue(isinstance(events[1], DataReceived)) self.assertEqual(events[1].data, b"<html><body>hello</body></html>") self.assertEqual(events[1].stream_id, stream_id) self.assertEqual(events[1].stream_ended, True) ===========unchanged ref 0=========== 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 _update() -> List[Event] at: aioquic.h3.connection.H3Connection.__init__ self._quic = quic at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool) RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: tests.test_connection client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={}) transfer(sender, receiver) at: tests.test_h3 h3_transfer(quic_sender, h3_receiver) at: unittest.case TestCase(methodName: str=...) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_h3 + def h3_transfer(quic_sender, h3_receiver): + transfer(quic_sender, h3_receiver._quic) + return h3_receiver._update() +
tests.test_h3/H3ConnectionTest.test_uni_stream_type
Modified
aiortc~aioquic
07df8b382bd5ea1f34f109a06374b52852cf4b88
[tests] rework HTTP/3 tests
<10>:<del> transfer(quic_client, quic_server) <11>:<del> self.assertEqual(h3_server._update(), []) <12>:<add> self.assertEqual(h3_transfer(quic_client, h3_server), []) <20>:<del> transfer(quic_client, quic_server) <21>:<del> self.assertEqual(h3_server._update(), []) <22>:<add> self.assertEqual(h3_transfer(quic_client, h3_server), []) <26>:<del> transfer(quic_client, quic_server) <27>:<del> self.assertEqual(h3_server._update(), []) <28>:<add> self.assertEqual(h3_transfer(quic_client, h3_server), [])
# module: tests.test_h3 class H3ConnectionTest(TestCase): def test_uni_stream_type(self): <0> with client_and_server( <1> client_options={"alpn_protocols": ["h3-20"]}, <2> server_options={"alpn_protocols": ["h3-20"]}, <3> ) as (quic_client, quic_server): <4> h3_server = H3Connection(quic_server) <5> <6> # unknown stream type 9 <7> stream_id = quic_client.get_next_available_stream_id(is_unidirectional=True) <8> self.assertEqual(stream_id, 2) <9> quic_client.send_stream_data(stream_id, b"\x09") <10> transfer(quic_client, quic_server) <11> self.assertEqual(h3_server._update(), []) <12> self.assertEqual(h3_server._stream_buffers, {2: b""}) <13> self.assertEqual(h3_server._stream_types, {2: 9}) <14> <15> # unknown stream type 64, one byte at a time <16> stream_id = quic_client.get_next_available_stream_id(is_unidirectional=True) <17> self.assertEqual(stream_id, 6) <18> <19> quic_client.send_stream_data(stream_id, b"\x40") <20> transfer(quic_client, quic_server) <21> self.assertEqual(h3_server._update(), []) <22> self.assertEqual(h3_server._stream_buffers, {2: b"", 6: b"\x40"}) <23> self.assertEqual(h3_server._stream_types, {2: 9}) <24> <25> quic_client.send_stream_data(stream_id, b"\x40") <26> transfer(quic_client, quic_server) <27> self.assertEqual(h3_server._update(), []) <28> self.assertEqual(h3_server._stream</s>
===========below chunk 0=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_uni_stream_type(self): # offset: 1 self.assertEqual(h3_server._stream_types, {2: 9, 6: 64}) ===========unchanged ref 0=========== at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection.__init__ self._stream_buffers: Dict[int, bytes] = {} self._stream_types: Dict[int, int] = {} at: tests.test_connection client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={}) at: tests.test_h3 h3_transfer(quic_sender, h3_receiver) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_h3 + def h3_transfer(quic_sender, h3_receiver): + transfer(quic_sender, h3_receiver._quic) + return h3_receiver._update() + ===========changed ref 1=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_connect(self): with client_and_server( client_options={"alpn_protocols": ["h3-20"]}, server_options={"alpn_protocols": ["h3-20"]}, ) as (quic_client, quic_server): h3_client = H3Connection(quic_client) h3_server = H3Connection(quic_server) # send request stream_id = quic_client.get_next_available_stream_id() h3_client.send_headers( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", b"/"), ], ) h3_client.send_data(stream_id=stream_id, data=b"", end_stream=True) - self.assertEqual(h3_client._update(), []) # receive request + events = h3_transfer(quic_client, h3_server) - transfer(quic_client, quic_server) - events = h3_server._update() self.assertEqual(len(events), 2) self.assertTrue(isinstance(events[0], RequestReceived)) self.assertEqual( events[0].headers, [ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", b"/"), ], ) self.assertEqual(events[0].stream_id, stream_id) self.assertEqual(events[0].stream_ended, False) self.assertTrue(isinstance(events[1], DataReceived)) self.assertEqual(events[1].data, b"") self.assertEqual(events[1</s> ===========changed ref 2=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_connect(self): # offset: 1 <s>], DataReceived)) self.assertEqual(events[1].data, b"") self.assertEqual(events[1].stream_id, stream_id) self.assertEqual(events[1].stream_ended, True) # send response h3_server.send_headers( stream_id=stream_id, headers=[ (b":status", b"200"), (b"content-type", b"text/html; charset=utf-8"), ], ) h3_server.send_data( stream_id=stream_id, data=b"<html><body>hello</body></html>", end_stream=True, ) - self.assertEqual(h3_server._update(), []) # receive response + events = h3_transfer(quic_server, h3_client) - transfer(quic_server, quic_client) - events = h3_client._update() self.assertEqual(len(events), 2) self.assertTrue(isinstance(events[0], ResponseReceived)) self.assertEqual( events[0].headers, [(b":status", b"200"), (b"content-type", b"text/html; charset=utf-8")], ) self.assertEqual(events[0].stream_id, stream_id) self.assertEqual(events[0].stream_ended, False) self.assertTrue(isinstance(events[1], DataReceived)) self.assertEqual(events[1].data, b"<html><body>hello</body></html>") self.assertEqual(events[1].stream_id, stream_id) self.assertEqual(events[1].stream_ended,
tests.test_h3/h3_transfer
Modified
aiortc~aioquic
79cea49297f3cc02bca640db80e037ffea5a02c2
[http3] rework events API
<1>:<add> return h3_receiver.handle_events() <del> return h3_receiver._update()
# module: tests.test_h3 def h3_transfer(quic_sender, h3_receiver): <0> transfer(quic_sender, h3_receiver._quic) <1> return h3_receiver._update() <2>
===========unchanged ref 0=========== at: aioquic.h3.connection.H3Connection handle_events() -> List[Event] at: aioquic.h3.connection.H3Connection.__init__ self._quic = quic at: tests.test_connection transfer(sender, receiver) ===========changed ref 0=========== # module: aioquic.h3.connection class H3Connection: + def handle_events(self) -> List[Event]: + """ + Handle events from the QUIC connection and return HTTP events. + """ + http_events: List[Event] = [] + + # process QUIC events + event = self._quic.next_event() + while event is not None: + if isinstance(event, aioquic.events.StreamDataReceived): + http_events.extend( + self._receive_stream_data( + event.stream_id, event.data, event.end_stream + ) + ) + + event = self._quic.next_event() + + return http_events + ===========changed ref 1=========== # module: aioquic.h3.connection class H3Connection: - def receive_datagram(self, data: bytes, addr: Any, now: float) -> List[Event]: - """ - Handle an incoming datagram and return events. - """ - self._quic.receive_datagram(data, addr, now=now) - return self._update() - ===========changed ref 2=========== # module: aioquic.h3.connection class H3Connection: + def _init_connection(self) -> None: + # send our settings + self._local_control_stream_id = self._create_uni_stream(StreamType.CONTROL) + self._quic.send_stream_data( + self._local_control_stream_id, + encode_frame( + FrameType.SETTINGS, + encode_settings( + { + Setting.QPACK_MAX_TABLE_CAPACITY: self._max_table_capacity, + Setting.QPACK_BLOCKED_STREAMS: self._blocked_streams, + } + ), + ), + ) + + # create encoder and decoder streams + self._local_encoder_stream_id = self._create_uni_stream( + StreamType.QPACK_ENCODER + ) + self._local_decoder_stream_id = self._create_uni_stream( + StreamType.QPACK_DECODER + ) + ===========changed ref 3=========== # module: aioquic.h3.connection class H3Connection: - def _update(self) -> List[Event]: - http_events: List[Event] = [] - - # process QUIC events - event = self._quic.next_event() - while event is not None: - if isinstance(event, aioquic.events.HandshakeCompleted): - # send our settings - self._local_control_stream_id = self._create_uni_stream( - StreamType.CONTROL - ) - self._quic.send_stream_data( - self._local_control_stream_id, - encode_frame( - FrameType.SETTINGS, - encode_settings( - { - Setting.QPACK_MAX_TABLE_CAPACITY: self._max_table_capacity, - Setting.QPACK_BLOCKED_STREAMS: self._blocked_streams, - } - ), - ), - ) - - # create encoder and decoder streams - self._local_encoder_stream_id = self._create_uni_stream( - StreamType.QPACK_ENCODER - ) - self._local_decoder_stream_id = self._create_uni_stream( - StreamType.QPACK_DECODER - ) - elif isinstance(event, aioquic.events.StreamDataReceived): - http_events.extend( - self._receive_stream_data( - event.stream_id, event.data, event.end_stream - ) - ) - - event = self._quic.next_event() - - return http_events -
examples.http3/run
Modified
aiortc~aioquic
79cea49297f3cc02bca640db80e037ffea5a02c2
[http3] rework events API
<26>:<add> http = H3Connection(quic) <del> conn = H3Connection(quic) <28>:<add> http.send_headers( <del> conn.send_headers( <37>:<add> http.send_data(stream_id=stream_id, data=b"", end_stream=True) <del> conn.send_data(stream_id=stream_id, data=b"", end_stream=True)
# module: examples.http3 def run(url: str) -> None: <0> # parse URL <1> parsed = urlparse(url) <2> assert parsed.scheme == "https", "Only HTTPS URLs are supported." <3> if ":" in parsed.netloc: <4> server_name, port_str = parsed.netloc.split(":") <5> port = int(port_str) <6> else: <7> server_name = parsed.netloc <8> port = 443 <9> <10> # prepare socket <11> server_addr = (socket.gethostbyname(server_name), port) <12> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <13> <14> # prepare QUIC connection <15> quic = QuicConnection( <16> configuration=QuicConfiguration( <17> alpn_protocols=["h3-20"], <18> is_client=True, <19> secrets_log_file=open("/tmp/ssl.log", "w"), <20> server_name=server_name, <21> ) <22> ) <23> quic.connect(server_addr, now=time.time()) <24> <25> # send request <26> conn = H3Connection(quic) <27> stream_id = quic.get_next_available_stream_id() <28> conn.send_headers( <29> stream_id=stream_id, <30> headers=[ <31> (b":method", b"GET"), <32> (b":scheme", parsed.scheme.encode("utf8")), <33> (b":authority", parsed.netloc.encode("utf8")), <34> (b":path", parsed.path.encode("utf8")), <35> ], <36> ) <37> conn.send_data(stream_id=stream_id, data=b"", end_stream=True) <38> for data, addr in quic.datagrams_to_send(now=time.time()): <39> sock.sendto(data, addr) <40> <41> # handle events <42> stream_ended = False <43> while not stream_</s>
===========below chunk 0=========== # module: examples.http3 def run(url: str) -> None: # offset: 1 data, addr = sock.recvfrom(2048) for event in conn.receive_datagram(data, addr, now=time.time()): print(event) if isinstance(event, (DataReceived, ResponseReceived)): stream_ended = event.stream_ended for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) ===========unchanged ref 0=========== at: aioquic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20, ] )) at: aioquic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20, ] ) at: aioquic.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.connection.QuicConnection connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_next_available_stream_id(is_unidirectional=False) -> int receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None ===========unchanged ref 1=========== at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection handle_events() -> List[Event] send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers) -> None at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: socket AF_INET: AddressFamily SOCK_DGRAM: SocketKind socket(family: int=..., type: int=..., proto: int=..., fileno: Optional[int]=...) gethostbyname(hostname: str) -> str at: socket.socket family: int type: int proto: int recvfrom(bufsize: int, flags: int=...) -> Tuple[bytes, _RetAddress] sendto(data: bytes, address: _Address) -> int sendto(data: bytes, flags: int, address: _Address) -> int at: time time() -> float at: urllib.parse urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes ===========changed ref 0=========== # module: aioquic.h3.connection class H3Connection: + def handle_events(self) -> List[Event]: + """ + Handle events from the QUIC connection and return HTTP events. + """ + http_events: List[Event] = [] + + # process QUIC events + event = self._quic.next_event() + while event is not None: + if isinstance(event, aioquic.events.StreamDataReceived): + http_events.extend( + self._receive_stream_data( + event.stream_id, event.data, event.end_stream + ) + ) + + event = self._quic.next_event() + + return http_events + ===========changed ref 1=========== # module: tests.test_h3 def h3_transfer(quic_sender, h3_receiver): transfer(quic_sender, h3_receiver._quic) + return h3_receiver.handle_events() - return h3_receiver._update() ===========changed ref 2=========== # module: aioquic.h3.connection class H3Connection: - def receive_datagram(self, data: bytes, addr: Any, now: float) -> List[Event]: - """ - Handle an incoming datagram and return events. - """ - self._quic.receive_datagram(data, addr, now=now) - return self._update() - ===========changed ref 3=========== # module: aioquic.h3.connection class H3Connection: + def _init_connection(self) -> None: + # send our settings + self._local_control_stream_id = self._create_uni_stream(StreamType.CONTROL) + self._quic.send_stream_data( + self._local_control_stream_id, + encode_frame( + FrameType.SETTINGS, + encode_settings( + { + Setting.QPACK_MAX_TABLE_CAPACITY: self._max_table_capacity, + Setting.QPACK_BLOCKED_STREAMS: self._blocked_streams, + } + ), + ), + ) + + # create encoder and decoder streams + self._local_encoder_stream_id = self._create_uni_stream( + StreamType.QPACK_ENCODER + ) + self._local_decoder_stream_id = self._create_uni_stream( + StreamType.QPACK_DECODER + ) +
aioquic.tls/KeyScheduleProxy.__init__
Modified
aiortc~aioquic
6bb8f015301ff3ca85daf49c2db710243a637d71
[tls] refactor KeyScheduleProxy
<0>:<add> self.__schedules = dict(map(lambda c: (c, KeySchedule(c)), cipher_suites)) <del> self.__items = list(map(KeySchedule, cipher_suites))
# module: aioquic.tls class KeyScheduleProxy: def __init__(self, cipher_suites: List[CipherSuite]): <0> self.__items = list(map(KeySchedule, cipher_suites)) <1>
===========unchanged ref 0=========== at: aioquic.tls CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) KeySchedule(cipher_suite: CipherSuite) at: typing List = _alias(list, 1, inst=False, name='List')
aioquic.tls/KeyScheduleProxy.extract
Modified
aiortc~aioquic
6bb8f015301ff3ca85daf49c2db710243a637d71
[tls] refactor KeyScheduleProxy
<0>:<add> for k in self.__schedules.values(): <del> for k in self.__items:
# module: aioquic.tls class KeyScheduleProxy: def extract(self, key_material: Optional[bytes] = None) -> None: <0> for k in self.__items: <1> k.extract(key_material) <2>
===========unchanged ref 0=========== at: aioquic.tls.KeySchedule extract(key_material: Optional[bytes]=None) -> None at: aioquic.tls.KeyScheduleProxy.__init__ self.__schedules = dict(map(lambda c: (c, KeySchedule(c)), cipher_suites)) ===========changed ref 0=========== # module: aioquic.tls class KeyScheduleProxy: def __init__(self, cipher_suites: List[CipherSuite]): + self.__schedules = dict(map(lambda c: (c, KeySchedule(c)), cipher_suites)) - self.__items = list(map(KeySchedule, cipher_suites))
aioquic.tls/KeyScheduleProxy.select
Modified
aiortc~aioquic
6bb8f015301ff3ca85daf49c2db710243a637d71
[tls] refactor KeyScheduleProxy
<0>:<del> for k in self.__items: <1>:<del> if k.cipher_suite == cipher_suite: <2>:<del> return k <3>:<del> raise KeyError <4>:<add> return self.__schedules[cipher_suite]
# module: aioquic.tls class KeyScheduleProxy: def select(self, cipher_suite: CipherSuite) -> KeySchedule: <0> for k in self.__items: <1> if k.cipher_suite == cipher_suite: <2> return k <3> raise KeyError <4>
===========unchanged ref 0=========== at: aioquic.tls CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) KeySchedule(cipher_suite: CipherSuite) at: aioquic.tls.KeyScheduleProxy.__init__ self.__schedules = dict(map(lambda c: (c, KeySchedule(c)), cipher_suites)) ===========changed ref 0=========== # module: aioquic.tls class KeyScheduleProxy: def extract(self, key_material: Optional[bytes] = None) -> None: + for k in self.__schedules.values(): - for k in self.__items: k.extract(key_material) ===========changed ref 1=========== # module: aioquic.tls class KeyScheduleProxy: def __init__(self, cipher_suites: List[CipherSuite]): + self.__schedules = dict(map(lambda c: (c, KeySchedule(c)), cipher_suites)) - self.__items = list(map(KeySchedule, cipher_suites))
aioquic.tls/KeyScheduleProxy.update_hash
Modified
aiortc~aioquic
6bb8f015301ff3ca85daf49c2db710243a637d71
[tls] refactor KeyScheduleProxy
<0>:<add> for k in self.__schedules.values(): <del> for k in self.__items:
# module: aioquic.tls class KeyScheduleProxy: def update_hash(self, data: bytes) -> None: <0> for k in self.__items: <1> k.update_hash(data) <2>
===========changed ref 0=========== # module: aioquic.tls class KeyScheduleProxy: def extract(self, key_material: Optional[bytes] = None) -> None: + for k in self.__schedules.values(): - for k in self.__items: k.extract(key_material) ===========changed ref 1=========== # module: aioquic.tls class KeyScheduleProxy: def select(self, cipher_suite: CipherSuite) -> KeySchedule: - for k in self.__items: - if k.cipher_suite == cipher_suite: - return k - raise KeyError + return self.__schedules[cipher_suite] ===========changed ref 2=========== # module: aioquic.tls class KeyScheduleProxy: def __init__(self, cipher_suites: List[CipherSuite]): + self.__schedules = dict(map(lambda c: (c, KeySchedule(c)), cipher_suites)) - self.__items = list(map(KeySchedule, cipher_suites))
aioquic.asyncio.server/serve
Modified
aiortc~aioquic
d0e97265c4150342955cf98fbf453b34391aabe5
[tests] explicitly close server after each test
<s>protocols: Optional[List[str]] = None, connection_handler: QuicConnectionHandler = None, idle_timeout: Optional[float] = None, stream_handler: QuicStreamHandler = None, secrets_log_file: Optional[TextIO] = None, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, + ) -> QuicServer: - ) -> None: <0> """ <1> Start a QUIC server at the given `host` and `port`. <2> <3> :func:`serve` requires a TLS certificate and private key, which can be <4> specified using the following arguments: <5> <6> * ``certificate`` is the server's TLS certificate. <7> See :func:`cryptography.x509.load_pem_x509_certificate`. <8> * ``private_key`` is the server's private key. <9> See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. <10> <11> :func:`serve` also accepts the following optional arguments: <12> <13> * ``connection_handler`` is a callback which is invoked whenever a <14> connection is created. It must be a a function accepting a single <15> argument: a :class:`~aioquic.asyncio.QuicConnectionProtocol`. <16> * ``secrets_log_file`` is a file-like object in which to log traffic <17> secrets. This is useful to analyze traffic captures with Wireshark. <18> * ``session_ticket_fetcher`` is a callback which is invoked by the TLS <19> engine when a session ticket is presented by the peer. It should return <20> the session ticket with the specified ID or `None` if it is not found. <21> * ``session_ticket_handler`` is a callback which is invoked by the TLS <22> engine when a new session ticket is issued. It should store the session <23> ticket for future lookup. <24> * ``stateless_retry`` specifies whether a stateless retry should be <25> performed prior to handling new connections. <26> </s>
===========below chunk 0=========== <s>[str]] = None, connection_handler: QuicConnectionHandler = None, idle_timeout: Optional[float] = None, stream_handler: QuicStreamHandler = None, secrets_log_file: Optional[TextIO] = None, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, + ) -> QuicServer: - ) -> None: # offset: 1 created. It must accept two arguments: a :class:`asyncio.StreamReader` and a :class:`asyncio.StreamWriter`. """ loop = asyncio.get_event_loop() configuration = QuicConfiguration( alpn_protocols=alpn_protocols, certificate=certificate, is_client=False, private_key=private_key, secrets_log_file=secrets_log_file, ) if idle_timeout is not None: configuration.idle_timeout = idle_timeout _, protocol = await loop.create_datagram_endpoint( lambda: QuicServer( configuration=configuration, connection_handler=connection_handler, session_ticket_fetcher=session_ticket_fetcher, session_ticket_handler=session_ticket_handler, stateless_retry=stateless_retry, stream_handler=stream_handler, ), local_addr=(host, port), ) ===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.asyncio.protocol QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None] at: aioquic.asyncio.server QuicConnectionHandler = Callable[[QuicConnectionProtocol], None] encode_address(addr: NetworkAddress) -> bytes QuicServer(*, configuration: QuicConfiguration, connection_handler: Optional[QuicConnectionHandler]=None, session_ticket_fetcher: Optional[SessionTicketFetcher]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stateless_retry: bool=False, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.asyncio.server.QuicServer._validate_retry_token retry_message = self._retry_key.decrypt( token, padding.OAEP( mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None ), ) at: aioquic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20, ] )) at: aioquic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None ===========unchanged ref 1=========== supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20, ] ) at: aioquic.tls SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] at: asyncio.events get_event_loop() -> AbstractEventLoop at: asyncio.events.AbstractEventLoop create_datagram_endpoint(protocol_factory: _ProtocolFactory, local_addr: Optional[Tuple[str, int]]=..., remote_addr: Optional[Tuple[str, int]]=..., *, family: int=..., proto: int=..., flags: int=..., reuse_address: Optional[bool]=..., reuse_port: Optional[bool]=..., allow_broadcast: Optional[bool]=..., sock: Optional[socket]=...) -> _TransProtPair at: typing List = _alias(list, 1, inst=False, name='List') TextIO() ===========changed ref 0=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): + def close(self): + for protocol in set(self._protocols.values()): + protocol.close() + self._protocols.clear() + self._transport.close() +
tests.test_asyncio/run_server
Modified
aiortc~aioquic
d0e97265c4150342955cf98fbf453b34391aabe5
[tests] explicitly close server after each test
<0>:<add> return await serve( <del> await serve(
# module: tests.test_asyncio def run_server(**kwargs): <0> await serve( <1> host="::", <2> port="4433", <3> certificate=SERVER_CERTIFICATE, <4> private_key=SERVER_PRIVATE_KEY, <5> stream_handler=handle_stream, <6> **kwargs <7> ) <8>
===========unchanged ref 0=========== at: aioquic.asyncio.server serve(host: str, port: int, *, certificate: Any, private_key: Any, alpn_protocols: Optional[List[str]]=None, connection_handler: QuicConnectionHandler=None, idle_timeout: Optional[float]=None, stream_handler: QuicStreamHandler=None, secrets_log_file: Optional[TextIO]=None, session_ticket_fetcher: Optional[SessionTicketFetcher]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stateless_retry: bool=False) -> QuicServer at: tests.test_asyncio handle_stream(reader, writer) at: tests.utils SERVER_CERTIFICATE = x509.load_pem_x509_certificate( load("ssl_cert.pem"), backend=default_backend() ) SERVER_PRIVATE_KEY = serialization.load_pem_private_key( load("ssl_key.pem"), password=None, backend=default_backend() ) ===========changed ref 0=========== <s>protocols: Optional[List[str]] = None, connection_handler: QuicConnectionHandler = None, idle_timeout: Optional[float] = None, stream_handler: QuicStreamHandler = None, secrets_log_file: Optional[TextIO] = None, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, + ) -> QuicServer: - ) -> None: """ Start a QUIC server at the given `host` and `port`. :func:`serve` requires a TLS certificate and private key, which can be specified using the following arguments: * ``certificate`` is the server's TLS certificate. See :func:`cryptography.x509.load_pem_x509_certificate`. * ``private_key`` is the server's private key. See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. :func:`serve` also accepts the following optional arguments: * ``connection_handler`` is a callback which is invoked whenever a connection is created. It must be a a function accepting a single argument: a :class:`~aioquic.asyncio.QuicConnectionProtocol`. * ``secrets_log_file`` is a file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. * ``session_ticket_fetcher`` is a callback which is invoked by the TLS engine when a session ticket is presented by the peer. It should return the session ticket with the specified ID or `None` if it is not found. * ``session_ticket_handler`` is a callback which is invoked by the TLS engine when a new session ticket is issued. It should store the session ticket for future lookup. * ``stateless_retry`` specifies whether a stateless retry should be performed prior to handling new connections. * ``stream_handler`` is a callback which is invoked whenever a stream is created. It must accept two arguments:</s> ===========changed ref 1=========== <s>[str]] = None, connection_handler: QuicConnectionHandler = None, idle_timeout: Optional[float] = None, stream_handler: QuicStreamHandler = None, secrets_log_file: Optional[TextIO] = None, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, + ) -> QuicServer: - ) -> None: # offset: 1 <s> connections. * ``stream_handler`` is a callback which is invoked whenever a stream is created. It must accept two arguments: a :class:`asyncio.StreamReader` and a :class:`asyncio.StreamWriter`. """ loop = asyncio.get_event_loop() configuration = QuicConfiguration( alpn_protocols=alpn_protocols, certificate=certificate, is_client=False, private_key=private_key, secrets_log_file=secrets_log_file, ) if idle_timeout is not None: configuration.idle_timeout = idle_timeout _, protocol = await loop.create_datagram_endpoint( lambda: QuicServer( configuration=configuration, connection_handler=connection_handler, session_ticket_fetcher=session_ticket_fetcher, session_ticket_handler=session_ticket_handler, stateless_retry=stateless_retry, stream_handler=stream_handler, ), local_addr=(host, port), ) + return cast(QuicServer, protocol) ===========changed ref 2=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): + def close(self): + for protocol in set(self._protocols.values()): + protocol.close() + self._protocols.clear() + self._transport.close() +
tests.test_asyncio/HighLevelTest.test_connect_and_serve
Modified
aiortc~aioquic
d0e97265c4150342955cf98fbf453b34391aabe5
[tests] explicitly close server after each test
<0>:<add> server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) <del> _, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) <2>:<add> server.close()
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): <0> _, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) <1> self.assertEqual(response, b"gnip") <2>
===========unchanged ref 0=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 1=========== at: tests.test_asyncio run_client(host, port=4433, request=b"ping", *, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None) at: tests.utils run(coro) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_asyncio def run_server(**kwargs): + return await serve( - await serve( host="::", port="4433", certificate=SERVER_CERTIFICATE, private_key=SERVER_PRIVATE_KEY, stream_handler=handle_stream, **kwargs ) ===========changed ref 1=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): + def close(self): + for protocol in set(self._protocols.values()): + protocol.close() + self._protocols.clear() + self._transport.close() + ===========changed ref 2=========== <s>protocols: Optional[List[str]] = None, connection_handler: QuicConnectionHandler = None, idle_timeout: Optional[float] = None, stream_handler: QuicStreamHandler = None, secrets_log_file: Optional[TextIO] = None, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, + ) -> QuicServer: - ) -> None: """ Start a QUIC server at the given `host` and `port`. :func:`serve` requires a TLS certificate and private key, which can be specified using the following arguments: * ``certificate`` is the server's TLS certificate. See :func:`cryptography.x509.load_pem_x509_certificate`. * ``private_key`` is the server's private key. See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. :func:`serve` also accepts the following optional arguments: * ``connection_handler`` is a callback which is invoked whenever a connection is created. It must be a a function accepting a single argument: a :class:`~aioquic.asyncio.QuicConnectionProtocol`. * ``secrets_log_file`` is a file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. * ``session_ticket_fetcher`` is a callback which is invoked by the TLS engine when a session ticket is presented by the peer. It should return the session ticket with the specified ID or `None` if it is not found. * ``session_ticket_handler`` is a callback which is invoked by the TLS engine when a new session ticket is issued. It should store the session ticket for future lookup. * ``stateless_retry`` specifies whether a stateless retry should be performed prior to handling new connections. * ``stream_handler`` is a callback which is invoked whenever a stream is created. It must accept two arguments:</s> ===========changed ref 3=========== <s>[str]] = None, connection_handler: QuicConnectionHandler = None, idle_timeout: Optional[float] = None, stream_handler: QuicStreamHandler = None, secrets_log_file: Optional[TextIO] = None, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, + ) -> QuicServer: - ) -> None: # offset: 1 <s> connections. * ``stream_handler`` is a callback which is invoked whenever a stream is created. It must accept two arguments: a :class:`asyncio.StreamReader` and a :class:`asyncio.StreamWriter`. """ loop = asyncio.get_event_loop() configuration = QuicConfiguration( alpn_protocols=alpn_protocols, certificate=certificate, is_client=False, private_key=private_key, secrets_log_file=secrets_log_file, ) if idle_timeout is not None: configuration.idle_timeout = idle_timeout _, protocol = await loop.create_datagram_endpoint( lambda: QuicServer( configuration=configuration, connection_handler=connection_handler, session_ticket_fetcher=session_ticket_fetcher, session_ticket_handler=session_ticket_handler, stateless_retry=stateless_retry, stream_handler=stream_handler, ), local_addr=(host, port), ) + return cast(QuicServer, protocol)
tests.test_asyncio/HighLevelTest.test_connect_and_serve_large
Modified
aiortc~aioquic
d0e97265c4150342955cf98fbf453b34391aabe5
[tests] explicitly close server after each test
<4>:<add> server, response = run( <del> _, response = run( <8>:<add> server.close()
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_large(self): <0> """ <1> Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA. <2> """ <3> data = b"Z" * 2097152 <4> _, response = run( <5> asyncio.gather(run_server(), run_client("127.0.0.1", request=data)) <6> ) <7> self.assertEqual(response, data) <8>
===========unchanged ref 0=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 1=========== at: tests.test_asyncio run_client(host, port=4433, request=b"ping", *, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None) at: tests.utils run(coro) ===========changed ref 0=========== # module: tests.test_asyncio def run_server(**kwargs): + return await serve( - await serve( host="::", port="4433", certificate=SERVER_CERTIFICATE, private_key=SERVER_PRIVATE_KEY, stream_handler=handle_stream, **kwargs ) ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): + server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) - _, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 2=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): + def close(self): + for protocol in set(self._protocols.values()): + protocol.close() + self._protocols.clear() + self._transport.close() + ===========changed ref 3=========== <s>protocols: Optional[List[str]] = None, connection_handler: QuicConnectionHandler = None, idle_timeout: Optional[float] = None, stream_handler: QuicStreamHandler = None, secrets_log_file: Optional[TextIO] = None, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, + ) -> QuicServer: - ) -> None: """ Start a QUIC server at the given `host` and `port`. :func:`serve` requires a TLS certificate and private key, which can be specified using the following arguments: * ``certificate`` is the server's TLS certificate. See :func:`cryptography.x509.load_pem_x509_certificate`. * ``private_key`` is the server's private key. See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. :func:`serve` also accepts the following optional arguments: * ``connection_handler`` is a callback which is invoked whenever a connection is created. It must be a a function accepting a single argument: a :class:`~aioquic.asyncio.QuicConnectionProtocol`. * ``secrets_log_file`` is a file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. * ``session_ticket_fetcher`` is a callback which is invoked by the TLS engine when a session ticket is presented by the peer. It should return the session ticket with the specified ID or `None` if it is not found. * ``session_ticket_handler`` is a callback which is invoked by the TLS engine when a new session ticket is issued. It should store the session ticket for future lookup. * ``stateless_retry`` specifies whether a stateless retry should be performed prior to handling new connections. * ``stream_handler`` is a callback which is invoked whenever a stream is created. It must accept two arguments:</s> ===========changed ref 4=========== <s>[str]] = None, connection_handler: QuicConnectionHandler = None, idle_timeout: Optional[float] = None, stream_handler: QuicStreamHandler = None, secrets_log_file: Optional[TextIO] = None, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, + ) -> QuicServer: - ) -> None: # offset: 1 <s> connections. * ``stream_handler`` is a callback which is invoked whenever a stream is created. It must accept two arguments: a :class:`asyncio.StreamReader` and a :class:`asyncio.StreamWriter`. """ loop = asyncio.get_event_loop() configuration = QuicConfiguration( alpn_protocols=alpn_protocols, certificate=certificate, is_client=False, private_key=private_key, secrets_log_file=secrets_log_file, ) if idle_timeout is not None: configuration.idle_timeout = idle_timeout _, protocol = await loop.create_datagram_endpoint( lambda: QuicServer( configuration=configuration, connection_handler=connection_handler, session_ticket_fetcher=session_ticket_fetcher, session_ticket_handler=session_ticket_handler, stateless_retry=stateless_retry, stream_handler=stream_handler, ), local_addr=(host, port), ) + return cast(QuicServer, protocol)
tests.test_asyncio/HighLevelTest.test_connect_and_serve_writelines
Modified
aiortc~aioquic
d0e97265c4150342955cf98fbf453b34391aabe5
[tests] explicitly close server after each test
<10>:<add> server, response = run( <del> _, response = run( <14>:<add> server.close()
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_writelines(self): <0> async def run_client_writelines(host, port=4433, **kwargs): <1> async with connect(host, port, **kwargs) as client: <2> reader, writer = await client.create_stream() <3> assert writer.can_write_eof() is True <4> <5> writer.writelines([b"01234567", b"89012345"]) <6> writer.write_eof() <7> <8> return await reader.read() <9> <10> _, response = run( <11> asyncio.gather(run_server(), run_client_writelines("127.0.0.1")) <12> ) <13> self.assertEqual(response, b"5432109876543210") <14>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(*args, **kwds) connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] at: aioquic.asyncio.protocol.QuicConnectionProtocol create_stream(is_unidirectional: bool=False) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter] at: asyncio.streams.StreamWriter writelines(data: Iterable[bytes]) -> None can_write_eof() -> bool ===========unchanged ref 1=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 2=========== at: tests.test_asyncio run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_large server, response = run( asyncio.gather(run_server(), run_client("127.0.0.1", request=data)) ) at: tests.utils run(coro) ===========changed ref 0=========== # module: tests.test_asyncio def run_server(**kwargs): + return await serve( - await serve( host="::", port="4433", certificate=SERVER_CERTIFICATE, private_key=SERVER_PRIVATE_KEY, stream_handler=handle_stream, **kwargs ) ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): + server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) - _, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_large(self): """ Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA. """ data = b"Z" * 2097152 + server, response = run( - _, response = run( asyncio.gather(run_server(), run_client("127.0.0.1", request=data)) ) self.assertEqual(response, data) + server.close() ===========changed ref 3=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): + def close(self): + for protocol in set(self._protocols.values()): + protocol.close() + self._protocols.clear() + self._transport.close() + ===========changed ref 4=========== <s>protocols: Optional[List[str]] = None, connection_handler: QuicConnectionHandler = None, idle_timeout: Optional[float] = None, stream_handler: QuicStreamHandler = None, secrets_log_file: Optional[TextIO] = None, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, + ) -> QuicServer: - ) -> None: """ Start a QUIC server at the given `host` and `port`. :func:`serve` requires a TLS certificate and private key, which can be specified using the following arguments: * ``certificate`` is the server's TLS certificate. See :func:`cryptography.x509.load_pem_x509_certificate`. * ``private_key`` is the server's private key. See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. :func:`serve` also accepts the following optional arguments: * ``connection_handler`` is a callback which is invoked whenever a connection is created. It must be a a function accepting a single argument: a :class:`~aioquic.asyncio.QuicConnectionProtocol`. * ``secrets_log_file`` is a file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. * ``session_ticket_fetcher`` is a callback which is invoked by the TLS engine when a session ticket is presented by the peer. It should return the session ticket with the specified ID or `None` if it is not found. * ``session_ticket_handler`` is a callback which is invoked by the TLS engine when a new session ticket is issued. It should store the session ticket for future lookup. * ``stateless_retry`` specifies whether a stateless retry should be performed prior to handling new connections. * ``stream_handler`` is a callback which is invoked whenever a stream is created. It must accept two arguments:</s>
tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_connection_handler
Modified
aiortc~aioquic
d0e97265c4150342955cf98fbf453b34391aabe5
[tests] explicitly close server after each test
<6>:<add> server, response = run( <del> _, response = run( <14>:<add> server.close()
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_connection_handler(self): <0> server_conn = None <1> <2> def connection_handler(conn): <3> nonlocal server_conn <4> server_conn = conn <5> <6> _, response = run( <7> asyncio.gather( <8> run_server(connection_handler=connection_handler), <9> run_client("127.0.0.1"), <10> ) <11> ) <12> self.assertEqual(response, b"gnip") <13> self.assertIsNotNone(server_conn) <14>
===========unchanged ref 0=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 1=========== at: tests.test_asyncio run_client(host, port=4433, request=b"ping", *, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_writelines server, response = run( asyncio.gather(run_server(), run_client_writelines("127.0.0.1")) ) server, response = run( asyncio.gather(run_server(), run_client_writelines("127.0.0.1")) ) at: tests.utils run(coro) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_asyncio def run_server(**kwargs): + return await serve( - await serve( host="::", port="4433", certificate=SERVER_CERTIFICATE, private_key=SERVER_PRIVATE_KEY, stream_handler=handle_stream, **kwargs ) ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): + server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) - _, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_large(self): """ Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA. """ data = b"Z" * 2097152 + server, response = run( - _, response = run( asyncio.gather(run_server(), run_client("127.0.0.1", request=data)) ) self.assertEqual(response, data) + server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_writelines(self): async def run_client_writelines(host, port=4433, **kwargs): async with connect(host, port, **kwargs) as client: reader, writer = await client.create_stream() assert writer.can_write_eof() is True writer.writelines([b"01234567", b"89012345"]) writer.write_eof() return await reader.read() + server, response = run( - _, response = run( asyncio.gather(run_server(), run_client_writelines("127.0.0.1")) ) self.assertEqual(response, b"5432109876543210") + server.close() ===========changed ref 4=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): + def close(self): + for protocol in set(self._protocols.values()): + protocol.close() + self._protocols.clear() + self._transport.close() + ===========changed ref 5=========== <s>protocols: Optional[List[str]] = None, connection_handler: QuicConnectionHandler = None, idle_timeout: Optional[float] = None, stream_handler: QuicStreamHandler = None, secrets_log_file: Optional[TextIO] = None, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, + ) -> QuicServer: - ) -> None: """ Start a QUIC server at the given `host` and `port`. :func:`serve` requires a TLS certificate and private key, which can be specified using the following arguments: * ``certificate`` is the server's TLS certificate. See :func:`cryptography.x509.load_pem_x509_certificate`. * ``private_key`` is the server's private key. See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. :func:`serve` also accepts the following optional arguments: * ``connection_handler`` is a callback which is invoked whenever a connection is created. It must be a a function accepting a single argument: a :class:`~aioquic.asyncio.QuicConnectionProtocol`. * ``secrets_log_file`` is a file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. * ``session_ticket_fetcher`` is a callback which is invoked by the TLS engine when a session ticket is presented by the peer. It should return the session ticket with the specified ID or `None` if it is not found. * ``session_ticket_handler`` is a callback which is invoked by the TLS engine when a new session ticket is issued. It should store the session ticket for future lookup. * ``stateless_retry`` specifies whether a stateless retry should be performed prior to handling new connections. * ``stream_handler`` is a callback which is invoked whenever a stream is created. It must accept two arguments:</s>
tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_packet_loss
Modified
aiortc~aioquic
d0e97265c4150342955cf98fbf453b34391aabe5
[tests] explicitly close server after each test
<5>:<add> server, response = run( <del> _, response = run( <12>:<add> server.close()
# module: tests.test_asyncio class HighLevelTest(TestCase): @patch("socket.socket.sendto", new_callable=lambda: sendto_with_loss) def test_connect_and_serve_with_packet_loss(self, mock_sendto): <0> """ <1> This test ensures handshake success and stream data is successfully sent <2> and received in the presence of packet loss (randomized 25% in each direction). <3> """ <4> data = b"Z" * 65536 <5> _, response = run( <6> asyncio.gather( <7> run_server(idle_timeout=300.0, stateless_retry=True), <8> run_client("127.0.0.1", idle_timeout=300.0, request=data), <9> ) <10> ) <11> self.assertEqual(response, data) <12>
===========unchanged ref 0=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 1=========== at: tests.test_asyncio sendto_with_loss(self, data, addr=None) run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_connection_handler server_conn = None server, response = run( asyncio.gather( run_server(connection_handler=connection_handler), run_client("127.0.0.1"), ) ) server, response = run( asyncio.gather( run_server(connection_handler=connection_handler), run_client("127.0.0.1"), ) ) at: tests.utils run(coro) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertIsNotNone(obj: Any, msg: Any=...) -> None at: unittest.mock _patcher(target: Any, new: _T, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[_T] _patcher(target: Any, *, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[Union[MagicMock, AsyncMock]] ===========changed ref 0=========== # module: tests.test_asyncio def run_server(**kwargs): + return await serve( - await serve( host="::", port="4433", certificate=SERVER_CERTIFICATE, private_key=SERVER_PRIVATE_KEY, stream_handler=handle_stream, **kwargs ) ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_connection_handler(self): server_conn = None def connection_handler(conn): nonlocal server_conn server_conn = conn + server, response = run( - _, response = run( asyncio.gather( run_server(connection_handler=connection_handler), run_client("127.0.0.1"), ) ) self.assertEqual(response, b"gnip") self.assertIsNotNone(server_conn) + server.close() ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): + server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) - _, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_large(self): """ Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA. """ data = b"Z" * 2097152 + server, response = run( - _, response = run( asyncio.gather(run_server(), run_client("127.0.0.1", request=data)) ) self.assertEqual(response, data) + server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_writelines(self): async def run_client_writelines(host, port=4433, **kwargs): async with connect(host, port, **kwargs) as client: reader, writer = await client.create_stream() assert writer.can_write_eof() is True writer.writelines([b"01234567", b"89012345"]) writer.write_eof() return await reader.read() + server, response = run( - _, response = run( asyncio.gather(run_server(), run_client_writelines("127.0.0.1")) ) self.assertEqual(response, b"5432109876543210") + server.close() ===========changed ref 5=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): + def close(self): + for protocol in set(self._protocols.values()): + protocol.close() + self._protocols.clear() + self._transport.close() +
tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_session_ticket
Modified
aiortc~aioquic
d0e97265c4150342955cf98fbf453b34391aabe5
[tests] explicitly close server after each test
<8>:<add> server, response = run( <del> _, response = run( <15>:<add> server.close() <19>:<add> server, response = run( <del> _, response = run( <26>:<add> server.close()
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_session_ticket(self): <0> client_ticket = None <1> store = SessionTicketStore() <2> <3> def save_ticket(t): <4> nonlocal client_ticket <5> client_ticket = t <6> <7> # first request <8> _, response = run( <9> asyncio.gather( <10> run_server(session_ticket_handler=store.add), <11> run_client("127.0.0.1", session_ticket_handler=save_ticket), <12> ) <13> ) <14> self.assertEqual(response, b"gnip") <15> <16> self.assertIsNotNone(client_ticket) <17> <18> # second request <19> _, response = run( <20> asyncio.gather( <21> run_server(session_ticket_fetcher=store.pop), <22> run_client("127.0.0.1", session_ticket=client_ticket), <23> ) <24> ) <25> self.assertEqual(response, b"gnip") <26>
===========unchanged ref 0=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 1=========== at: tests.test_asyncio SessionTicketStore() run_client(host, port=4433, request=b"ping", *, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_packet_loss data = b"Z" * 65536 server, response = run( asyncio.gather( run_server(idle_timeout=300.0, stateless_retry=True), run_client("127.0.0.1", idle_timeout=300.0, request=data), ) ) server, response = run( asyncio.gather( run_server(idle_timeout=300.0, stateless_retry=True), run_client("127.0.0.1", idle_timeout=300.0, request=data), ) ) at: tests.test_asyncio.SessionTicketStore add(ticket) at: tests.utils run(coro) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertIsNotNone(obj: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_asyncio def run_server(**kwargs): + return await serve( - await serve( host="::", port="4433", certificate=SERVER_CERTIFICATE, private_key=SERVER_PRIVATE_KEY, stream_handler=handle_stream, **kwargs ) ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_connection_handler(self): server_conn = None def connection_handler(conn): nonlocal server_conn server_conn = conn + server, response = run( - _, response = run( asyncio.gather( run_server(connection_handler=connection_handler), run_client("127.0.0.1"), ) ) self.assertEqual(response, b"gnip") self.assertIsNotNone(server_conn) + server.close() ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): + server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) - _, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("socket.socket.sendto", new_callable=lambda: sendto_with_loss) def test_connect_and_serve_with_packet_loss(self, mock_sendto): """ This test ensures handshake success and stream data is successfully sent and received in the presence of packet loss (randomized 25% in each direction). """ data = b"Z" * 65536 + server, response = run( - _, response = run( asyncio.gather( run_server(idle_timeout=300.0, stateless_retry=True), run_client("127.0.0.1", idle_timeout=300.0, request=data), ) ) self.assertEqual(response, data) + server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_large(self): """ Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA. """ data = b"Z" * 2097152 + server, response = run( - _, response = run( asyncio.gather(run_server(), run_client("127.0.0.1", request=data)) ) self.assertEqual(response, data) + server.close() ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_writelines(self): async def run_client_writelines(host, port=4433, **kwargs): async with connect(host, port, **kwargs) as client: reader, writer = await client.create_stream() assert writer.can_write_eof() is True writer.writelines([b"01234567", b"89012345"]) writer.write_eof() return await reader.read() + server, response = run( - _, response = run( asyncio.gather(run_server(), run_client_writelines("127.0.0.1")) ) self.assertEqual(response, b"5432109876543210") + server.close() ===========changed ref 6=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): + def close(self): + for protocol in set(self._protocols.values()): + protocol.close() + self._protocols.clear() + self._transport.close() +
tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_sni
Modified
aiortc~aioquic
d0e97265c4150342955cf98fbf453b34391aabe5
[tests] explicitly close server after each test
<0>:<add> server, response = run(asyncio.gather(run_server(), run_client("localhost"))) <del> _, response = run(asyncio.gather(run_server(), run_client("localhost"))) <2>:<add> server.close()
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_sni(self): <0> _, response = run(asyncio.gather(run_server(), run_client("localhost"))) <1> self.assertEqual(response, b"gnip") <2>
===========unchanged ref 0=========== at: tests.test_asyncio run_client(host, port=4433, request=b"ping", *, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_session_ticket client_ticket = None store = SessionTicketStore() at: tests.test_asyncio.SessionTicketStore pop(label) ===========changed ref 0=========== # module: tests.test_asyncio def run_server(**kwargs): + return await serve( - await serve( host="::", port="4433", certificate=SERVER_CERTIFICATE, private_key=SERVER_PRIVATE_KEY, stream_handler=handle_stream, **kwargs ) ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_connection_handler(self): server_conn = None def connection_handler(conn): nonlocal server_conn server_conn = conn + server, response = run( - _, response = run( asyncio.gather( run_server(connection_handler=connection_handler), run_client("127.0.0.1"), ) ) self.assertEqual(response, b"gnip") self.assertIsNotNone(server_conn) + server.close() ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): + server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) - _, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("socket.socket.sendto", new_callable=lambda: sendto_with_loss) def test_connect_and_serve_with_packet_loss(self, mock_sendto): """ This test ensures handshake success and stream data is successfully sent and received in the presence of packet loss (randomized 25% in each direction). """ data = b"Z" * 65536 + server, response = run( - _, response = run( asyncio.gather( run_server(idle_timeout=300.0, stateless_retry=True), run_client("127.0.0.1", idle_timeout=300.0, request=data), ) ) self.assertEqual(response, data) + server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_large(self): """ Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA. """ data = b"Z" * 2097152 + server, response = run( - _, response = run( asyncio.gather(run_server(), run_client("127.0.0.1", request=data)) ) self.assertEqual(response, data) + server.close() ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_writelines(self): async def run_client_writelines(host, port=4433, **kwargs): async with connect(host, port, **kwargs) as client: reader, writer = await client.create_stream() assert writer.can_write_eof() is True writer.writelines([b"01234567", b"89012345"]) writer.write_eof() return await reader.read() + server, response = run( - _, response = run( asyncio.gather(run_server(), run_client_writelines("127.0.0.1")) ) self.assertEqual(response, b"5432109876543210") + server.close() ===========changed ref 6=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_session_ticket(self): client_ticket = None store = SessionTicketStore() def save_ticket(t): nonlocal client_ticket client_ticket = t # first request + server, response = run( - _, response = run( asyncio.gather( run_server(session_ticket_handler=store.add), run_client("127.0.0.1", session_ticket_handler=save_ticket), ) ) self.assertEqual(response, b"gnip") + server.close() self.assertIsNotNone(client_ticket) # second request + server, response = run( - _, response = run( asyncio.gather( run_server(session_ticket_fetcher=store.pop), run_client("127.0.0.1", session_ticket=client_ticket), ) ) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 7=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): + def close(self): + for protocol in set(self._protocols.values()): + protocol.close() + self._protocols.clear() + self._transport.close() + ===========changed ref 8=========== <s>protocols: Optional[List[str]] = None, connection_handler: QuicConnectionHandler = None, idle_timeout: Optional[float] = None, stream_handler: QuicStreamHandler = None, secrets_log_file: Optional[TextIO] = None, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, + ) -> QuicServer: - ) -> None: """ Start a QUIC server at the given `host` and `port`. :func:`serve` requires a TLS certificate and private key, which can be specified using the following arguments: * ``certificate`` is the server's TLS certificate. See :func:`cryptography.x509.load_pem_x509_certificate`. * ``private_key`` is the server's private key. See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. :func:`serve` also accepts the following optional arguments: * ``connection_handler`` is a callback which is invoked whenever a connection is created. It must be a a function accepting a single argument: a :class:`~aioquic.asyncio.QuicConnectionProtocol`. * ``secrets_log_file`` is a file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. * ``session_ticket_fetcher`` is a callback which is invoked by the TLS engine when a session ticket is presented by the peer. It should return the session ticket with the specified ID or `None` if it is not found. * ``session_ticket_handler`` is a callback which is invoked by the TLS engine when a new session ticket is issued. It should store the session ticket for future lookup. * ``stateless_retry`` specifies whether a stateless retry should be performed prior to handling new connections. * ``stream_handler`` is a callback which is invoked whenever a stream is created. It must accept two arguments:</s>
tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_stateless_retry
Modified
aiortc~aioquic
d0e97265c4150342955cf98fbf453b34391aabe5
[tests] explicitly close server after each test
<0>:<add> server, response = run( <del> _, response = run( <4>:<add> server.close()
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_stateless_retry(self): <0> _, response = run( <1> asyncio.gather(run_server(stateless_retry=True), run_client("127.0.0.1")) <2> ) <3> self.assertEqual(response, b"gnip") <4>
===========unchanged ref 0=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 1=========== at: tests.test_asyncio run_client(host, port=4433, request=b"ping", *, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_session_ticket server, response = run( asyncio.gather( run_server(session_ticket_handler=store.add), run_client("127.0.0.1", session_ticket_handler=save_ticket), ) ) server, response = run( asyncio.gather( run_server(session_ticket_fetcher=store.pop), run_client("127.0.0.1", session_ticket=client_ticket), ) ) server, response = run( asyncio.gather( run_server(session_ticket_handler=store.add), run_client("127.0.0.1", session_ticket_handler=save_ticket), ) ) server, response = run( asyncio.gather( run_server(session_ticket_fetcher=store.pop), run_client("127.0.0.1", session_ticket=client_ticket), ) ) at: tests.utils run(coro) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_asyncio def run_server(**kwargs): + return await serve( - await serve( host="::", port="4433", certificate=SERVER_CERTIFICATE, private_key=SERVER_PRIVATE_KEY, stream_handler=handle_stream, **kwargs ) ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_sni(self): + server, response = run(asyncio.gather(run_server(), run_client("localhost"))) - _, response = run(asyncio.gather(run_server(), run_client("localhost"))) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_connection_handler(self): server_conn = None def connection_handler(conn): nonlocal server_conn server_conn = conn + server, response = run( - _, response = run( asyncio.gather( run_server(connection_handler=connection_handler), run_client("127.0.0.1"), ) ) self.assertEqual(response, b"gnip") self.assertIsNotNone(server_conn) + server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): + server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) - _, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("socket.socket.sendto", new_callable=lambda: sendto_with_loss) def test_connect_and_serve_with_packet_loss(self, mock_sendto): """ This test ensures handshake success and stream data is successfully sent and received in the presence of packet loss (randomized 25% in each direction). """ data = b"Z" * 65536 + server, response = run( - _, response = run( asyncio.gather( run_server(idle_timeout=300.0, stateless_retry=True), run_client("127.0.0.1", idle_timeout=300.0, request=data), ) ) self.assertEqual(response, data) + server.close() ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_large(self): """ Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA. """ data = b"Z" * 2097152 + server, response = run( - _, response = run( asyncio.gather(run_server(), run_client("127.0.0.1", request=data)) ) self.assertEqual(response, data) + server.close() ===========changed ref 6=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_writelines(self): async def run_client_writelines(host, port=4433, **kwargs): async with connect(host, port, **kwargs) as client: reader, writer = await client.create_stream() assert writer.can_write_eof() is True writer.writelines([b"01234567", b"89012345"]) writer.write_eof() return await reader.read() + server, response = run( - _, response = run( asyncio.gather(run_server(), run_client_writelines("127.0.0.1")) ) self.assertEqual(response, b"5432109876543210") + server.close()
tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_stateless_retry_bad
Modified
aiortc~aioquic
d0e97265c4150342955cf98fbf453b34391aabe5
[tests] explicitly close server after each test
<2>:<add> server = run(run_server(stateless_retry=True)) <3>:<del> run( <4>:<del> asyncio.gather( <5>:<del> run_server(stateless_retry=True), <6>:<add> run(run_client("127.0.0.1", idle_timeout=4.0)) <del> run_client("127.0.0.1", idle_timeout=4.0), <7>:<del> ) <8>:<del> ) <9>:<add> server.close()
# module: tests.test_asyncio class HighLevelTest(TestCase): @patch("aioquic.asyncio.server.QuicServer._validate_retry_token") def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate): <0> mock_validate.side_effect = ValueError("Decryption failed.") <1> <2> with self.assertRaises(ConnectionError): <3> run( <4> asyncio.gather( <5> run_server(stateless_retry=True), <6> run_client("127.0.0.1", idle_timeout=4.0), <7> ) <8> ) <9>
===========unchanged ref 0=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 1=========== at: tests.test_asyncio run_client(host, port=4433, request=b"ping", *, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_sni server, response = run(asyncio.gather(run_server(), run_client("localhost"))) at: tests.utils run(coro) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None at: unittest.mock _patcher(target: Any, new: _T, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[_T] _patcher(target: Any, *, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[Union[MagicMock, AsyncMock]] ===========changed ref 0=========== # module: tests.test_asyncio def run_server(**kwargs): + return await serve( - await serve( host="::", port="4433", certificate=SERVER_CERTIFICATE, private_key=SERVER_PRIVATE_KEY, stream_handler=handle_stream, **kwargs ) ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_stateless_retry(self): + server, response = run( - _, response = run( asyncio.gather(run_server(stateless_retry=True), run_client("127.0.0.1")) ) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_sni(self): + server, response = run(asyncio.gather(run_server(), run_client("localhost"))) - _, response = run(asyncio.gather(run_server(), run_client("localhost"))) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_connection_handler(self): server_conn = None def connection_handler(conn): nonlocal server_conn server_conn = conn + server, response = run( - _, response = run( asyncio.gather( run_server(connection_handler=connection_handler), run_client("127.0.0.1"), ) ) self.assertEqual(response, b"gnip") self.assertIsNotNone(server_conn) + server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): + server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) - _, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("socket.socket.sendto", new_callable=lambda: sendto_with_loss) def test_connect_and_serve_with_packet_loss(self, mock_sendto): """ This test ensures handshake success and stream data is successfully sent and received in the presence of packet loss (randomized 25% in each direction). """ data = b"Z" * 65536 + server, response = run( - _, response = run( asyncio.gather( run_server(idle_timeout=300.0, stateless_retry=True), run_client("127.0.0.1", idle_timeout=300.0, request=data), ) ) self.assertEqual(response, data) + server.close() ===========changed ref 6=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_large(self): """ Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA. """ data = b"Z" * 2097152 + server, response = run( - _, response = run( asyncio.gather(run_server(), run_client("127.0.0.1", request=data)) ) self.assertEqual(response, data) + server.close()
tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_version_negotiation
Modified
aiortc~aioquic
d0e97265c4150342955cf98fbf453b34391aabe5
[tests] explicitly close server after each test
<0>:<add> server, response = run( <del> _, response = run( <6>:<add> server.close()
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_version_negotiation(self): <0> _, response = run( <1> asyncio.gather( <2> run_server(), run_client("127.0.0.1", protocol_version=0x1A2A3A4A) <3> ) <4> ) <5> self.assertEqual(response, b"gnip") <6>
===========unchanged ref 0=========== at: tests.test_asyncio run_client(host, port=4433, request=b"ping", *, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None) at: tests.utils run(coro) at: unittest.case.TestCase assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None ===========changed ref 0=========== # module: tests.test_asyncio def run_server(**kwargs): + return await serve( - await serve( host="::", port="4433", certificate=SERVER_CERTIFICATE, private_key=SERVER_PRIVATE_KEY, stream_handler=handle_stream, **kwargs ) ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_stateless_retry(self): + server, response = run( - _, response = run( asyncio.gather(run_server(stateless_retry=True), run_client("127.0.0.1")) ) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_sni(self): + server, response = run(asyncio.gather(run_server(), run_client("localhost"))) - _, response = run(asyncio.gather(run_server(), run_client("localhost"))) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("aioquic.asyncio.server.QuicServer._validate_retry_token") def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate): mock_validate.side_effect = ValueError("Decryption failed.") + server = run(run_server(stateless_retry=True)) with self.assertRaises(ConnectionError): - run( - asyncio.gather( - run_server(stateless_retry=True), + run(run_client("127.0.0.1", idle_timeout=4.0)) - run_client("127.0.0.1", idle_timeout=4.0), - ) - ) + server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_connection_handler(self): server_conn = None def connection_handler(conn): nonlocal server_conn server_conn = conn + server, response = run( - _, response = run( asyncio.gather( run_server(connection_handler=connection_handler), run_client("127.0.0.1"), ) ) self.assertEqual(response, b"gnip") self.assertIsNotNone(server_conn) + server.close() ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): + server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) - _, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 6=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("socket.socket.sendto", new_callable=lambda: sendto_with_loss) def test_connect_and_serve_with_packet_loss(self, mock_sendto): """ This test ensures handshake success and stream data is successfully sent and received in the presence of packet loss (randomized 25% in each direction). """ data = b"Z" * 65536 + server, response = run( - _, response = run( asyncio.gather( run_server(idle_timeout=300.0, stateless_retry=True), run_client("127.0.0.1", idle_timeout=300.0, request=data), ) ) self.assertEqual(response, data) + server.close() ===========changed ref 7=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_large(self): """ Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA. """ data = b"Z" * 2097152 + server, response = run( - _, response = run( asyncio.gather(run_server(), run_client("127.0.0.1", request=data)) ) self.assertEqual(response, data) + server.close() ===========changed ref 8=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_writelines(self): async def run_client_writelines(host, port=4433, **kwargs): async with connect(host, port, **kwargs) as client: reader, writer = await client.create_stream() assert writer.can_write_eof() is True writer.writelines([b"01234567", b"89012345"]) writer.write_eof() return await reader.read() + server, response = run( - _, response = run( asyncio.gather(run_server(), run_client_writelines("127.0.0.1")) ) self.assertEqual(response, b"5432109876543210") + server.close() ===========changed ref 9=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_session_ticket(self): client_ticket = None store = SessionTicketStore() def save_ticket(t): nonlocal client_ticket client_ticket = t # first request + server, response = run( - _, response = run( asyncio.gather( run_server(session_ticket_handler=store.add), run_client("127.0.0.1", session_ticket_handler=save_ticket), ) ) self.assertEqual(response, b"gnip") + server.close() self.assertIsNotNone(client_ticket) # second request + server, response = run( - _, response = run( asyncio.gather( run_server(session_ticket_fetcher=store.pop), run_client("127.0.0.1", session_ticket=client_ticket), ) ) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 10=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): + def close(self): + for protocol in set(self._protocols.values()): + protocol.close() + self._protocols.clear() + self._transport.close() +
tests.test_asyncio/HighLevelTest.test_change_connection_id
Modified
aiortc~aioquic
d0e97265c4150342955cf98fbf453b34391aabe5
[tests] explicitly close server after each test
<6>:<add> server, _ = run( <del> run( <11>:<add> server.close()
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_change_connection_id(self): <0> async def run_client_key_update(host, **kwargs): <1> async with connect(host, 4433, **kwargs) as client: <2> await client.ping() <3> client.change_connection_id() <4> await client.ping() <5> <6> run( <7> asyncio.gather( <8> run_server(stateless_retry=False), run_client_key_update("127.0.0.1") <9> ) <10> ) <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, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] at: aioquic.asyncio.protocol.QuicConnectionProtocol change_connection_id() -> None ping() -> None at: tests.test_asyncio run_client(host, port=4433, request=b"ping", *, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_version_negotiation server, response = run( asyncio.gather( run_server(), run_client("127.0.0.1", protocol_version=0x1A2A3A4A) ) ) server, response = run( asyncio.gather( run_server(), run_client("127.0.0.1", protocol_version=0x1A2A3A4A) ) ) at: tests.utils run(coro) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========unchanged ref 1=========== assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None ===========changed ref 0=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_version_negotiation(self): + server, response = run( - _, response = run( asyncio.gather( run_server(), run_client("127.0.0.1", protocol_version=0x1A2A3A4A) ) ) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_stateless_retry(self): + server, response = run( - _, response = run( asyncio.gather(run_server(stateless_retry=True), run_client("127.0.0.1")) ) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_sni(self): + server, response = run(asyncio.gather(run_server(), run_client("localhost"))) - _, response = run(asyncio.gather(run_server(), run_client("localhost"))) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("aioquic.asyncio.server.QuicServer._validate_retry_token") def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate): mock_validate.side_effect = ValueError("Decryption failed.") + server = run(run_server(stateless_retry=True)) with self.assertRaises(ConnectionError): - run( - asyncio.gather( - run_server(stateless_retry=True), + run(run_client("127.0.0.1", idle_timeout=4.0)) - run_client("127.0.0.1", idle_timeout=4.0), - ) - ) + server.close() ===========changed ref 4=========== # module: tests.test_asyncio def run_server(**kwargs): + return await serve( - await serve( host="::", port="4433", certificate=SERVER_CERTIFICATE, private_key=SERVER_PRIVATE_KEY, stream_handler=handle_stream, **kwargs ) ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_connection_handler(self): server_conn = None def connection_handler(conn): nonlocal server_conn server_conn = conn + server, response = run( - _, response = run( asyncio.gather( run_server(connection_handler=connection_handler), run_client("127.0.0.1"), ) ) self.assertEqual(response, b"gnip") self.assertIsNotNone(server_conn) + server.close() ===========changed ref 6=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): + server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) - _, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 7=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("socket.socket.sendto", new_callable=lambda: sendto_with_loss) def test_connect_and_serve_with_packet_loss(self, mock_sendto): """ This test ensures handshake success and stream data is successfully sent and received in the presence of packet loss (randomized 25% in each direction). """ data = b"Z" * 65536 + server, response = run( - _, response = run( asyncio.gather( run_server(idle_timeout=300.0, stateless_retry=True), run_client("127.0.0.1", idle_timeout=300.0, request=data), ) ) self.assertEqual(response, data) + server.close() ===========changed ref 8=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_large(self): """ Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA. """ data = b"Z" * 2097152 + server, response = run( - _, response = run( asyncio.gather(run_server(), run_client("127.0.0.1", request=data)) ) self.assertEqual(response, data) + server.close() ===========changed ref 9=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_writelines(self): async def run_client_writelines(host, port=4433, **kwargs): async with connect(host, port, **kwargs) as client: reader, writer = await client.create_stream() assert writer.can_write_eof() is True writer.writelines([b"01234567", b"89012345"]) writer.write_eof() return await reader.read() + server, response = run( - _, response = run( asyncio.gather(run_server(), run_client_writelines("127.0.0.1")) ) self.assertEqual(response, b"5432109876543210") + server.close()
tests.test_asyncio/HighLevelTest.test_key_update
Modified
aiortc~aioquic
d0e97265c4150342955cf98fbf453b34391aabe5
[tests] explicitly close server after each test
<6>:<add> server, _ = run( <del> run( <11>:<add> server.close()
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_key_update(self): <0> async def run_client_key_update(host, **kwargs): <1> async with connect(host, 4433, **kwargs) as client: <2> await client.ping() <3> client.request_key_update() <4> await client.ping() <5> <6> run( <7> asyncio.gather( <8> run_server(stateless_retry=False), run_client_key_update("127.0.0.1") <9> ) <10> ) <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, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] at: aioquic.asyncio.protocol.QuicConnectionProtocol ping() -> None ===========unchanged ref 1=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 2=========== at: tests.test_asyncio run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None) at: tests.test_asyncio.HighLevelTest.test_change_connection_id run_client_key_update(host, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds) at: tests.utils run(coro) ===========changed ref 0=========== # module: tests.test_asyncio def run_server(**kwargs): + return await serve( - await serve( host="::", port="4433", certificate=SERVER_CERTIFICATE, private_key=SERVER_PRIVATE_KEY, stream_handler=handle_stream, **kwargs ) ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_version_negotiation(self): + server, response = run( - _, response = run( asyncio.gather( run_server(), run_client("127.0.0.1", protocol_version=0x1A2A3A4A) ) ) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_stateless_retry(self): + server, response = run( - _, response = run( asyncio.gather(run_server(stateless_retry=True), run_client("127.0.0.1")) ) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_sni(self): + server, response = run(asyncio.gather(run_server(), run_client("localhost"))) - _, response = run(asyncio.gather(run_server(), run_client("localhost"))) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_change_connection_id(self): async def run_client_key_update(host, **kwargs): async with connect(host, 4433, **kwargs) as client: await client.ping() client.change_connection_id() await client.ping() + server, _ = run( - run( asyncio.gather( run_server(stateless_retry=False), run_client_key_update("127.0.0.1") ) ) + server.close() ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("aioquic.asyncio.server.QuicServer._validate_retry_token") def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate): mock_validate.side_effect = ValueError("Decryption failed.") + server = run(run_server(stateless_retry=True)) with self.assertRaises(ConnectionError): - run( - asyncio.gather( - run_server(stateless_retry=True), + run(run_client("127.0.0.1", idle_timeout=4.0)) - run_client("127.0.0.1", idle_timeout=4.0), - ) - ) + server.close() ===========changed ref 6=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_connection_handler(self): server_conn = None def connection_handler(conn): nonlocal server_conn server_conn = conn + server, response = run( - _, response = run( asyncio.gather( run_server(connection_handler=connection_handler), run_client("127.0.0.1"), ) ) self.assertEqual(response, b"gnip") self.assertIsNotNone(server_conn) + server.close() ===========changed ref 7=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): + server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) - _, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) self.assertEqual(response, b"gnip") + server.close()
tests.test_asyncio/HighLevelTest.test_ping
Modified
aiortc~aioquic
d0e97265c4150342955cf98fbf453b34391aabe5
[tests] explicitly close server after each test
<5>:<add> server, _ = run( <del> run( <10>:<add> server.close()
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_ping(self): <0> async def run_client_ping(host, **kwargs): <1> async with connect(host, 4433, **kwargs) as client: <2> await client.ping() <3> await client.ping() <4> <5> run( <6> asyncio.gather( <7> run_server(stateless_retry=False), run_client_ping("127.0.0.1") <8> ) <9> ) <10>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol ping() -> None ===========unchanged ref 1=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 2=========== at: tests.test_asyncio run_server(*, alpn_protocols: Optional[List[str]]=None, secrets_log_file: Optional[TextIO]=None) at: tests.test_asyncio.HighLevelTest.test_key_update run_client_key_update(host, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None, **kwds) at: tests.utils run(coro) ===========changed ref 0=========== # module: tests.test_asyncio def run_server(**kwargs): + return await serve( - await serve( host="::", port="4433", certificate=SERVER_CERTIFICATE, private_key=SERVER_PRIVATE_KEY, stream_handler=handle_stream, **kwargs ) ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_version_negotiation(self): + server, response = run( - _, response = run( asyncio.gather( run_server(), run_client("127.0.0.1", protocol_version=0x1A2A3A4A) ) ) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_key_update(self): async def run_client_key_update(host, **kwargs): async with connect(host, 4433, **kwargs) as client: await client.ping() client.request_key_update() await client.ping() + server, _ = run( - run( asyncio.gather( run_server(stateless_retry=False), run_client_key_update("127.0.0.1") ) ) + server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_stateless_retry(self): + server, response = run( - _, response = run( asyncio.gather(run_server(stateless_retry=True), run_client("127.0.0.1")) ) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_sni(self): + server, response = run(asyncio.gather(run_server(), run_client("localhost"))) - _, response = run(asyncio.gather(run_server(), run_client("localhost"))) self.assertEqual(response, b"gnip") + server.close() ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_change_connection_id(self): async def run_client_key_update(host, **kwargs): async with connect(host, 4433, **kwargs) as client: await client.ping() client.change_connection_id() await client.ping() + server, _ = run( - run( asyncio.gather( run_server(stateless_retry=False), run_client_key_update("127.0.0.1") ) ) + server.close() ===========changed ref 6=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("aioquic.asyncio.server.QuicServer._validate_retry_token") def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate): mock_validate.side_effect = ValueError("Decryption failed.") + server = run(run_server(stateless_retry=True)) with self.assertRaises(ConnectionError): - run( - asyncio.gather( - run_server(stateless_retry=True), + run(run_client("127.0.0.1", idle_timeout=4.0)) - run_client("127.0.0.1", idle_timeout=4.0), - ) - ) + server.close() ===========changed ref 7=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_connection_handler(self): server_conn = None def connection_handler(conn): nonlocal server_conn server_conn = conn + server, response = run( - _, response = run( asyncio.gather( run_server(connection_handler=connection_handler), run_client("127.0.0.1"), ) ) self.assertEqual(response, b"gnip") self.assertIsNotNone(server_conn) + server.close() ===========changed ref 8=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): + server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) - _, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) self.assertEqual(response, b"gnip") + server.close()
aioquic.asyncio.server/QuicServer.__init__
Modified
aiortc~aioquic
1554b7e67d62b9da9debf4b8e66015fb9c7e9386
[server] move stateless retry token handling
<15>:<del> self._retry_key = rsa.generate_private_key( <16>:<del> public_exponent=65537, key_size=1024, backend=default_backend() <17>:<del> ) <18>:<add> self._retry = QuicRetryTokenHandler() <19>:<add> self._retry = None <del> self._retry_key = None
<s>ic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def __init__( self, *, configuration: QuicConfiguration, connection_handler: Optional[QuicConnectionHandler] = None, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: <0> self._configuration = configuration <1> self._protocols: Dict[bytes, QuicConnectionProtocol] = {} <2> self._loop = asyncio.get_event_loop() <3> self._session_ticket_fetcher = session_ticket_fetcher <4> self._session_ticket_handler = session_ticket_handler <5> self._transport: Optional[asyncio.DatagramTransport] = None <6> <7> if connection_handler is not None: <8> self._connection_handler = connection_handler <9> else: <10> self._connection_handler = lambda c: None <11> <12> self._stream_handler = stream_handler <13> <14> if stateless_retry: <15> self._retry_key = rsa.generate_private_key( <16> public_exponent=65537, key_size=1024, backend=default_backend() <17> ) <18> else: <19> self._retry_key = None <20>
===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.asyncio.protocol QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None] QuicConnectionProtocol(connection: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.asyncio.protocol.QuicConnectionProtocol close() -> None at: aioquic.retry QuicRetryTokenHandler() at: asyncio.events get_event_loop() -> AbstractEventLoop at: asyncio.protocols.BaseProtocol __slots__ = () connection_made(self, transport: transports.BaseTransport) -> None at: asyncio.transports BaseTransport(extra: Optional[Mapping[Any, Any]]=...) DatagramTransport(extra: Optional[Mapping[Any, Any]]=...) at: asyncio.transports.BaseTransport __slots__ = ('_extra',) close() -> None at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: aioquic.asyncio.server - def encode_address(addr: NetworkAddress) -> bytes: - return ipaddress.ip_address(addr[0]).packed + bytes([addr[1] >> 8, addr[1] & 0xFF]) - ===========changed ref 1=========== + # module: aioquic.retry + + ===========changed ref 2=========== + # module: aioquic.retry + def encode_address(addr: NetworkAddress) -> bytes: + return ipaddress.ip_address(addr[0]).packed + bytes([addr[1] >> 8, addr[1] & 0xFF]) + ===========changed ref 3=========== + # module: aioquic.retry + class QuicRetryTokenHandler: + def __init__(self) -> None: + self._key = rsa.generate_private_key( + public_exponent=65537, key_size=1024, backend=default_backend() + ) + ===========changed ref 4=========== + # module: aioquic.retry + class QuicRetryTokenHandler: + def create_token(self, addr: NetworkAddress, destination_cid: bytes) -> bytes: + retry_message = encode_address(addr) + b"|" + destination_cid + return self._key.public_key().encrypt( + retry_message, + padding.OAEP( + mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None + ), + ) + ===========changed ref 5=========== + # module: aioquic.retry + class QuicRetryTokenHandler: + def validate_token(self, addr: NetworkAddress, token: bytes) -> bytes: + retry_message = self._key.decrypt( + token, + padding.OAEP( + mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None + ), + ) + encoded_addr, original_connection_id = retry_message.split(b"|", maxsplit=1) + if encoded_addr != encode_address(addr): + raise ValueError("Remote address does not match.") + return original_connection_id +
aioquic.asyncio.server/QuicServer.datagram_received
Modified
aiortc~aioquic
1554b7e67d62b9da9debf4b8e66015fb9c7e9386
[server] move stateless retry token handling
<23>:<add> if self._retry is not None: <del> if self._retry_key is not None: <32>:<add> retry_token=self._retry.create_token( <del> retry_token=self._create_retry_token( <42>:<add> original_connection_id = self._retry.validate_token( <del> original_connection_id = self._validate_retry_token(
# module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: <0> data = cast(bytes, data) <1> buf = Buffer(data=data) <2> header = pull_quic_header(buf, host_cid_length=8) <3> <4> # version negotiation <5> if ( <6> header.version is not None <7> and header.version not in self._configuration.supported_versions <8> ): <9> self._transport.sendto( <10> encode_quic_version_negotiation( <11> source_cid=header.destination_cid, <12> destination_cid=header.source_cid, <13> supported_versions=self._configuration.supported_versions, <14> ), <15> addr, <16> ) <17> return <18> <19> protocol = self._protocols.get(header.destination_cid, None) <20> original_connection_id: Optional[bytes] = None <21> if protocol is None and header.packet_type == PACKET_TYPE_INITIAL: <22> # stateless retry <23> if self._retry_key is not None: <24> if not header.token: <25> # create a retry token <26> self._transport.sendto( <27> encode_quic_retry( <28> version=header.version, <29> source_cid=os.urandom(8), <30> destination_cid=header.source_cid, <31> original_destination_cid=header.destination_cid, <32> retry_token=self._create_retry_token( <33> addr, header.destination_cid <34> ), <35> ), <36> addr, <37> ) <38> return <39> else: <40> # validate retry token <41> try: <42> original_connection_id = self._validate_retry_token( <43> addr, header.token <44> ) <45> except ValueError: <46> return <47> <48> # create new connection <49> connection = QuicConnection( <50> </s>
===========below chunk 0=========== # module: aioquic.asyncio.server class QuicServer(asyncio.DatagramProtocol): def datagram_received(self, data: Union[bytes, Text], addr: NetworkAddress) -> None: # offset: 1 original_connection_id=original_connection_id, session_ticket_fetcher=self._session_ticket_fetcher, session_ticket_handler=self._session_ticket_handler, ) protocol = QuicConnectionProtocol( connection, stream_handler=self._stream_handler ) protocol._connection_id_issued_handler = partial( self._connection_id_issued, protocol=protocol ) protocol._connection_id_retired_handler = partial( self._connection_id_retired, protocol=protocol ) self._protocols[header.destination_cid] = protocol protocol.connection_made(self._transport) self._protocols[connection.host_cid] = protocol self._connection_handler(protocol) if protocol is not None: protocol.datagram_received(data, addr) ===========unchanged ref 0=========== at: aioquic.asyncio.protocol QuicConnectionProtocol(connection: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.asyncio.protocol.QuicConnectionProtocol connection_made(transport: asyncio.BaseTransport) -> None datagram_received(data: Union[bytes, Text], addr: NetworkAddress) -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None at: aioquic.asyncio.server.QuicServer.__init__ self._configuration = configuration self._protocols: Dict[bytes, QuicConnectionProtocol] = {} self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler self._transport: Optional[asyncio.DatagramTransport] = None self._connection_handler = connection_handler self._connection_handler = lambda c: None self._stream_handler = stream_handler self._retry = QuicRetryTokenHandler() self._retry = None at: aioquic.asyncio.server.QuicServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: aioquic.asyncio.server.QuicServer.datagram_received data = cast(bytes, data) header = pull_quic_header(buf, host_cid_length=8) at: aioquic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None ===========unchanged ref 1=========== session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20, ] ) at: aioquic.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.connection.QuicConnection.__init__ self.host_cid = self._host_cids[0].cid at: aioquic.connection.QuicConnection.receive_datagram self.host_cid = context.host_cid at: aioquic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 encode_quic_retry(version: int, source_cid: bytes, destination_cid: bytes, original_destination_cid: bytes, retry_token: bytes) -> bytes encode_quic_version_negotiation(source_cid: bytes, destination_cid: bytes, supported_versions: List[QuicProtocolVersion]) -> bytes at: aioquic.packet.QuicHeader is_long_header: bool version: Optional[int] packet_type: int destination_cid: bytes source_cid: bytes original_destination_cid: bytes = b"" token: bytes = b"" rest_length: int = 0 at: aioquic.retry.QuicRetryTokenHandler create_token(addr: NetworkAddress, destination_cid: bytes) -> bytes validate_token(addr: NetworkAddress, token: bytes) -> bytes at: asyncio.transports.DatagramTransport __slots__ = () sendto(data: Any, addr: Optional[_Address]=...) -> None ===========unchanged ref 2=========== at: functools partial(func: Callable[..., _T], *args: Any, **kwargs: Any) partial(func, *args, **keywords, /) -> function with partial application() at: os urandom(size: int, /) -> bytes at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co] ===========changed ref 0=========== + # module: aioquic.retry + class QuicRetryTokenHandler: + def create_token(self, addr: NetworkAddress, destination_cid: bytes) -> bytes: + retry_message = encode_address(addr) + b"|" + destination_cid + return self._key.public_key().encrypt( + retry_message, + padding.OAEP( + mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None + ), + ) + ===========changed ref 1=========== + # module: aioquic.retry + class QuicRetryTokenHandler: + def validate_token(self, addr: NetworkAddress, token: bytes) -> bytes: + retry_message = self._key.decrypt( + token, + padding.OAEP( + mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None + ), + ) + encoded_addr, original_connection_id = retry_message.split(b"|", maxsplit=1) + if encoded_addr != encode_address(addr): + raise ValueError("Remote address does not match.") + return original_connection_id + ===========changed ref 2=========== # module: aioquic.asyncio.server - def encode_address(addr: NetworkAddress) -> bytes: - return ipaddress.ip_address(addr[0]).packed + bytes([addr[1] >> 8, addr[1] & 0xFF]) -
aioquic.h3.connection/H3Connection.handle_events
Modified
aiortc~aioquic
4e81cee943d038678d2941fc6ff9fb1f685207f2
[examples] add an HTTP/3 server example
<8>:<del> if isinstance(event, aioquic.events.StreamDataReceived): <9>:<del> http_events.extend( <10>:<del> self._receive_stream_data( <11>:<del> event.stream_id, event.data, event.end_stream <12>:<del> ) <13>:<del> ) <14>:<del> <15>:<add> http_events.extend(self.handle_event(event))
# module: aioquic.h3.connection class H3Connection: def handle_events(self) -> List[Event]: <0> """ <1> Handle events from the QUIC connection and return HTTP events. <2> """ <3> http_events: List[Event] = [] <4> <5> # process QUIC events <6> event = self._quic.next_event() <7> while event is not None: <8> if isinstance(event, aioquic.events.StreamDataReceived): <9> http_events.extend( <10> self._receive_stream_data( <11> event.stream_id, event.data, event.end_stream <12> ) <13> ) <14> <15> event = self._quic.next_event() <16> <17> return http_events <18>
===========unchanged ref 0=========== at: aioquic.events Event() StreamDataReceived(data: bytes, end_stream: bool, stream_id: int) at: aioquic.h3.connection.H3Connection _receive_stream_data(stream_id: int, data: bytes, stream_ended: bool) -> List[Event] at: aioquic.h3.events Event() at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.h3.connection class H3Connection: + def handle_event(self, event: aioquic.events.Event) -> List[Event]: + """ + Handle a QUIC event and return a list of HTTP events. + """ + http_events: List[Event] = [] + + if isinstance(event, aioquic.events.StreamDataReceived): + http_events.extend( + self._receive_stream_data(event.stream_id, event.data, event.end_stream) + ) + + return http_events +
examples.http3-client/run
Modified
aiortc~aioquic
d5ea72874a9ee815f9242f193a0432d31bb92873
[examples] add arguments for SSL log and session ticket to H3 client
<17>:<del> alpn_protocols=["h3-20"], <18>:<del> is_client=True, <19>:<del> secrets_log_file=open("/tmp/ssl.log", "w"), <20>:<del> server_name=server_name, <21>:<add> alpn_protocols=["h3-20"], is_client=True, server_name=server_name, **kwargs <add> ), <del> ) <22>:<add> session_ticket_handler=save_session_ticket,
# module: examples.http3-client + def run(url: str, **kwargs) -> None: - def run(url: str) -> None: <0> # parse URL <1> parsed = urlparse(url) <2> assert parsed.scheme == "https", "Only HTTPS URLs are supported." <3> if ":" in parsed.netloc: <4> server_name, port_str = parsed.netloc.split(":") <5> port = int(port_str) <6> else: <7> server_name = parsed.netloc <8> port = 443 <9> <10> # prepare socket <11> server_addr = (socket.gethostbyname(server_name), port) <12> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <13> <14> # prepare QUIC connection <15> quic = QuicConnection( <16> configuration=QuicConfiguration( <17> alpn_protocols=["h3-20"], <18> is_client=True, <19> secrets_log_file=open("/tmp/ssl.log", "w"), <20> server_name=server_name, <21> ) <22> ) <23> quic.connect(server_addr, now=time.time()) <24> <25> # send request <26> http = H3Connection(quic) <27> stream_id = quic.get_next_available_stream_id() <28> http.send_headers( <29> stream_id=stream_id, <30> headers=[ <31> (b":method", b"GET"), <32> (b":scheme", parsed.scheme.encode("utf8")), <33> (b":authority", parsed.netloc.encode("utf8")), <34> (b":path", parsed.path.encode("utf8")), <35> ], <36> ) <37> http.send_data(stream_id=stream_id, data=b"", end_stream=True) <38> for data, addr in quic.datagrams_to_send(now=time.time()): <39> sock.sendto(data, addr) <40> <41> </s>
===========below chunk 0=========== # module: examples.http3-client + def run(url: str, **kwargs) -> None: - def run(url: str) -> None: # offset: 1 stream_ended = False while not stream_ended: data, addr = sock.recvfrom(2048) quic.receive_datagram(data, addr, now=time.time()) for event in http.handle_events(): print(event) if isinstance(event, (DataReceived, ResponseReceived)): stream_ended = event.stream_ended for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) ===========unchanged ref 0=========== at: _pickle dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None) at: aioquic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20, ] )) at: aioquic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20, ] ) at: aioquic.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.connection.QuicConnection connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_next_available_stream_id(is_unidirectional=False) -> int ===========unchanged ref 1=========== 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: examples.http3-client logger = logging.getLogger("client") args = parser.parse_args() at: logging.Logger info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None at: pickle dump, dumps, load, loads = _dump, _dumps, _load, _loads at: socket AF_INET: AddressFamily SOCK_DGRAM: SocketKind socket(family: int=..., type: int=..., proto: int=..., fileno: Optional[int]=...) gethostbyname(hostname: str) -> str at: socket.socket family: int type: int proto: int sendto(data: bytes, address: _Address) -> int sendto(data: bytes, flags: int, address: _Address) -> int at: time time() -> float 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 + logger = logging.getLogger("client") - logger = logging.getLogger("http3")
aioquic.recovery/QuicPacketRecovery.detect_loss
Modified
aiortc~aioquic
1f5f5f510801ad377240a1508a6ef7f12fbda3da
[recovery] add QuicPacketRecovery.on_packet_lost
<11>:<del> lost_bytes = 0 <28>:<del> del space.sent_packets[packet.packet_number] <29>:<del> if packet.is_ack_eliciting: <30>:<del> space.ack_eliciting_in_flight -= 1 <31>:<del> if packet.is_crypto_packet: <32>:<del> space.crypto_packet_in_flight -= 1 <33>:<add> self.on_packet_lost(packet, space) <34>:<del> lost_bytes += packet.sent_bytes <37>:<del> # trigger callbacks <38>:<del> for handler, args in packet.delivery_handlers: <39>:<del> handler(QuicDeliveryState.LOST, *args) <40>:<add> if lost_largest_time is not None: <add> self.on_packets_lost(lost_largest_time, now=now) <41>:<del> if lost_bytes: <42>:<del> self.
# module: aioquic.recovery class QuicPacketRecovery: def detect_loss(self, space: QuicPacketSpace, now: float) -> None: <0> """ <1> Check whether any packets should be declared lost. <2> """ <3> loss_delay = K_TIME_THRESHOLD * ( <4> max(self._rtt_latest, self._rtt_smoothed) <5> if self._rtt_initialized <6> else K_INITIAL_RTT <7> ) <8> packet_threshold = space.largest_acked_packet - K_PACKET_THRESHOLD <9> time_threshold = now - loss_delay <10> <11> lost_bytes = 0 <12> lost_largest_time = None <13> lost_packets = [] <14> space.loss_time = None <15> for packet_number, packet in space.sent_packets.items(): <16> if packet_number > space.largest_acked_packet: <17> break <18> <19> if packet_number <= packet_threshold or packet.sent_time <= time_threshold: <20> lost_packets.append(packet) <21> else: <22> packet_loss_time = packet.sent_time + loss_delay <23> if space.loss_time is None or space.loss_time > packet_loss_time: <24> space.loss_time = packet_loss_time <25> <26> for packet in lost_packets: <27> # remove packet and update counters <28> del space.sent_packets[packet.packet_number] <29> if packet.is_ack_eliciting: <30> space.ack_eliciting_in_flight -= 1 <31> if packet.is_crypto_packet: <32> space.crypto_packet_in_flight -= 1 <33> if packet.in_flight: <34> lost_bytes += packet.sent_bytes <35> lost_largest_time = packet.sent_time <36> <37> # trigger callbacks <38> for handler, args in packet.delivery_handlers: <39> handler(QuicDeliveryState.LOST, *args) <40> <41> if lost_bytes: <42> self.</s>
===========below chunk 0=========== # module: aioquic.recovery class QuicPacketRecovery: def detect_loss(self, space: QuicPacketSpace, now: float) -> None: # offset: 1 ===========unchanged ref 0=========== at: aioquic.packet_builder.QuicSentPacket epoch: Epoch in_flight: bool is_ack_eliciting: bool is_crypto_packet: bool packet_number: int sent_time: Optional[float] = None sent_bytes: int = 0 delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field( default_factory=list ) at: aioquic.recovery K_PACKET_THRESHOLD = 3 K_INITIAL_RTT = 0.5 # seconds K_TIME_THRESHOLD = 9 / 8 QuicPacketSpace() at: aioquic.recovery.QuicPacketRecovery on_packet_expired(packet: QuicSentPacket) -> None on_packet_expired(self, packet: QuicSentPacket) -> None on_packet_lost(packet: QuicSentPacket, space: QuicPacketSpace) -> None on_packets_lost(lost_largest_time: float, now: float) -> None at: aioquic.recovery.QuicPacketRecovery.__init__ self.spaces: List[QuicPacketSpace] = [] self._rtt_initialized = False self._rtt_latest = 0.0 self._rtt_smoothed = 0.0 at: aioquic.recovery.QuicPacketRecovery.on_ack_received self._rtt_latest = max(latest_rtt, 0.001) self._rtt_latest -= ack_delay self._rtt_initialized = True self._rtt_smoothed = latest_rtt self._rtt_smoothed = ( 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest ) at: aioquic.recovery.QuicPacketSpace.__init__ self.ack_at: Optional[float] = None self.largest_acked_packet = 0 ===========unchanged ref 1=========== self.loss_time: Optional[float] = None self.sent_packets: Dict[int, QuicSentPacket] = {}
aioquic.recovery/QuicPacketRecovery.on_loss_detection_timeout
Modified
aiortc~aioquic
1f5f5f510801ad377240a1508a6ef7f12fbda3da
[recovery] add QuicPacketRecovery.on_packet_lost
<10>:<del> del space.sent_packets[packet_number] <11>:<del> space.ack_eliciting_in_flight -= 1 <12>:<del> space.crypto_packet_in_flight -= 1 <13>:<del> if packet.in_flight: <14>:<del> self.bytes_in_flight -= packet.sent_bytes <15>:<del> <16>:<del> # trigger callbacks <17>:<del> for handler, args in packet.delivery_handlers: <18>:<del> handler(QuicDeliveryState.LOST, *args) <19>:<add> self.on_packet_lost(packet, space)
# module: aioquic.recovery class QuicPacketRecovery: def on_loss_detection_timeout(self, now: float) -> None: <0> loss_space = self.get_earliest_loss_time() <1> if loss_space is not None: <2> self.detect_loss(loss_space, now=now) <3> elif sum(space.crypto_packet_in_flight for space in self.spaces): <4> # reschedule crypto packets <5> for space in self.spaces: <6> for packet_number, packet in list( <7> filter(lambda i: i[1].is_crypto_packet, space.sent_packets.items()) <8> ): <9> # remove packet and update counters <10> del space.sent_packets[packet_number] <11> space.ack_eliciting_in_flight -= 1 <12> space.crypto_packet_in_flight -= 1 <13> if packet.in_flight: <14> self.bytes_in_flight -= packet.sent_bytes <15> <16> # trigger callbacks <17> for handler, args in packet.delivery_handlers: <18> handler(QuicDeliveryState.LOST, *args) <19> self._crypto_count += 1 <20> else: <21> self._pto_count += 1 <22> self._send_probe() <23>
===========unchanged ref 0=========== at: aioquic.packet_builder QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field( default_factory=list )) at: aioquic.packet_builder.QuicSentPacket sent_time: Optional[float] = None sent_bytes: int = 0 at: aioquic.recovery K_MAX_DATAGRAM_SIZE = 1280 at: aioquic.recovery.QuicPacketRecovery on_packet_lost(packet: QuicSentPacket, space: QuicPacketSpace) -> None at: aioquic.recovery.QuicPacketRecovery.__init__ self._send_probe = send_probe self._crypto_count = 0 self._pto_count = 0 self.bytes_in_flight = 0 self.congestion_window = K_INITIAL_WINDOW self._congestion_recovery_start_time = 0.0 self._ssthresh = math.inf at: aioquic.recovery.QuicPacketRecovery.on_ack_received self._crypto_count = 0 self._pto_count = 0 at: aioquic.recovery.QuicPacketRecovery.on_packet_expired self.bytes_in_flight -= packet.sent_bytes at: aioquic.recovery.QuicPacketRecovery.on_packet_lost self.bytes_in_flight -= packet.sent_bytes at: aioquic.recovery.QuicPacketRecovery.on_packet_sent self.bytes_in_flight += packet.sent_bytes at: aioquic.recovery.QuicPacketRecovery.on_packets_lost self._congestion_recovery_start_time = now ===========unchanged ref 1=========== 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.recovery class QuicPacketRecovery: def detect_loss(self, space: QuicPacketSpace, now: float) -> None: """ Check whether any packets should be declared lost. """ loss_delay = K_TIME_THRESHOLD * ( max(self._rtt_latest, self._rtt_smoothed) if self._rtt_initialized else K_INITIAL_RTT ) packet_threshold = space.largest_acked_packet - K_PACKET_THRESHOLD time_threshold = now - loss_delay - lost_bytes = 0 lost_largest_time = None lost_packets = [] space.loss_time = None for packet_number, packet in space.sent_packets.items(): if packet_number > space.largest_acked_packet: break if packet_number <= packet_threshold or packet.sent_time <= time_threshold: lost_packets.append(packet) else: packet_loss_time = packet.sent_time + loss_delay if space.loss_time is None or space.loss_time > packet_loss_time: space.loss_time = packet_loss_time for packet in lost_packets: # remove packet and update counters - del space.sent_packets[packet.packet_number] - if packet.is_ack_eliciting: - space.ack_eliciting_in_flight -= 1 - if packet.is_crypto_packet: - space.crypto_packet_in_flight -= 1 + self.on_packet_lost(packet, space) if packet.in_flight: - lost_bytes += packet.sent_bytes lost_largest_time = packet.sent_time - # trigger callbacks - for handler, args in packet.delivery_handlers: - handler(QuicDeliveryState.LOST, *args) + if lost_largest_time is not None: + self.on_packets_lost(lost_</s> ===========changed ref 1=========== # module: aioquic.recovery class QuicPacketRecovery: def detect_loss(self, space: QuicPacketSpace, now: float) -> None: # offset: 1 <s>) + if lost_largest_time is not None: + self.on_packets_lost(lost_largest_time, now=now) - if lost_bytes: - self.on_packets_lost(lost_bytes, lost_largest_time, now=now) -
aioquic.recovery/QuicPacketRecovery.on_packets_lost
Modified
aiortc~aioquic
1f5f5f510801ad377240a1508a6ef7f12fbda3da
[recovery] add QuicPacketRecovery.on_packet_lost
<0>:<del> # remove lost packets from bytes in flight <1>:<del> self.bytes_in_flight -= lost_bytes <2>:<del>
# module: aioquic.recovery class QuicPacketRecovery: - def on_packets_lost( - self, lost_bytes: int, lost_largest_time: float, now: float - ) -> None: + def on_packets_lost(self, lost_largest_time: float, now: float) -> None: <0> # remove lost packets from bytes in flight <1> self.bytes_in_flight -= lost_bytes <2> <3> # start a new congestion event if packet was sent after the <4> # start of the previous congestion recovery period. <5> if lost_largest_time > self._congestion_recovery_start_time: <6> self._congestion_recovery_start_time = now <7> self.congestion_window = max( <8> int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW <9> ) <10> self._ssthresh = self.congestion_window <11>
===========unchanged ref 0=========== at: aioquic.recovery K_MINIMUM_WINDOW = 2 * K_MAX_DATAGRAM_SIZE K_LOSS_REDUCTION_FACTOR = 0.5 at: aioquic.recovery.QuicPacketRecovery.__init__ self.congestion_window = K_INITIAL_WINDOW self._congestion_recovery_start_time = 0.0 self._ssthresh = math.inf at: aioquic.recovery.QuicPacketRecovery.on_packet_acked self.congestion_window += ( K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window ) self.congestion_window += packet.sent_bytes ===========changed ref 0=========== # module: aioquic.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.is_crypto_packet: + space.crypto_packet_in_flight -= 1 + if packet.in_flight: + self.bytes_in_flight -= packet.sent_bytes + + # trigger callbacks + for handler, args in packet.delivery_handlers: + handler(QuicDeliveryState.LOST, *args) + ===========changed ref 1=========== # module: aioquic.recovery class QuicPacketRecovery: def on_loss_detection_timeout(self, now: float) -> None: loss_space = self.get_earliest_loss_time() if loss_space is not None: self.detect_loss(loss_space, now=now) elif sum(space.crypto_packet_in_flight for space in self.spaces): # reschedule crypto packets for space in self.spaces: for packet_number, packet in list( filter(lambda i: i[1].is_crypto_packet, space.sent_packets.items()) ): # remove packet and update counters - del space.sent_packets[packet_number] - space.ack_eliciting_in_flight -= 1 - space.crypto_packet_in_flight -= 1 - if packet.in_flight: - self.bytes_in_flight -= packet.sent_bytes - - # trigger callbacks - for handler, args in packet.delivery_handlers: - handler(QuicDeliveryState.LOST, *args) + self.on_packet_lost(packet, space) self._crypto_count += 1 else: self._pto_count += 1 self._send_probe() ===========changed ref 2=========== # module: aioquic.recovery class QuicPacketRecovery: def detect_loss(self, space: QuicPacketSpace, now: float) -> None: """ Check whether any packets should be declared lost. """ loss_delay = K_TIME_THRESHOLD * ( max(self._rtt_latest, self._rtt_smoothed) if self._rtt_initialized else K_INITIAL_RTT ) packet_threshold = space.largest_acked_packet - K_PACKET_THRESHOLD time_threshold = now - loss_delay - lost_bytes = 0 lost_largest_time = None lost_packets = [] space.loss_time = None for packet_number, packet in space.sent_packets.items(): if packet_number > space.largest_acked_packet: break if packet_number <= packet_threshold or packet.sent_time <= time_threshold: lost_packets.append(packet) else: packet_loss_time = packet.sent_time + loss_delay if space.loss_time is None or space.loss_time > packet_loss_time: space.loss_time = packet_loss_time for packet in lost_packets: # remove packet and update counters - del space.sent_packets[packet.packet_number] - if packet.is_ack_eliciting: - space.ack_eliciting_in_flight -= 1 - if packet.is_crypto_packet: - space.crypto_packet_in_flight -= 1 + self.on_packet_lost(packet, space) if packet.in_flight: - lost_bytes += packet.sent_bytes lost_largest_time = packet.sent_time - # trigger callbacks - for handler, args in packet.delivery_handlers: - handler(QuicDeliveryState.LOST, *args) + if lost_largest_time is not None: + self.on_packets_lost(lost_</s> ===========changed ref 3=========== # module: aioquic.recovery class QuicPacketRecovery: def detect_loss(self, space: QuicPacketSpace, now: float) -> None: # offset: 1 <s>) + if lost_largest_time is not None: + self.on_packets_lost(lost_largest_time, now=now) - if lost_bytes: - self.on_packets_lost(lost_bytes, lost_largest_time, now=now) -
aioquic.recovery/QuicPacketSpace.__init__
Modified
aiortc~aioquic
fc09c97d4543d7bc241308ff9cc9b5e88635a5eb
[recovery] merge crypto and pto timers
<7>:<del> self.crypto_packet_in_flight = 0
# module: aioquic.recovery class QuicPacketSpace: def __init__(self) -> None: <0> self.ack_at: Optional[float] = None <1> self.ack_queue = RangeSet() <2> self.expected_packet_number = 0 <3> self.largest_received_packet = 0 <4> <5> # sent packets and loss <6> self.ack_eliciting_in_flight = 0 <7> self.crypto_packet_in_flight = 0 <8> self.largest_acked_packet = 0 <9> self.loss_time: Optional[float] = None <10> self.sent_packets: Dict[int, QuicSentPacket] = {} <11>
===========unchanged ref 0=========== at: aioquic.packet_builder QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field( default_factory=list )) at: aioquic.rangeset RangeSet(ranges: Iterable[range]=[]) at: typing Dict = _alias(dict, 2, inst=False, name='Dict')
aioquic.recovery/QuicPacketRecovery.__init__
Modified
aiortc~aioquic
fc09c97d4543d7bc241308ff9cc9b5e88635a5eb
[recovery] merge crypto and pto timers
<8>:<del> self._crypto_count = 0 <16>:<del> self._time_of_last_sent_crypto_packet = 0.0
# module: aioquic.recovery class QuicPacketRecovery: def __init__(self, send_probe: Callable[[], None]) -> None: <0> self.ack_delay_exponent = 3 <1> self.max_ack_delay = 25 # ms <2> self.spaces: List[QuicPacketSpace] = [] <3> <4> # callbacks <5> self._send_probe = send_probe <6> <7> # loss detection <8> self._crypto_count = 0 <9> self._pto_count = 0 <10> self._rtt_initialized = False <11> self._rtt_latest = 0.0 <12> self._rtt_min = math.inf <13> self._rtt_smoothed = 0.0 <14> self._rtt_variance = 0.0 <15> self._time_of_last_sent_ack_eliciting_packet = 0.0 <16> self._time_of_last_sent_crypto_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 = math.inf <23>
===========unchanged ref 0=========== at: aioquic.recovery K_INITIAL_WINDOW = 10 * K_MAX_DATAGRAM_SIZE QuicPacketSpace() at: aioquic.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.recovery.QuicPacketRecovery.on_loss_detection_timeout self._pto_count += 1 at: aioquic.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.recovery.QuicPacketRecovery.on_packet_expired self.bytes_in_flight -= packet.sent_bytes at: aioquic.recovery.QuicPacketRecovery.on_packet_lost self.bytes_in_flight -= packet.sent_bytes at: aioquic.recovery.QuicPacketRecovery.on_packet_sent self._time_of_last_sent_ack_eliciting_packet = packet.sent_time self.bytes_in_flight += packet.sent_bytes ===========unchanged ref 1=========== at: aioquic.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 List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.recovery class QuicPacketSpace: def __init__(self) -> None: self.ack_at: Optional[float] = None self.ack_queue = RangeSet() self.expected_packet_number = 0 self.largest_received_packet = 0 # sent packets and loss self.ack_eliciting_in_flight = 0 - self.crypto_packet_in_flight = 0 self.largest_acked_packet = 0 self.loss_time: Optional[float] = None self.sent_packets: Dict[int, QuicSentPacket] = {}
aioquic.recovery/QuicPacketRecovery.discard_space
Modified
aiortc~aioquic
fc09c97d4543d7bc241308ff9cc9b5e88635a5eb
[recovery] merge crypto and pto timers
<9>:<del> space.crypto_packet_in_flight = 0
# module: aioquic.recovery class QuicPacketRecovery: def discard_space(self, space: QuicPacketSpace) -> None: <0> assert space in self.spaces <1> <2> for packet in space.sent_packets.values(): <3> if packet.in_flight: <4> self.on_packet_expired(packet) <5> space.sent_packets.clear() <6> <7> space.ack_at = None <8> space.ack_eliciting_in_flight = 0 <9> space.crypto_packet_in_flight = 0 <10> space.loss_time = None <11>
===========unchanged ref 0=========== at: aioquic.packet_builder.QuicSentPacket epoch: Epoch in_flight: bool is_ack_eliciting: bool is_crypto_packet: bool packet_number: int sent_time: Optional[float] = None sent_bytes: int = 0 delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field( default_factory=list ) at: aioquic.recovery QuicPacketSpace() at: aioquic.recovery.QuicPacketRecovery on_packet_expired(packet: QuicSentPacket) -> None at: aioquic.recovery.QuicPacketRecovery.__init__ self.spaces: List[QuicPacketSpace] = [] at: aioquic.recovery.QuicPacketSpace.__init__ self.ack_at: Optional[float] = None self.ack_eliciting_in_flight = 0 self.loss_time: Optional[float] = None self.sent_packets: Dict[int, QuicSentPacket] = {} ===========changed ref 0=========== # module: aioquic.recovery class QuicPacketSpace: def __init__(self) -> None: self.ack_at: Optional[float] = None self.ack_queue = RangeSet() self.expected_packet_number = 0 self.largest_received_packet = 0 # sent packets and loss self.ack_eliciting_in_flight = 0 - self.crypto_packet_in_flight = 0 self.largest_acked_packet = 0 self.loss_time: Optional[float] = None self.sent_packets: Dict[int, QuicSentPacket] = {} ===========changed ref 1=========== # module: aioquic.recovery class QuicPacketRecovery: def __init__(self, send_probe: Callable[[], None]) -> None: self.ack_delay_exponent = 3 self.max_ack_delay = 25 # ms self.spaces: List[QuicPacketSpace] = [] # callbacks self._send_probe = send_probe # loss detection - self._crypto_count = 0 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 - self._time_of_last_sent_crypto_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 = math.inf
aioquic.recovery/QuicPacketRecovery.get_loss_detection_time
Modified
aiortc~aioquic
fc09c97d4543d7bc241308ff9cc9b5e88635a5eb
[recovery] merge crypto and pto timers
<5>:<del> # crypto timer <6>:<del> if sum(space.crypto_packet_in_flight for space in self.spaces): <7>:<del> timeout = max( <8>:<del> 2 * (self._rtt_smoothed if self._rtt_initialized else K_INITIAL_RTT), <9>:<del> K_GRANULARITY, <10>:<del> ) * (2 ** self._crypto_count) <11>:<del> return self._time_of_last_sent_crypto_packet + timeout <12>:<del> <15>:<add> if not self._rtt_initialized: <add> timeout = 2 * K_INITIAL_RTT * (2 ** self._pto_count) <add> else: <add> timeout = ( <del> timeout = ( <16>:<add> self._rtt_smoothed <del> self._rtt_smoothed <17>:<add> + max(4 * self._rtt_variance, K_GRANULARITY) <del> + max(4 * self._rtt_variance, K_GRANULARITY) <18>:<add> + self.max_ack_delay / 1000 <del> + self.max_ack_delay / 1000 <19>:<add> ) * (2 ** self._pto_count) <del> ) * (2 ** self._pto_count)
# module: aioquic.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> # crypto timer <6> if sum(space.crypto_packet_in_flight for space in self.spaces): <7> timeout = max( <8> 2 * (self._rtt_smoothed if self._rtt_initialized else K_INITIAL_RTT), <9> K_GRANULARITY, <10> ) * (2 ** self._crypto_count) <11> return self._time_of_last_sent_crypto_packet + timeout <12> <13> # packet timer <14> if sum(space.ack_eliciting_in_flight for space in self.spaces): <15> timeout = ( <16> self._rtt_smoothed <17> + max(4 * self._rtt_variance, K_GRANULARITY) <18> + self.max_ack_delay / 1000 <19> ) * (2 ** self._pto_count) <20> return self._time_of_last_sent_ack_eliciting_packet + timeout <21> <22> return None <23>
===========unchanged ref 0=========== at: aioquic.recovery K_INITIAL_RTT = 0.5 # seconds K_GRANULARITY = 0.001 # seconds at: aioquic.recovery.QuicPacketRecovery.__init__ 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.recovery.QuicPacketRecovery.get_loss_detection_time loss_space = self.get_earliest_loss_time() at: aioquic.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.recovery.QuicPacketRecovery.on_loss_detection_timeout self._pto_count += 1 at: aioquic.recovery.QuicPacketRecovery.on_packet_sent self._time_of_last_sent_ack_eliciting_packet = packet.sent_time at: aioquic.recovery.QuicPacketSpace.__init__ self.ack_eliciting_in_flight = 0 self.loss_time: Optional[float] = None ===========changed ref 0=========== # module: aioquic.recovery class QuicPacketRecovery: def discard_space(self, space: QuicPacketSpace) -> None: assert space in self.spaces for packet in space.sent_packets.values(): if packet.in_flight: self.on_packet_expired(packet) space.sent_packets.clear() space.ack_at = None space.ack_eliciting_in_flight = 0 - space.crypto_packet_in_flight = 0 space.loss_time = None ===========changed ref 1=========== # module: aioquic.recovery class QuicPacketSpace: def __init__(self) -> None: self.ack_at: Optional[float] = None self.ack_queue = RangeSet() self.expected_packet_number = 0 self.largest_received_packet = 0 # sent packets and loss self.ack_eliciting_in_flight = 0 - self.crypto_packet_in_flight = 0 self.largest_acked_packet = 0 self.loss_time: Optional[float] = None self.sent_packets: Dict[int, QuicSentPacket] = {} ===========changed ref 2=========== # module: aioquic.recovery class QuicPacketRecovery: def __init__(self, send_probe: Callable[[], None]) -> None: self.ack_delay_exponent = 3 self.max_ack_delay = 25 # ms self.spaces: List[QuicPacketSpace] = [] # callbacks self._send_probe = send_probe # loss detection - self._crypto_count = 0 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 - self._time_of_last_sent_crypto_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 = math.inf
aioquic.recovery/QuicPacketRecovery.on_ack_received
Modified
aiortc~aioquic
fc09c97d4543d7bc241308ff9cc9b5e88635a5eb
[recovery] merge crypto and pto timers
<20>:<del> if packet.is_crypto_packet: <21>:<del> space.crypto_packet_in_flight -= 1
# module: aioquic.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.is_crypto_packet: <21> space.crypto_packet_in_flight -= 1 <22> if packet.in_flight: <23> self.on_packet_acked(packet) <24> largest_newly_acked = packet_number <25> largest_sent_time = packet.sent_time <26> <27> # trigger callbacks <28> for handler, args in packet.delivery_handlers: <29> handler(QuicDeliveryState.ACKED, *args) <30> <31> # nothing to do if there are no newly acked packets <32> if largest_newly_acked is None: <33> return <34> <35> if largest_acked == largest_newly_acked and is_ack_eliciting: <36> latest_rtt = now - largest_sent_time <37> <38> # decode ACK delay into seconds <39> </s>
===========below chunk 0=========== # module: aioquic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay_encoded: int, now: float, ) -> None: # offset: 1 (ack_delay_encoded << self.ack_delay_exponent) / 1000000, 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 ) self.detect_loss(space, now=now) self._crypto_count = 0 self._pto_count = 0 ===========unchanged ref 0=========== at: aioquic.packet_builder QuicDeliveryState() at: aioquic.packet_builder.QuicSentPacket in_flight: bool is_ack_eliciting: bool sent_time: Optional[float] = None delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field( default_factory=list ) at: aioquic.rangeset.RangeSet bounds() -> range at: aioquic.recovery.QuicPacketRecovery detect_loss(self, space: QuicPacketSpace, now: float) -> None detect_loss(space: QuicPacketSpace, now: float) -> None get_earliest_loss_time(self) -> Optional[QuicPacketSpace] get_earliest_loss_time() -> Optional[QuicPacketSpace] on_packet_acked(packet: QuicSentPacket) -> None on_packet_acked(self, packet: QuicSentPacket) -> None at: aioquic.recovery.QuicPacketRecovery.__init__ self.ack_delay_exponent = 3 self.max_ack_delay = 25 # ms self.spaces: List[QuicPacketSpace] = [] 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.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.recovery class QuicPacketRecovery: def discard_space(self, space: QuicPacketSpace) -> None: assert space in self.spaces for packet in space.sent_packets.values(): if packet.in_flight: self.on_packet_expired(packet) space.sent_packets.clear() space.ack_at = None space.ack_eliciting_in_flight = 0 - space.crypto_packet_in_flight = 0 space.loss_time = None ===========changed ref 1=========== # module: aioquic.recovery class QuicPacketSpace: def __init__(self) -> None: self.ack_at: Optional[float] = None self.ack_queue = RangeSet() self.expected_packet_number = 0 self.largest_received_packet = 0 # sent packets and loss self.ack_eliciting_in_flight = 0 - self.crypto_packet_in_flight = 0 self.largest_acked_packet = 0 self.loss_time: Optional[float] = None self.sent_packets: Dict[int, QuicSentPacket] = {} ===========changed ref 2=========== # module: aioquic.recovery class QuicPacketRecovery: def __init__(self, send_probe: Callable[[], None]) -> None: self.ack_delay_exponent = 3 self.max_ack_delay = 25 # ms self.spaces: List[QuicPacketSpace] = [] # callbacks self._send_probe = send_probe # loss detection - self._crypto_count = 0 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 - self._time_of_last_sent_crypto_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 = math.inf ===========changed ref 3=========== # module: aioquic.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 - # crypto timer - if sum(space.crypto_packet_in_flight for space in self.spaces): - timeout = max( - 2 * (self._rtt_smoothed if self._rtt_initialized else K_INITIAL_RTT), - K_GRANULARITY, - ) * (2 ** self._crypto_count) - return self._time_of_last_sent_crypto_packet + timeout - # packet timer if sum(space.ack_eliciting_in_flight for space in self.spaces): + if not self._rtt_initialized: + timeout = 2 * K_INITIAL_RTT * (2 ** self._pto_count) + else: + timeout = ( - timeout = ( + self._rtt_smoothed - self._rtt_smoothed + + max(4 * self._rtt_variance, K_GRANULARITY) - + max(4 * self._rtt_variance, K_GRANULARITY) + + self.max_ack_delay / 1000 - + self.max_ack_delay / 1000 + ) * (2 ** self._pto_count) - ) * (2 ** self._pto_count) return self._time_of_last_sent_ack_eliciting_packet + timeout return None
aioquic.recovery/QuicPacketRecovery.on_loss_detection_timeout
Modified
aiortc~aioquic
fc09c97d4543d7bc241308ff9cc9b5e88635a5eb
[recovery] merge crypto and pto timers
<3>:<add> else: <add> self._pto_count += 1 <add> <add> # reschedule some data <del> elif sum(space.crypto_packet_in_flight for space in self.spaces): <4>:<del> # reschedule crypto packets <11>:<del> self._crypto_count += 1 <12>:<del> else: <13>:<del> self._pto_count += 1 <14>:<add>
# module: aioquic.recovery class QuicPacketRecovery: def on_loss_detection_timeout(self, now: float) -> None: <0> loss_space = self.get_earliest_loss_time() <1> if loss_space is not None: <2> self.detect_loss(loss_space, now=now) <3> elif sum(space.crypto_packet_in_flight for space in self.spaces): <4> # reschedule crypto packets <5> for space in self.spaces: <6> for packet_number, packet in list( <7> filter(lambda i: i[1].is_crypto_packet, space.sent_packets.items()) <8> ): <9> # remove packet and update counters <10> self.on_packet_lost(packet, space) <11> self._crypto_count += 1 <12> else: <13> self._pto_count += 1 <14> self._send_probe() <15>
===========unchanged ref 0=========== at: aioquic.packet_builder QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field( default_factory=list )) at: aioquic.packet_builder.QuicSentPacket sent_time: Optional[float] = None sent_bytes: int = 0 at: aioquic.recovery.QuicPacketRecovery on_packet_lost(packet: QuicSentPacket, space: QuicPacketSpace) -> None at: aioquic.recovery.QuicPacketRecovery.__init__ self._send_probe = send_probe self.bytes_in_flight = 0 self.congestion_window = K_INITIAL_WINDOW self._congestion_recovery_start_time = 0.0 self._ssthresh = math.inf at: aioquic.recovery.QuicPacketRecovery.on_packet_expired self.bytes_in_flight -= packet.sent_bytes at: aioquic.recovery.QuicPacketRecovery.on_packet_lost self.bytes_in_flight -= packet.sent_bytes at: aioquic.recovery.QuicPacketRecovery.on_packet_sent self.bytes_in_flight += packet.sent_bytes at: aioquic.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 ===========changed ref 0=========== # module: aioquic.recovery class QuicPacketRecovery: def discard_space(self, space: QuicPacketSpace) -> None: assert space in self.spaces for packet in space.sent_packets.values(): if packet.in_flight: self.on_packet_expired(packet) space.sent_packets.clear() space.ack_at = None space.ack_eliciting_in_flight = 0 - space.crypto_packet_in_flight = 0 space.loss_time = None ===========changed ref 1=========== # module: aioquic.recovery class QuicPacketSpace: def __init__(self) -> None: self.ack_at: Optional[float] = None self.ack_queue = RangeSet() self.expected_packet_number = 0 self.largest_received_packet = 0 # sent packets and loss self.ack_eliciting_in_flight = 0 - self.crypto_packet_in_flight = 0 self.largest_acked_packet = 0 self.loss_time: Optional[float] = None self.sent_packets: Dict[int, QuicSentPacket] = {} ===========changed ref 2=========== # module: aioquic.recovery class QuicPacketRecovery: def __init__(self, send_probe: Callable[[], None]) -> None: self.ack_delay_exponent = 3 self.max_ack_delay = 25 # ms self.spaces: List[QuicPacketSpace] = [] # callbacks self._send_probe = send_probe # loss detection - self._crypto_count = 0 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 - self._time_of_last_sent_crypto_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 = math.inf ===========changed ref 3=========== # module: aioquic.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 - # crypto timer - if sum(space.crypto_packet_in_flight for space in self.spaces): - timeout = max( - 2 * (self._rtt_smoothed if self._rtt_initialized else K_INITIAL_RTT), - K_GRANULARITY, - ) * (2 ** self._crypto_count) - return self._time_of_last_sent_crypto_packet + timeout - # packet timer if sum(space.ack_eliciting_in_flight for space in self.spaces): + if not self._rtt_initialized: + timeout = 2 * K_INITIAL_RTT * (2 ** self._pto_count) + else: + timeout = ( - timeout = ( + self._rtt_smoothed - self._rtt_smoothed + + max(4 * self._rtt_variance, K_GRANULARITY) - + max(4 * self._rtt_variance, K_GRANULARITY) + + self.max_ack_delay / 1000 - + self.max_ack_delay / 1000 + ) * (2 ** self._pto_count) - ) * (2 ** self._pto_count) return self._time_of_last_sent_ack_eliciting_packet + timeout return None ===========changed ref 4=========== # module: aioquic.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.is_crypto_packet: - space.crypto_packet_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</s>
aioquic.recovery/QuicPacketRecovery.on_packet_lost
Modified
aiortc~aioquic
fc09c97d4543d7bc241308ff9cc9b5e88635a5eb
[recovery] merge crypto and pto timers
<4>:<del> if packet.is_crypto_packet: <5>:<del> space.crypto_packet_in_flight -= 1
# module: aioquic.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.is_crypto_packet: <5> space.crypto_packet_in_flight -= 1 <6> if packet.in_flight: <7> self.bytes_in_flight -= packet.sent_bytes <8> <9> # trigger callbacks <10> for handler, args in packet.delivery_handlers: <11> handler(QuicDeliveryState.LOST, *args) <12>
===========unchanged ref 0=========== at: aioquic.packet_builder QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field( default_factory=list )) at: aioquic.packet_builder.QuicSentPacket in_flight: bool is_ack_eliciting: bool packet_number: int sent_time: Optional[float] = None sent_bytes: int = 0 at: aioquic.recovery QuicPacketSpace() at: aioquic.recovery.QuicPacketRecovery.__init__ self._time_of_last_sent_ack_eliciting_packet = 0.0 self.bytes_in_flight = 0 at: aioquic.recovery.QuicPacketRecovery.on_packet_acked self.bytes_in_flight -= packet.sent_bytes at: aioquic.recovery.QuicPacketRecovery.on_packet_expired self.bytes_in_flight -= packet.sent_bytes at: aioquic.recovery.QuicPacketRecovery.on_packet_lost self.bytes_in_flight -= packet.sent_bytes at: aioquic.recovery.QuicPacketSpace.__init__ self.ack_eliciting_in_flight = 0 self.sent_packets: Dict[int, QuicSentPacket] = {} ===========changed ref 0=========== # module: aioquic.recovery class QuicPacketRecovery: def on_loss_detection_timeout(self, now: float) -> None: loss_space = self.get_earliest_loss_time() if loss_space is not None: self.detect_loss(loss_space, now=now) + else: + self._pto_count += 1 + + # reschedule some data - elif sum(space.crypto_packet_in_flight for space in self.spaces): - # reschedule crypto packets for space in self.spaces: for packet_number, packet in list( filter(lambda i: i[1].is_crypto_packet, space.sent_packets.items()) ): # remove packet and update counters self.on_packet_lost(packet, space) - self._crypto_count += 1 - else: - self._pto_count += 1 + self._send_probe() ===========changed ref 1=========== # module: aioquic.recovery class QuicPacketRecovery: def discard_space(self, space: QuicPacketSpace) -> None: assert space in self.spaces for packet in space.sent_packets.values(): if packet.in_flight: self.on_packet_expired(packet) space.sent_packets.clear() space.ack_at = None space.ack_eliciting_in_flight = 0 - space.crypto_packet_in_flight = 0 space.loss_time = None ===========changed ref 2=========== # module: aioquic.recovery class QuicPacketSpace: def __init__(self) -> None: self.ack_at: Optional[float] = None self.ack_queue = RangeSet() self.expected_packet_number = 0 self.largest_received_packet = 0 # sent packets and loss self.ack_eliciting_in_flight = 0 - self.crypto_packet_in_flight = 0 self.largest_acked_packet = 0 self.loss_time: Optional[float] = None self.sent_packets: Dict[int, QuicSentPacket] = {} ===========changed ref 3=========== # module: aioquic.recovery class QuicPacketRecovery: def __init__(self, send_probe: Callable[[], None]) -> None: self.ack_delay_exponent = 3 self.max_ack_delay = 25 # ms self.spaces: List[QuicPacketSpace] = [] # callbacks self._send_probe = send_probe # loss detection - self._crypto_count = 0 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 - self._time_of_last_sent_crypto_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 = math.inf ===========changed ref 4=========== # module: aioquic.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 - # crypto timer - if sum(space.crypto_packet_in_flight for space in self.spaces): - timeout = max( - 2 * (self._rtt_smoothed if self._rtt_initialized else K_INITIAL_RTT), - K_GRANULARITY, - ) * (2 ** self._crypto_count) - return self._time_of_last_sent_crypto_packet + timeout - # packet timer if sum(space.ack_eliciting_in_flight for space in self.spaces): + if not self._rtt_initialized: + timeout = 2 * K_INITIAL_RTT * (2 ** self._pto_count) + else: + timeout = ( - timeout = ( + self._rtt_smoothed - self._rtt_smoothed + + max(4 * self._rtt_variance, K_GRANULARITY) - + max(4 * self._rtt_variance, K_GRANULARITY) + + self.max_ack_delay / 1000 - + self.max_ack_delay / 1000 + ) * (2 ** self._pto_count) - ) * (2 ** self._pto_count) return self._time_of_last_sent_ack_eliciting_packet + timeout return None
aioquic.recovery/QuicPacketRecovery.on_packet_sent
Modified
aiortc~aioquic
fc09c97d4543d7bc241308ff9cc9b5e88635a5eb
[recovery] merge crypto and pto timers
<4>:<del> if packet.is_crypto_packet: <5>:<del> space.crypto_packet_in_flight += 1 <7>:<del> if packet.is_crypto_packet: <8>:<del> self._time_of_last_sent_crypto_packet = packet.sent_time
# module: aioquic.recovery class QuicPacketRecovery: def on_packet_sent(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None: <0> space.sent_packets[packet.packet_number] = packet <1> <2> if packet.is_ack_eliciting: <3> space.ack_eliciting_in_flight += 1 <4> if packet.is_crypto_packet: <5> space.crypto_packet_in_flight += 1 <6> if packet.in_flight: <7> if packet.is_crypto_packet: <8> self._time_of_last_sent_crypto_packet = packet.sent_time <9> if packet.is_ack_eliciting: <10> self._time_of_last_sent_ack_eliciting_packet = packet.sent_time <11> <12> # add packet to bytes in flight <13> self.bytes_in_flight += packet.sent_bytes <14>
===========unchanged ref 0=========== at: aioquic.recovery K_MINIMUM_WINDOW = 2 * K_MAX_DATAGRAM_SIZE K_LOSS_REDUCTION_FACTOR = 0.5 at: aioquic.recovery.QuicPacketRecovery.__init__ self.congestion_window = K_INITIAL_WINDOW self._congestion_recovery_start_time = 0.0 self._ssthresh = math.inf at: aioquic.recovery.QuicPacketRecovery.on_packet_acked self.congestion_window += ( K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window ) self.congestion_window += packet.sent_bytes ===========changed ref 0=========== # module: aioquic.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.is_crypto_packet: - space.crypto_packet_in_flight -= 1 if packet.in_flight: self.bytes_in_flight -= packet.sent_bytes # trigger callbacks for handler, args in packet.delivery_handlers: handler(QuicDeliveryState.LOST, *args) ===========changed ref 1=========== # module: aioquic.recovery class QuicPacketRecovery: def on_loss_detection_timeout(self, now: float) -> None: loss_space = self.get_earliest_loss_time() if loss_space is not None: self.detect_loss(loss_space, now=now) + else: + self._pto_count += 1 + + # reschedule some data - elif sum(space.crypto_packet_in_flight for space in self.spaces): - # reschedule crypto packets for space in self.spaces: for packet_number, packet in list( filter(lambda i: i[1].is_crypto_packet, space.sent_packets.items()) ): # remove packet and update counters self.on_packet_lost(packet, space) - self._crypto_count += 1 - else: - self._pto_count += 1 + self._send_probe() ===========changed ref 2=========== # module: aioquic.recovery class QuicPacketRecovery: def discard_space(self, space: QuicPacketSpace) -> None: assert space in self.spaces for packet in space.sent_packets.values(): if packet.in_flight: self.on_packet_expired(packet) space.sent_packets.clear() space.ack_at = None space.ack_eliciting_in_flight = 0 - space.crypto_packet_in_flight = 0 space.loss_time = None ===========changed ref 3=========== # module: aioquic.recovery class QuicPacketSpace: def __init__(self) -> None: self.ack_at: Optional[float] = None self.ack_queue = RangeSet() self.expected_packet_number = 0 self.largest_received_packet = 0 # sent packets and loss self.ack_eliciting_in_flight = 0 - self.crypto_packet_in_flight = 0 self.largest_acked_packet = 0 self.loss_time: Optional[float] = None self.sent_packets: Dict[int, QuicSentPacket] = {} ===========changed ref 4=========== # module: aioquic.recovery class QuicPacketRecovery: def __init__(self, send_probe: Callable[[], None]) -> None: self.ack_delay_exponent = 3 self.max_ack_delay = 25 # ms self.spaces: List[QuicPacketSpace] = [] # callbacks self._send_probe = send_probe # loss detection - self._crypto_count = 0 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 - self._time_of_last_sent_crypto_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 = math.inf ===========changed ref 5=========== # module: aioquic.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 - # crypto timer - if sum(space.crypto_packet_in_flight for space in self.spaces): - timeout = max( - 2 * (self._rtt_smoothed if self._rtt_initialized else K_INITIAL_RTT), - K_GRANULARITY, - ) * (2 ** self._crypto_count) - return self._time_of_last_sent_crypto_packet + timeout - # packet timer if sum(space.ack_eliciting_in_flight for space in self.spaces): + if not self._rtt_initialized: + timeout = 2 * K_INITIAL_RTT * (2 ** self._pto_count) + else: + timeout = ( - timeout = ( + self._rtt_smoothed - self._rtt_smoothed + + max(4 * self._rtt_variance, K_GRANULARITY) - + max(4 * self._rtt_variance, K_GRANULARITY) + + self.max_ack_delay / 1000 - + self.max_ack_delay / 1000 + ) * (2 ** self._pto_count) - ) * (2 ** self._pto_count) return self._time_of_last_sent_ack_eliciting_packet + timeout return None
tests.test_recovery/QuicPacketRecoveryTest.test_on_packet_lost_crypto
Modified
aiortc~aioquic
fc09c97d4543d7bc241308ff9cc9b5e88635a5eb
[recovery] merge crypto and pto timers
<14>:<del> self.assertEqual(space.crypto_packet_in_flight, 1) <20>:<del> self.assertEqual(space.crypto_packet_in_flight, 0)
# module: tests.test_recovery class QuicPacketRecoveryTest(TestCase): def test_on_packet_lost_crypto(self): <0> packet = QuicSentPacket( <1> epoch=tls.Epoch.INITIAL, <2> in_flight=True, <3> is_ack_eliciting=True, <4> is_crypto_packet=True, <5> packet_number=0, <6> sent_bytes=1280, <7> sent_time=123.45, <8> ) <9> space = self.INITIAL_SPACE <10> <11> self.recovery.on_packet_sent(packet, space) <12> self.assertEqual(self.recovery.bytes_in_flight, 1280) <13> self.assertEqual(space.ack_eliciting_in_flight, 1) <14> self.assertEqual(space.crypto_packet_in_flight, 1) <15> self.assertEqual(len(space.sent_packets), 1) <16> <17> self.recovery.on_packet_lost(packet, space) <18> self.assertEqual(self.recovery.bytes_in_flight, 0) <19> self.assertEqual(space.ack_eliciting_in_flight, 0) <20> self.assertEqual(space.crypto_packet_in_flight, 0) <21> self.assertEqual(len(space.sent_packets), 0) <22>
===========unchanged ref 0=========== at: aioquic.packet_builder QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field( default_factory=list )) at: aioquic.packet_builder.QuicSentPacket epoch: Epoch in_flight: bool is_ack_eliciting: bool is_crypto_packet: bool packet_number: int sent_time: Optional[float] = None sent_bytes: int = 0 delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field( default_factory=list ) at: aioquic.recovery.QuicPacketRecovery on_packet_lost(packet: QuicSentPacket, space: QuicPacketSpace) -> None on_packet_sent(packet: QuicSentPacket, space: QuicPacketSpace) -> None at: aioquic.recovery.QuicPacketRecovery.__init__ self.bytes_in_flight = 0 at: aioquic.recovery.QuicPacketRecovery.on_packet_acked self.bytes_in_flight -= packet.sent_bytes at: aioquic.recovery.QuicPacketRecovery.on_packet_expired self.bytes_in_flight -= packet.sent_bytes at: aioquic.recovery.QuicPacketRecovery.on_packet_lost self.bytes_in_flight -= packet.sent_bytes at: aioquic.recovery.QuicPacketRecovery.on_packet_sent self.bytes_in_flight += packet.sent_bytes at: aioquic.recovery.QuicPacketSpace.__init__ self.ack_eliciting_in_flight = 0 self.sent_packets: Dict[int, QuicSentPacket] = {} ===========unchanged ref 1=========== at: aioquic.tls Epoch() at: tests.test_recovery.QuicPacketRecoveryTest.setUp self.INITIAL_SPACE = QuicPacketSpace() self.recovery = QuicPacketRecovery(send_probe=send_probe) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.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.is_crypto_packet: - space.crypto_packet_in_flight -= 1 if packet.in_flight: self.bytes_in_flight -= packet.sent_bytes # trigger callbacks for handler, args in packet.delivery_handlers: handler(QuicDeliveryState.LOST, *args) ===========changed ref 1=========== # module: aioquic.recovery class QuicPacketRecovery: def on_packet_sent(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None: space.sent_packets[packet.packet_number] = packet if packet.is_ack_eliciting: space.ack_eliciting_in_flight += 1 - if packet.is_crypto_packet: - space.crypto_packet_in_flight += 1 if packet.in_flight: - if packet.is_crypto_packet: - self._time_of_last_sent_crypto_packet = packet.sent_time if packet.is_ack_eliciting: self._time_of_last_sent_ack_eliciting_packet = packet.sent_time # add packet to bytes in flight self.bytes_in_flight += packet.sent_bytes ===========changed ref 2=========== # module: aioquic.recovery class QuicPacketRecovery: def discard_space(self, space: QuicPacketSpace) -> None: assert space in self.spaces for packet in space.sent_packets.values(): if packet.in_flight: self.on_packet_expired(packet) space.sent_packets.clear() space.ack_at = None space.ack_eliciting_in_flight = 0 - space.crypto_packet_in_flight = 0 space.loss_time = None ===========changed ref 3=========== # module: aioquic.recovery class QuicPacketSpace: def __init__(self) -> None: self.ack_at: Optional[float] = None self.ack_queue = RangeSet() self.expected_packet_number = 0 self.largest_received_packet = 0 # sent packets and loss self.ack_eliciting_in_flight = 0 - self.crypto_packet_in_flight = 0 self.largest_acked_packet = 0 self.loss_time: Optional[float] = None self.sent_packets: Dict[int, QuicSentPacket] = {} ===========changed ref 4=========== # module: aioquic.recovery class QuicPacketRecovery: def on_loss_detection_timeout(self, now: float) -> None: loss_space = self.get_earliest_loss_time() if loss_space is not None: self.detect_loss(loss_space, now=now) + else: + self._pto_count += 1 + + # reschedule some data - elif sum(space.crypto_packet_in_flight for space in self.spaces): - # reschedule crypto packets for space in self.spaces: for packet_number, packet in list( filter(lambda i: i[1].is_crypto_packet, space.sent_packets.items()) ): # remove packet and update counters self.on_packet_lost(packet, space) - self._crypto_count += 1 - else: - self._pto_count += 1 + self._send_probe() ===========changed ref 5=========== # module: aioquic.recovery class QuicPacketRecovery: def __init__(self, send_probe: Callable[[], None]) -> None: self.ack_delay_exponent = 3 self.max_ack_delay = 25 # ms self.spaces: List[QuicPacketSpace] = [] # callbacks self._send_probe = send_probe # loss detection - self._crypto_count = 0 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 - self._time_of_last_sent_crypto_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 = math.inf
aioquic.recovery/QuicPacketRecovery.__init__
Modified
aiortc~aioquic
091d169f28d7efeeac27d58a1dec1a6cef1d39a3
[recovery] send anti-deadlock packets more agressively
<1>:<add> self.is_client_without_1rtt = is_client_without_1rtt
# module: aioquic.recovery class QuicPacketRecovery: + def __init__( + self, is_client_without_1rtt: bool, send_probe: Callable[[], None] + ) -> None: - def __init__(self, send_probe: Callable[[], None]) -> None: <0> self.ack_delay_exponent = 3 <1> self.max_ack_delay = 25 # ms <2> self.spaces: List[QuicPacketSpace] = [] <3> <4> # callbacks <5> self._send_probe = send_probe <6> <7> # loss detection <8> self._pto_count = 0 <9> self._rtt_initialized = False <10> self._rtt_latest = 0.0 <11> self._rtt_min = math.inf <12> self._rtt_smoothed = 0.0 <13> self._rtt_variance = 0.0 <14> self._time_of_last_sent_ack_eliciting_packet = 0.0 <15> <16> # congestion control <17> self.bytes_in_flight = 0 <18> self.congestion_window = K_INITIAL_WINDOW <19> self._congestion_recovery_start_time = 0.0 <20> self._ssthresh = math.inf <21>
===========unchanged ref 0=========== at: aioquic.recovery QuicPacketSpace() at: aioquic.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.recovery.QuicPacketRecovery.on_loss_detection_timeout self._pto_count += 1 at: aioquic.recovery.QuicPacketRecovery.on_packet_acked self.bytes_in_flight -= packet.sent_bytes at: aioquic.recovery.QuicPacketRecovery.on_packet_expired self.bytes_in_flight -= packet.sent_bytes at: aioquic.recovery.QuicPacketRecovery.on_packet_lost self.bytes_in_flight -= packet.sent_bytes at: aioquic.recovery.QuicPacketRecovery.on_packet_sent self._time_of_last_sent_ack_eliciting_packet = packet.sent_time self.bytes_in_flight += packet.sent_bytes at: math inf: float at: typing Callable = _CallableType(collections.abc.Callable, 2) List = _alias(list, 1, inst=False, name='List')
aioquic.recovery/QuicPacketRecovery.get_loss_detection_time
Modified
aiortc~aioquic
091d169f28d7efeeac27d58a1dec1a6cef1d39a3
[recovery] send anti-deadlock packets more agressively
<6>:<add> if ( <add> self.is_client_without_1rtt <add> or sum(space.ack_eliciting_in_flight for space in self.spaces) > 0 <del> if sum(space.ack_eliciting_in_flight for space in self.spaces): <7>:<add> ):
# module: aioquic.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 sum(space.ack_eliciting_in_flight for space in self.spaces): <7> if not self._rtt_initialized: <8> timeout = 2 * K_INITIAL_RTT * (2 ** self._pto_count) <9> else: <10> timeout = ( <11> self._rtt_smoothed <12> + max(4 * self._rtt_variance, K_GRANULARITY) <13> + self.max_ack_delay / 1000 <14> ) * (2 ** self._pto_count) <15> return self._time_of_last_sent_ack_eliciting_packet + timeout <16> <17> return None <18>
===========unchanged ref 0=========== at: aioquic.recovery K_INITIAL_RTT = 0.5 # seconds at: aioquic.recovery.QuicPacketRecovery get_earliest_loss_time() -> Optional[QuicPacketSpace] at: aioquic.recovery.QuicPacketRecovery.__init__ self.is_client_without_1rtt = is_client_without_1rtt self.spaces: List[QuicPacketSpace] = [] self._pto_count = 0 self._rtt_initialized = False self._rtt_smoothed = 0.0 at: aioquic.recovery.QuicPacketRecovery.on_ack_received self._rtt_initialized = True self._rtt_smoothed = latest_rtt self._rtt_smoothed = ( 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest ) self._pto_count = 0 at: aioquic.recovery.QuicPacketRecovery.on_loss_detection_timeout self._pto_count += 1 at: aioquic.recovery.QuicPacketSpace.__init__ self.ack_eliciting_in_flight = 0 self.loss_time: Optional[float] = None ===========changed ref 0=========== # module: aioquic.recovery class QuicPacketRecovery: + def __init__( + self, is_client_without_1rtt: bool, send_probe: Callable[[], None] + ) -> None: - def __init__(self, send_probe: Callable[[], None]) -> None: self.ack_delay_exponent = 3 + self.is_client_without_1rtt = is_client_without_1rtt self.max_ack_delay = 25 # ms self.spaces: List[QuicPacketSpace] = [] # callbacks 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 = math.inf
aioquic.connection/QuicConnection.__init__
Modified
aiortc~aioquic
091d169f28d7efeeac27d58a1dec1a6cef1d39a3
[recovery] send anti-deadlock packets more agressively
# module: aioquic.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._stateless_retry_count = 0 <14> self._version_negotiation_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.Event] = 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.host_cid = self._</s>
===========below chunk 0=========== # module: aioquic.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_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(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_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</s> ===========below chunk 1=========== # module: aioquic.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>i_local = 0 self._remote_max_stream_data_bidi_remote = 0 self._remote_max_stream_data_uni = 0 self._remote_max_streams_bidi = 0 self._remote_max_streams_uni = 0 self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._spin_bit = False self._spin_bit_peer = False self._spin_highest_pn = 0 self._state = QuicConnectionState.FIRSTFLIGHT self._streams: Dict[int, QuicStream] = {} self._streams_blocked_bidi: List[QuicStream] = [] self._streams_blocked_uni: List[QuicStream] = [] self._version: Optional[int] = None # things to send self._close_pending = False self._ping_pending: List[int] = [] self._probe_pending = False self._retire_connection_ids: List[int] = [] self._streams_blocked_pending = False # callbacks self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler # frame handlers self.__frame_handlers = [ (self._handle_padding_frame, EPOCHS("IZHO")), (self._handle_padding_frame, EPOCHS("ZO")), (self._handle_ack_frame, EPOCHS("IHO")), </s> ===========below chunk 2=========== # module: aioquic.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_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, EPOCHS("ZO")), (self._handle_max_streams_uni_frame, EPOCHS("ZO")), (self._handle_data_blocked_frame, EPOCHS("ZO")), (self._handle_stream_data_blocked</s> ===========below chunk 3=========== # module: aioquic.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_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.connection/QuicConnection._handle_crypto_frame
Modified
aiortc~aioquic
091d169f28d7efeeac27d58a1dec1a6cef1d39a3
[recovery] send anti-deadlock packets more agressively
<38>:<add> self._loss.is_client_without_1rtt = False
# module: aioquic.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._replenish_connection_ids() <39> self._events.append( <40> events.HandshakeCompleted( <41> alpn_protocol=self.tls.alpn_negotiated, <42> early_data_accepted=self.tls.early_data_accepted,</s>
===========below chunk 0=========== # module: aioquic.connection class QuicConnection: def _handle_crypto_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: # offset: 1 ) ) 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.connection QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, time: float) at: aioquic.connection.QuicConnection _close_begin(is_initiator: bool, now: float) -> None _replenish_connection_ids() -> None _push_crypto_data() -> None _parse_transport_parameters(data: bytes, from_session_ticket: bool=False) -> None _unblock_streams(is_unidirectional: bool) -> None at: aioquic.connection.QuicConnection.__init__ self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} self._events: Deque[events.Event] = deque() self._handshake_complete = False self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, send_probe=self._send_probe ) self._parameters_received = False at: aioquic.connection.QuicConnection._initialize self.tls = tls.Context(is_client=self._is_client, logger=self._logger) 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(), } ===========unchanged ref 1=========== at: aioquic.connection.QuicReceiveContext epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath time: float at: aioquic.events HandshakeCompleted(alpn_protocol: Optional[str], early_data_accepted: bool, session_resumed: bool) at: aioquic.events.HandshakeCompleted alpn_protocol: Optional[str] early_data_accepted: bool session_resumed: bool at: aioquic.packet QuicErrorCode(x: Union[str, bytes, bytearray], base: int) QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) pull_crypto_frame(buf: Buffer) -> QuicStreamFrame at: aioquic.recovery.QuicPacketRecovery.__init__ self.is_client_without_1rtt = is_client_without_1rtt at: aioquic.stream.QuicStream add_frame(frame: QuicStreamFrame) -> None pull_data() -> bytes at: aioquic.tls Alert(*args: object) State() ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: aioquic.tls.Alert description: AlertDescription at: aioquic.tls.Context handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None at: aioquic.tls.Context.__init__ self.alpn_negotiated: Optional[str] = None self.early_data_accepted = False self.received_extensions: Optional[List[Extension]] = None ===========unchanged ref 2=========== self.state = State.CLIENT_HANDSHAKE_START self.state = State.SERVER_EXPECT_CLIENT_HELLO at: aioquic.tls.Context._client_handle_encrypted_extensions self.alpn_negotiated = encrypted_extensions.alpn_protocol self.early_data_accepted = encrypted_extensions.early_data self.received_extensions = encrypted_extensions.other_extensions at: aioquic.tls.Context._server_handle_hello self.alpn_negotiated = negotiate( self.alpn_protocols, peer_hello.alpn_protocols, AlertHandshakeFailure("No common ALPN protocols"), ) self.received_extensions = peer_hello.other_extensions self.early_data_accepted = True at: aioquic.tls.Context._set_state self.state = state at: collections.deque append(x: _T) -> None ===========changed ref 0=========== # module: aioquic.recovery class QuicPacketRecovery: + def __init__( + self, is_client_without_1rtt: bool, send_probe: Callable[[], None] + ) -> None: - def __init__(self, send_probe: Callable[[], None]) -> None: self.ack_delay_exponent = 3 + self.is_client_without_1rtt = is_client_without_1rtt self.max_ack_delay = 25 # ms self.spaces: List[QuicPacketSpace] = [] # callbacks 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 = math.inf ===========changed ref 1=========== # module: aioquic.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 sum(space.ack_eliciting_in_flight for space in self.spaces): + ): 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 / 1000 ) * (2 ** self._pto_count) return self._time_of_last_sent_ack_eliciting_packet + timeout return None
aioquic.connection/QuicConnection._write_handshake
Modified
aiortc~aioquic
091d169f28d7efeeac27d58a1dec1a6cef1d39a3
[recovery] send anti-deadlock packets more agressively
<13>:<add> builder.start_packet(packet_type, crypto, is_probe=self._probe_pending) <del> builder.start_packet(packet_type, crypto) <25>:<add> # PADDING (anti-deadlock packet) <add> if self._probe_pending and self._is_client and epoch == tls.Epoch.HANDSHAKE: <add> buf.push_bytes(bytes(builder.remaining_space)) <add> self._probe_pending = False <add>
# module: aioquic.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> if not builder.end_packet(): <26> break <27>
===========unchanged ref 0=========== at: aioquic.connection write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None at: aioquic.connection.QuicConnection.__init__ self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._probe_pending = False at: aioquic.connection.QuicConnection._initialize self._cryptos = { tls.Epoch.INITIAL: CryptoPair(), tls.Epoch.ZERO_RTT: CryptoPair(), tls.Epoch.HANDSHAKE: CryptoPair(), tls.Epoch.ONE_RTT: CryptoPair(), } self._crypto_streams = { tls.Epoch.INITIAL: QuicStream(), tls.Epoch.HANDSHAKE: QuicStream(), tls.Epoch.ONE_RTT: QuicStream(), } self._spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } at: aioquic.connection.QuicConnection._send_probe self._probe_pending = True at: aioquic.connection.QuicConnection._write_application self._probe_pending = False at: aioquic.connection.QuicConnection._write_handshake self._probe_pending = False at: aioquic.crypto.CryptoContext is_valid() -> bool at: aioquic.crypto.CryptoPair.__init__ self.send = CryptoContext() at: aioquic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20 ===========unchanged ref 1=========== 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 at: aioquic.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) at: aioquic.packet_builder.QuicPacketBuilder start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None start_packet(packet_type: int, crypto: CryptoPair, is_probe=False) -> None end_packet() -> bool at: aioquic.packet_builder.QuicPacketBuilder.__init__ self.buffer = Buffer(PACKET_MAX_SIZE) at: aioquic.recovery.QuicPacketSpace.__init__ self.ack_at: Optional[float] = None self.ack_queue = RangeSet() at: aioquic.stream.QuicStream.__init__ self.send_buffer_is_empty = True at: aioquic.stream.QuicStream.get_frame self.send_buffer_is_empty = True at: aioquic.stream.QuicStream.on_data_delivery self.send_buffer_is_empty = False at: aioquic.stream.QuicStream.write self.send_buffer_is_empty = False at: aioquic.tls Epoch() ===========changed ref 0=========== # module: aioquic.connection class QuicConnection: def _handle_crypto_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a CRYPTO frame. """ stream = self._crypto_streams[context.epoch] 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_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, ) ) </s> ===========changed ref 1=========== # module: aioquic.connection class QuicConnection: def _handle_crypto_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: # offset: 1 <s>_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 2=========== # module: aioquic.recovery class QuicPacketRecovery: + def __init__( + self, is_client_without_1rtt: bool, send_probe: Callable[[], None] + ) -> None: - def __init__(self, send_probe: Callable[[], None]) -> None: self.ack_delay_exponent = 3 + self.is_client_without_1rtt = is_client_without_1rtt self.max_ack_delay = 25 # ms self.spaces: List[QuicPacketSpace] = [] # callbacks 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 = math.inf
tests.test_recovery/QuicPacketRecoveryTest.setUp
Modified
aiortc~aioquic
091d169f28d7efeeac27d58a1dec1a6cef1d39a3
[recovery] send anti-deadlock packets more agressively
<4>:<add> self.recovery = QuicPacketRecovery( <del> self.recovery = QuicPacketRecovery(send_probe=send_probe) <5>:<add> is_client_without_1rtt=False, send_probe=send_probe <add> )
# module: tests.test_recovery class QuicPacketRecoveryTest(TestCase): def setUp(self): <0> self.INITIAL_SPACE = QuicPacketSpace() <1> self.HANDSHAKE_SPACE = QuicPacketSpace() <2> self.ONE_RTT_SPACE = QuicPacketSpace() <3> <4> self.recovery = QuicPacketRecovery(send_probe=send_probe) <5> self.recovery.spaces = [ <6> self.INITIAL_SPACE, <7> self.HANDSHAKE_SPACE, <8> self.ONE_RTT_SPACE, <9> ] <10>
===========unchanged ref 0=========== at: aioquic.recovery QuicPacketSpace() QuicPacketRecovery(is_client_without_1rtt: bool, send_probe: Callable[[], None]) at: aioquic.recovery.QuicPacketRecovery.__init__ self.spaces: List[QuicPacketSpace] = [] at: tests.test_recovery send_probe() at: unittest.case.TestCase failureException = AssertionError longMessage = True maxDiff = 80*8 _diffThreshold = 2**16 setUp(self) -> None failUnlessEqual = assertEquals = _deprecate(assertEqual) failUnlessEqual = assertEquals = _deprecate(assertEqual) failIfEqual = assertNotEquals = _deprecate(assertNotEqual) failIfEqual = assertNotEquals = _deprecate(assertNotEqual) failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual) failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual) failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual) failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual) failUnless = assert_ = _deprecate(assertTrue) failUnless = assert_ = _deprecate(assertTrue) failUnlessRaises = _deprecate(assertRaises) failIf = _deprecate(assertFalse) assertRaisesRegexp = _deprecate(assertRaisesRegex) assertRegexpMatches = _deprecate(assertRegex) assertNotRegexpMatches = _deprecate(assertNotRegex) ===========changed ref 0=========== # module: aioquic.recovery class QuicPacketRecovery: + def __init__( + self, is_client_without_1rtt: bool, send_probe: Callable[[], None] + ) -> None: - def __init__(self, send_probe: Callable[[], None]) -> None: self.ack_delay_exponent = 3 + self.is_client_without_1rtt = is_client_without_1rtt self.max_ack_delay = 25 # ms self.spaces: List[QuicPacketSpace] = [] # callbacks 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 = math.inf ===========changed ref 1=========== # module: aioquic.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 sum(space.ack_eliciting_in_flight for space in self.spaces): + ): 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 / 1000 ) * (2 ** self._pto_count) return self._time_of_last_sent_ack_eliciting_packet + timeout return None ===========changed ref 2=========== # module: aioquic.connection class QuicConnection: def _write_handshake(self, builder: QuicPacketBuilder, epoch: tls.Epoch) -> None: crypto = self._cryptos[epoch] if not crypto.send.is_valid(): return buf = builder.buffer crypto_stream = self._crypto_streams[epoch] space = self._spaces[epoch] while True: if epoch == tls.Epoch.INITIAL: packet_type = PACKET_TYPE_INITIAL else: packet_type = PACKET_TYPE_HANDSHAKE + builder.start_packet(packet_type, crypto, is_probe=self._probe_pending) - builder.start_packet(packet_type, crypto) # ACK if space.ack_at is not None: builder.start_frame(QuicFrameType.ACK) push_ack_frame(buf, space.ack_queue, 0) space.ack_at = None # CRYPTO if not crypto_stream.send_buffer_is_empty: write_crypto_frame(builder=builder, space=space, stream=crypto_stream) + # PADDING (anti-deadlock packet) + if self._probe_pending and self._is_client and epoch == tls.Epoch.HANDSHAKE: + buf.push_bytes(bytes(builder.remaining_space)) + self._probe_pending = False + if not builder.end_packet(): break ===========changed ref 3=========== # module: aioquic.connection class QuicConnection: def _handle_crypto_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a CRYPTO frame. """ stream = self._crypto_streams[context.epoch] 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_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, ) ) </s>
aioquic.packet_builder/QuicPacketBuilder.start_packet
Modified
aiortc~aioquic
c365ee7ac070a33e21106ea936f953afe1bd7b80
[connection] ensure we can send one packet when probe is needed
<15>:<add> if self.max_flight_bytes is not None: <del> if self.max_flight_bytes is not None and not is_probe:
# module: aioquic.packet_builder class QuicPacketBuilder: - def start_packet( - self, packet_type: int, crypto: CryptoPair, is_probe=False - ) -> None: + def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: <0> """ <1> Starts a new packet. <2> """ <3> buf = self.buffer <4> self._ack_eliciting = False <5> <6> # if there is too little space remaining, start a new datagram <7> # FIXME: the limit is arbitrary! <8> packet_start = buf.tell() <9> if self._buffer_capacity - packet_start < 128: <10> self._flush_current_datagram() <11> packet_start = 0 <12> <13> # initialize datagram if needed <14> if self._datagram_init: <15> if self.max_flight_bytes is not None and not is_probe: <16> remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes <17> if remaining_flight_bytes < self._buffer_capacity: <18> self._buffer_capacity = remaining_flight_bytes <19> if self.max_total_bytes is not None: <20> remaining_total_bytes = self.max_total_bytes - self._total_bytes <21> if remaining_total_bytes < self._buffer_capacity: <22> self._buffer_capacity = remaining_total_bytes <23> self._datagram_init = False <24> <25> # calculate header size <26> packet_long_header = is_long_header(packet_type) <27> if packet_long_header: <28> header_size = 10 + len(self._peer_cid) + len(self._host_cid) <29> if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: <30> token_length = len(self._peer_token) <31> header_size += size_uint_var(token_length) + token_length <32> else: <33> header_size = 3 + len(self._peer_cid) </s>
===========below chunk 0=========== # module: aioquic.packet_builder class QuicPacketBuilder: - def start_packet( - self, packet_type: int, crypto: CryptoPair, is_probe=False - ) -> None: + def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: # offset: 1 # check we have enough space if packet_start + header_size >= self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if packet_type == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHAKE: epoch = Epoch.HANDSHAKE else: epoch = Epoch.ONE_RTT 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, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type buf.seek(self._packet_start + self._header_size) ===========unchanged ref 0=========== at: aioquic._buffer.Buffer seek(pos: int) -> None tell() -> int at: aioquic.buffer size_uint_var(value: int) -> int at: aioquic.crypto CryptoPair() at: aioquic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20 PACKET_TYPE_MASK = 0xF0 is_long_header(first_byte: int) -> bool at: aioquic.packet_builder QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field( default_factory=list )) QuicPacketBuilderStop(*args: object) at: aioquic.packet_builder.QuicPacketBuilder _flush_current_datagram() -> None at: aioquic.packet_builder.QuicPacketBuilder.__init__ self.max_flight_bytes: Optional[int] = None self.max_total_bytes: Optional[int] = None self._host_cid = host_cid self._peer_cid = peer_cid self._peer_token = peer_token self._ack_eliciting = False self._datagram_init = True self._flight_bytes = 0 self._total_bytes = 0 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) self._buffer_capacity = PACKET_MAX_SIZE at: aioquic.packet_builder.QuicPacketBuilder._flush_current_datagram self._datagram_init = True self._flight_bytes += datagram_bytes self._total_bytes += datagram_bytes at: aioquic.packet_builder.QuicPacketBuilder.end_packet self._packet_number += 1 self._packet = None at: aioquic.packet_builder.QuicPacketBuilder.start_frame self._ack_eliciting = True at: aioquic.packet_builder.QuicSentPacket epoch: Epoch in_flight: bool is_ack_eliciting: bool is_crypto_packet: bool packet_number: int sent_time: Optional[float] = None sent_bytes: int = 0 delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field( default_factory=list ) at: aioquic.tls Epoch()
aioquic.connection/QuicConnection.datagrams_to_send
Modified
aiortc~aioquic
c365ee7ac070a33e21106ea936f953afe1bd7b80
[connection] ensure we can send one packet when probe is needed
# module: aioquic.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> network_path = self._network_paths[0] <5> <6> if self._state in END_STATES: <7> return [] <8> <9> # build datagrams <10> builder = QuicPacketBuilder( <11> host_cid=self.host_cid, <12> packet_number=self._packet_number, <13> pad_first_datagram=( <14> self._is_client and self._state == QuicConnectionState.FIRSTFLIGHT <15> ), <16> peer_cid=self._peer_cid, <17> peer_token=self._peer_token, <18> spin_bit=self._spin_bit, <19> version=self._version, <20> ) <21> if self._close_pending: <22> for epoch, packet_type in ( <23> (tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT), <24> (tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE), <25> (tls.Epoch.INITIAL, PACKET_TYPE_INITIAL), <26> ): <27> crypto = self._cryptos[epoch] <28> if crypto.send.is_valid(): <29> builder.start_packet(packet_type, crypto) <30> write_close_frame( <31> builder=builder, <32> error_code=self._close_event.error_code, <33> frame_type=self._close_event.frame_type, <34> reason_phrase=self._close_event.reason_phrase, <35> ) <36> builder.end_packet() <37> self._close_pending = False <38> break <39> self._close_begin(is_initiator=True, now=now) <40> else: <41> # congestion control</s>
===========below chunk 0=========== # module: aioquic.connection class QuicConnection: def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]: # offset: 1 self._loss.congestion_window - self._loss.bytes_in_flight ) if not network_path.is_validated: # limit data on un-validated network paths 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 # 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: network_path.bytes_sent += len(datagram) ret.append((datagram, network_path.addr)) return ret ===========unchanged ref 0=========== at: aioquic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20, ] ) at: aioquic.connection NetworkAddress = Any 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.connection.QuicConnection _close_begin(is_initiator: bool, now: float) -> None _connect(now: float) -> None at: aioquic.connection.QuicConnection.__init__ self._configuration = configuration 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, send_probe=self._send_probe ) self._network_paths: List[QuicNetworkPath] = [] self._packet_number = 0 self._peer_cid = os.urandom(8) self._peer_token = b"" ===========unchanged ref 1=========== self._spin_bit = False self._state = QuicConnectionState.FIRSTFLIGHT self._version: Optional[int] = None self._close_pending = False self._probe_pending = False at: aioquic.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.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.connection.QuicConnection._send_probe self._probe_pending = True at: aioquic.connection.QuicConnection._set_state self._state = state at: aioquic.connection.QuicConnection._write_application self._probe_pending = False at: aioquic.connection.QuicConnection._write_handshake self._probe_pending = False at: aioquic.connection.QuicConnection.change_connection_id self._peer_cid = connection_id.cid at: aioquic.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.connection.QuicConnection.connect self._network_paths = [QuicNetworkPath(addr, is_validated=True)] ===========unchanged ref 2=========== at: aioquic.connection.QuicConnection.handle_timer self._close_event = events.ConnectionTerminated( error_code=QuicErrorCode.INTERNAL_ERROR, frame_type=None, reason_phrase="Idle timeout", ) at: aioquic.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", ) self._version = QuicProtocolVersion(header.version) self._version = QuicProtocolVersion(max(common)) self._peer_cid = header.source_cid self._peer_token = header.token self._network_paths = [network_path] self._spin_bit = self._spin_bit_peer self._spin_bit = not self._spin_bit_peer self.host_cid = context.host_cid at: aioquic.connection.QuicNetworkPath addr: NetworkAddress bytes_received: int = 0 bytes_sent: int = 0 is_validated: bool = False local_challenge: Optional[bytes] = None remote_challenge: Optional[bytes] = None at: aioquic.crypto.CryptoContext is_valid() -> bool at: aioquic.crypto.CryptoPair.__init__ self.send = CryptoContext() at: aioquic.events.ConnectionTerminated error_code: int frame_type: Optional[int] reason_phrase: str at: aioquic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20 PACKET_TYPE_ONE_RTT = PACKET_FIXED_BIT
aioquic.connection/QuicConnection._write_application
Modified
aiortc~aioquic
c365ee7ac070a33e21106ea936f953afe1bd7b80
[connection] ensure we can send one packet when probe is needed
<16>:<add> builder.start_packet(packet_type, crypto) <del> builder.start_packet(packet_type, crypto, is_probe=self._probe_pending)
# module: aioquic.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, is_probe=self._probe_pending) <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> # PATH CHALLENGE <30> if ( <31> not network_path.is_validated <32> and network_path.local_challenge is None <33> ): <34> self._logger.info( <35> "Network path %s sending challenge", network_path.addr <36> ) <37> network_path.local_challenge = os.urandom(8) <38> builder.start_frame(QuicFrameType.PATH_CHALLENG</s>
===========below chunk 0=========== # module: aioquic.connection class QuicConnection: def _write_application( self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float ) -> None: # offset: 1 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, 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_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(QuicFrame</s> ===========below chunk 1=========== # module: aioquic.connection class QuicConnection: def _write_application( self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float ) -> None: # offset: 2 <s>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.values(): # 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</s> ===========below chunk 2=========== # module: aioquic.connection class QuicConnection: def _write_application( self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float ) -> None: # offset: 3 <s>_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.connection write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None write_stream_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream, max_offset: int) -> int QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None) at: aioquic.connection.QuicConnection _on_ack_delivery(delivery: QuicDeliveryState, space: QuicPacketSpace, highest_acked: int) -> None _on_new_connection_id_delivery(delivery: QuicDeliveryState, connection_id: QuicConnectionId) -> None _on_ping_delivery(delivery: QuicDeliveryState, uids: Sequence[int]) -> None _on_retire_connection_id_delivery(delivery: QuicDeliveryState, sequence_number: int) -> None _write_connection_limits(builder: QuicPacketBuilder, space: QuicPacketSpace) -> None _write_stream_limits(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None at: aioquic.connection.QuicConnection.__init__ self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} self._events: Deque[events.Event] = deque() self._handshake_complete = False
aioquic.connection/QuicConnection._write_handshake
Modified
aiortc~aioquic
c365ee7ac070a33e21106ea936f953afe1bd7b80
[connection] ensure we can send one packet when probe is needed
<13>:<add> builder.start_packet(packet_type, crypto) <del> builder.start_packet(packet_type, crypto, is_probe=self._probe_pending)
# module: aioquic.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, is_probe=self._probe_pending) <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.connection write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None at: aioquic.connection.QuicConnection.__init__ self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} self._remote_max_data_used = 0 self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} at: aioquic.connection.QuicConnection._initialize self._cryptos = { tls.Epoch.INITIAL: CryptoPair(), tls.Epoch.ZERO_RTT: CryptoPair(), tls.Epoch.HANDSHAKE: CryptoPair(), tls.Epoch.ONE_RTT: CryptoPair(), } self._crypto_streams = { tls.Epoch.INITIAL: QuicStream(), tls.Epoch.HANDSHAKE: QuicStream(), tls.Epoch.ONE_RTT: QuicStream(), } self._spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } at: aioquic.connection.QuicConnection._write_application 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, ), ) at: aioquic.crypto.CryptoContext is_valid() -> bool at: aioquic.crypto.CryptoPair.__init__ self.send = CryptoContext() at: aioquic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 ===========unchanged ref 1=========== 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 at: aioquic.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) at: aioquic.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.packet_builder.QuicPacketBuilder.__init__ self.buffer = Buffer(PACKET_MAX_SIZE) at: aioquic.recovery.QuicPacketSpace.__init__ self.ack_at: Optional[float] = None self.ack_queue = RangeSet() at: aioquic.stream.QuicStream.__init__ self.send_buffer_is_empty = True at: aioquic.stream.QuicStream.get_frame self.send_buffer_is_empty = True at: aioquic.stream.QuicStream.on_data_delivery self.send_buffer_is_empty = False at: aioquic.stream.QuicStream.write self.send_buffer_is_empty = False at: aioquic.tls Epoch() ===========changed ref 0=========== # module: aioquic.packet_builder class QuicPacketBuilder: - def start_packet( - self, packet_type: int, crypto: CryptoPair, is_probe=False - ) -> None: + def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: """ Starts a new packet. """ buf = self.buffer self._ack_eliciting = False # if there is too little space remaining, start a new datagram # FIXME: the limit is arbitrary! packet_start = buf.tell() if self._buffer_capacity - packet_start < 128: self._flush_current_datagram() packet_start = 0 # initialize datagram if needed if self._datagram_init: + if self.max_flight_bytes is not None: - if self.max_flight_bytes is not None and not is_probe: remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes if remaining_flight_bytes < self._buffer_capacity: self._buffer_capacity = remaining_flight_bytes if self.max_total_bytes is not None: remaining_total_bytes = self.max_total_bytes - self._total_bytes if remaining_total_bytes < self._buffer_capacity: self._buffer_capacity = remaining_total_bytes self._datagram_init = False # calculate header size packet_long_header = is_long_header(packet_type) if packet_long_header: header_size = 10 + len(self._peer_cid) + len(self._host_cid) if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: token_length = len(self._peer_token) header_size += size_uint_var(token_length) + token_length else: header_size = 3 + len(self._peer_cid) # check we have enough space if packet_start + header_size</s> ===========changed ref 1=========== # module: aioquic.packet_builder class QuicPacketBuilder: - def start_packet( - self, packet_type: int, crypto: CryptoPair, is_probe=False - ) -> None: + def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: # offset: 1 <s> = 3 + len(self._peer_cid) # check we have enough space if packet_start + header_size >= self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if packet_type == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHAKE: epoch = Epoch.HANDSHAKE else: epoch = Epoch.ONE_RTT 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, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type buf.seek(self._packet_start + self._header_size)
examples.http3-server/HttpServer.__init__
Modified
aiortc~aioquic
f797370e721ad2f72a3366ac81e0e4df2136d691
[examples] wire up timers for HTTP/3 server example
<6>:<add> self._timer: Dict[QuicConnection, Tuple[asyncio.TimerHandle, float]] = {}
# module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def __init__( self, *, configuration: QuicConfiguration, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, ) -> None: <0> self._connections: Dict[bytes, QuicConnection] = {} <1> self._configuration = configuration <2> self._http: Dict[QuicConnection, HttpConnection] = {} <3> self._loop = asyncio.get_event_loop() <4> self._session_ticket_fetcher = session_ticket_fetcher <5> self._session_ticket_handler = session_ticket_handler <6> self._transport: Optional[asyncio.DatagramTransport] = None <7> <8> if stateless_retry: <9> self._retry = QuicRetryTokenHandler() <10> else: <11> self._retry = None <12>
===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_19, QuicProtocolVersion.DRAFT_20, ] )) at: aioquic.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.retry QuicRetryTokenHandler() at: aioquic.tls SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] at: asyncio.events TimerHandle(when: float, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop, context: Optional[Context]=...) get_event_loop() -> AbstractEventLoop at: asyncio.protocols DatagramProtocol() at: asyncio.transports DatagramTransport(extra: Optional[Mapping[Any, Any]]=...) at: examples.http3-server HttpConnection = Union[H0Connection, H3Connection] at: examples.http3-server.HttpServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: typing Tuple = _TupleType(tuple, -1, inst=False, name='Tuple') Dict = _alias(dict, 2, inst=False, name='Dict')
examples.http3-server/HttpServer._consume_events
Modified
aiortc~aioquic
f797370e721ad2f72a3366ac81e0e4df2136d691
[examples] wire up timers for HTTP/3 server example
<3>:<add> if isinstance(event, aioquic.events.ConnectionTerminated): <add> # remove the connection <add> for cid, conn in list(self._connections.items()): <add> if conn == connection: <add> del self._connections[cid] <add> self._http.pop(connection, None) <add> self._timer.pop(connection, None) <add> return <add> elif isinstance(event, aioquic.events.HandshakeCompleted): <del> if isinstance(event, aioquic.events.HandshakeCompleted): <27>:<del> """ <28>:<add> next_timer_at = connection.get_timer() <del> timer_at = connection.get_timer() <29>:<add> (timer, timer_at) = self._timer.get(connection, (None, None)) <add> if timer is not None and timer_at != next_timer_at: <del> if self._timer is not None and self._timer_at != timer_at: <30>:<add> timer.cancel() <del> self._timer.cancel() <31>:<add> timer = None <del> self._timer = None <32>:<add> if timer is None and timer_at is not None: <del> if self._timer is None and timer_at is not None: <33>:<add> timer = self._loop.call_at( <add> next_timer_at, partial(
# module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def _consume_events(self, connection: QuicConnection) -> None: <0> # process events <1> event = connection.next_event() <2> while event is not None: <3> if isinstance(event, aioquic.events.HandshakeCompleted): <4> if event.alpn_protocol == "h3-20": <5> self._http[connection] = H3Connection(connection) <6> elif event.alpn_protocol == "hq-20": <7> self._http[connection] = H0Connection(connection) <8> elif isinstance(event, aioquic.events.ConnectionIdIssued): <9> self._connections[event.connection_id] = connection <10> elif isinstance(event, aioquic.events.ConnectionIdRetired): <11> assert self._connections[event.connection_id] == connection <12> del self._connections[event.connection_id] <13> <14> #  pass event to the HTTP layer <15> http = self._http.get(connection) <16> if http is not None: <17> for http_event in http.handle_event(event): <18> handle_http_event(http, http_event) <19> <20> event = connection.next_event() <21> <22> # send datagrams <23> for data, addr in connection.datagrams_to_send(now=self._loop.time()): <24> self._transport.sendto(data, addr) <25> <26> # re-arm timer <27> """ <28> timer_at = connection.get_timer() <29> if self._timer is not None and self._timer_at != timer_at: <30> self._timer.cancel() <31> self._timer = None <32> if self._timer is None and timer_at is not None: <33> self._timer = self._loop.call_at(timer_at, self._handle_timer) <34> self._timer_at = timer_at <35> """ <36>
===========unchanged ref 0=========== at: aioquic.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.connection.QuicConnection datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] next_event() -> Optional[events.Event] at: aioquic.events ConnectionIdIssued(connection_id: bytes) ConnectionIdRetired(connection_id: bytes) ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str) HandshakeCompleted(alpn_protocol: Optional[str], early_data_accepted: bool, session_resumed: bool) at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection handle_event(event: aioquic.events.Event) -> List[Event] at: asyncio.events.AbstractEventLoop time() -> float at: asyncio.transports.DatagramTransport __slots__ = () sendto(data: Any, addr: Optional[_Address]=...) -> None at: examples.http3-server H0Connection(quic: QuicConnection) handle_http_event(connection: HttpConnection, event: aioquic.h3.events.Event) -> None at: examples.http3-server.H0Connection handle_event(event: aioquic.events.Event) at: examples.http3-server.HttpServer.__init__ self._connections: Dict[bytes, QuicConnection] = {} self._http: Dict[QuicConnection, HttpConnection] = {} self._loop = asyncio.get_event_loop() self._timer: Dict[QuicConnection, Tuple[asyncio.TimerHandle, float]] = {} ===========unchanged ref 1=========== self._transport: Optional[asyncio.DatagramTransport] = None at: examples.http3-server.HttpServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: examples.http3-server.HttpServer.datagram_received connection = self._connections.get(header.destination_cid, None) connection = QuicConnection( configuration=self._configuration, original_connection_id=original_connection_id, session_ticket_fetcher=self._session_ticket_fetcher, session_ticket_handler=self._session_ticket_handler, ) at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co] at: typing.MutableMapping pop(key: _KT) -> _VT pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T] ===========changed ref 0=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def __init__( self, *, configuration: QuicConfiguration, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, stateless_retry: bool = False, ) -> None: self._connections: Dict[bytes, QuicConnection] = {} self._configuration = configuration self._http: Dict[QuicConnection, HttpConnection] = {} self._loop = asyncio.get_event_loop() self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler + self._timer: Dict[QuicConnection, Tuple[asyncio.TimerHandle, float]] = {} self._transport: Optional[asyncio.DatagramTransport] = None if stateless_retry: self._retry = QuicRetryTokenHandler() else: self._retry = None
examples.client/run
Modified
aiortc~aioquic
c6e2fd76e359835b0e0ba12cd0486e613a0f962a
[examples] make HTTP/0.9 client take an URL
<0>:<add> # parse URL <add> parsed = urlparse(url) <add> assert parsed.scheme == "https", "Only HTTPS URLs are supported." <add> if ":" in parsed.netloc: <add> server_name, port_str = parsed.netloc.split(":") <add> port = int(port_str) <add> else: <add> server_name = parsed.netloc <add> port = 443 <add> <add> async with connect(server_name, port, **kwargs) as connection: <del> async with connect(host, port, **kwargs) as connection: <3>:<add> writer.write(("GET %s\r\n" % parsed.path).encode("utf8")) <del> writer.write(("GET %s\r\n" % path).encode("utf8"))
# module: examples.client + def run(url, **kwargs): - def run(host, port, path, **kwargs): <0> async with connect(host, port, **kwargs) as connection: <1> # perform HTTP/0.9 request <2> reader, writer = await connection.create_stream() <3> writer.write(("GET %s\r\n" % path).encode("utf8")) <4> writer.write_eof() <5> <6> start = time.time() <7> response = await reader.read() <8> elapsed = time.time() - start <9> print(response.decode("utf8")) <10> <11> octets = len(response) <12> logger.info( <13> "Received %d bytes in %.1f s (%.3f Mbps)" <14> % (octets, elapsed, octets * 8 / elapsed / 1000000) <15> ) <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, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] at: aioquic.asyncio.protocol.QuicConnectionProtocol create_stream(is_unidirectional: bool=False) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter] at: asyncio.streams.StreamWriter write(data: bytes) -> None write_eof() -> None 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 if __name__ == "__main__": parser = argparse.ArgumentParser(description="HTTP/3 client") + parser.add_argument("url", type=str, help="the URL to query (must be HTTPS)") - parser.add_argument("url", type=str, help="the server's host name or address") parser.add_argument( "-l", "--secrets-log", type=str, help="log secrets to a file, for use with Wireshark", ) parser.add_argument( "-s", "--session-ticket", type=str, help="read and write session ticket from the specified file", ) parser.add_argument( "-v", "--verbose", action="store_true", help="increase logging verbosity" ) args = parser.parse_args() logging.basicConfig( format="%(asctime)s %(levelname)s %(name)s %(message)s", level=logging.DEBUG if args.verbose else logging.INFO, ) # open SSL log file if args.secrets_log: secrets_log_file = open(args.secrets_log, "a") else: secrets_log_file = None # load session ticket session_ticket = None if args.session_ticket: try: with open(args.session_ticket, "rb") as fp: session_ticket = pickle.load(fp) except FileNotFoundError: pass run(url=args.url, secrets_log_file=secrets_log_file, session_ticket=session_ticket)
aioquic.packet/pull_quic_header
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<7>:<del> cid_lengths = buf.pull_uint8() <9>:<add> destination_cid_length = buf.pull_uint8() <del> destination_cid_length = decode_cid_length(cid_lengths // 16) <12>:<add> source_cid_length = buf.pull_uint8() <del> source_cid_length = decode_cid_length(cid_lengths % 16) <29>:<add> original_destination_cid_length = buf.pull_uint8() <del> original_destination_cid_length = decode_cid_length(first_byte & 0xF)
# module: aioquic.packet def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader: <0> first_byte = buf.pull_uint8() <1> <2> original_destination_cid = b"" <3> token = b"" <4> if is_long_header(first_byte): <5> # long header packet <6> version = buf.pull_uint32() <7> cid_lengths = buf.pull_uint8() <8> <9> destination_cid_length = decode_cid_length(cid_lengths // 16) <10> destination_cid = buf.pull_bytes(destination_cid_length) <11> <12> source_cid_length = decode_cid_length(cid_lengths % 16) <13> source_cid = buf.pull_bytes(source_cid_length) <14> <15> if version == QuicProtocolVersion.NEGOTIATION: <16> # version negotiation <17> packet_type = None <18> rest_length = buf.capacity - buf.tell() <19> else: <20> if not (first_byte & PACKET_FIXED_BIT): <21> raise ValueError("Packet fixed bit is zero") <22> <23> packet_type = first_byte & PACKET_TYPE_MASK <24> if packet_type == PACKET_TYPE_INITIAL: <25> token_length = buf.pull_uint_var() <26> token = buf.pull_bytes(token_length) <27> rest_length = buf.pull_uint_var() <28> elif packet_type == PACKET_TYPE_RETRY: <29> original_destination_cid_length = decode_cid_length(first_byte & 0xF) <30> original_destination_cid = buf.pull_bytes( <31> original_destination_cid_length <32> ) <33> token = buf.pull_bytes(buf.capacity - buf.tell()) <34> rest_length = 0 <35> else: <36> rest_length = buf.pull_uint_var() <37> <38> return QuicHeader( <39> is_long_header=True, <40> version=version, </s>
===========below chunk 0=========== # module: aioquic.packet def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader: # offset: 1 destination_cid=destination_cid, source_cid=source_cid, original_destination_cid=original_destination_cid, token=token, rest_length=rest_length, ) else: # short header packet if not (first_byte & PACKET_FIXED_BIT): raise ValueError("Packet fixed bit is zero") packet_type = first_byte & PACKET_TYPE_MASK destination_cid = buf.pull_bytes(host_cid_length) return QuicHeader( is_long_header=False, version=None, packet_type=packet_type, destination_cid=destination_cid, source_cid=b"", token=b"", rest_length=buf.capacity - buf.tell(), ) ===========unchanged ref 0=========== at: aioquic._buffer.Buffer tell() -> int pull_bytes(length: int) -> bytes pull_uint8() -> int pull_uint32() -> int pull_uint_var() -> int at: aioquic.packet PACKET_FIXED_BIT = 0x40 PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 PACKET_TYPE_RETRY = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x30 PACKET_TYPE_MASK = 0xF0 QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicHeader(is_long_header: bool, version: Optional[int], packet_type: int, destination_cid: bytes, source_cid: bytes, original_destination_cid: bytes=b"", token: bytes=b"", rest_length: int=0) at: aioquic.packet.QuicHeader is_long_header: bool version: Optional[int] packet_type: int destination_cid: bytes source_cid: bytes original_destination_cid: bytes = b"" token: bytes = b"" rest_length: int = 0 at: aioquic.packet.pull_quic_header first_byte = buf.pull_uint8() ===========changed ref 0=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 1=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 2=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 -
aioquic.packet/encode_quic_retry
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<1>:<add> capacity=8 <del> capacity=6 <7>:<add> buf.push_uint8(PACKET_TYPE_RETRY) <del> buf.push_uint8(PACKET_TYPE_RETRY | encode_cid_length(len(original_destination_cid))) <9>:<del> buf.push_uint8( <10>:<del> (encode_cid_length(len(destination_cid)) << 4) <11>:<del> | encode_cid_length(len(source_cid)) <12>:<del> ) <13>:<add> buf.push_uint8(len(destination_cid)) <14>:<add> buf.push_uint8(len(source_cid)) <15>:<add> buf.push_uint8(len(original_destination_cid))
# module: aioquic.packet def encode_quic_retry( version: int, source_cid: bytes, destination_cid: bytes, original_destination_cid: bytes, retry_token: bytes, ) -> bytes: <0> buf = Buffer( <1> capacity=6 <2> + len(destination_cid) <3> + len(source_cid) <4> + len(original_destination_cid) <5> + len(retry_token) <6> ) <7> buf.push_uint8(PACKET_TYPE_RETRY | encode_cid_length(len(original_destination_cid))) <8> buf.push_uint32(version) <9> buf.push_uint8( <10> (encode_cid_length(len(destination_cid)) << 4) <11> | encode_cid_length(len(source_cid)) <12> ) <13> buf.push_bytes(destination_cid) <14> buf.push_bytes(source_cid) <15> buf.push_bytes(original_destination_cid) <16> buf.push_bytes(retry_token) <17> return buf.data <18>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer push_bytes(value: bytes) -> None push_uint8(value: int) -> None push_uint32(v: int) -> None at: aioquic.packet PACKET_TYPE_RETRY = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x30 QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 1=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 2=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 3=========== # module: aioquic.packet def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader: first_byte = buf.pull_uint8() original_destination_cid = b"" token = b"" if is_long_header(first_byte): # long header packet version = buf.pull_uint32() - cid_lengths = buf.pull_uint8() + destination_cid_length = buf.pull_uint8() - destination_cid_length = decode_cid_length(cid_lengths // 16) destination_cid = buf.pull_bytes(destination_cid_length) + source_cid_length = buf.pull_uint8() - source_cid_length = decode_cid_length(cid_lengths % 16) source_cid = buf.pull_bytes(source_cid_length) if version == QuicProtocolVersion.NEGOTIATION: # version negotiation packet_type = None rest_length = buf.capacity - buf.tell() else: if not (first_byte & PACKET_FIXED_BIT): raise ValueError("Packet fixed bit is zero") packet_type = first_byte & PACKET_TYPE_MASK if packet_type == PACKET_TYPE_INITIAL: token_length = buf.pull_uint_var() token = buf.pull_bytes(token_length) rest_length = buf.pull_uint_var() elif packet_type == PACKET_TYPE_RETRY: + original_destination_cid_length = buf.pull_uint8() - original_destination_cid_length = decode_cid_length(first_byte & 0xF) original_destination_cid = buf.pull_bytes( original_destination_cid_length ) token = buf.pull_bytes(buf.capacity - buf.tell()) rest_length = 0 else: rest_length = buf.pull_uint_var() return QuicHeader( is_</s> ===========changed ref 4=========== # module: aioquic.packet def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader: # offset: 1 <s> else: rest_length = buf.pull_uint_var() return QuicHeader( is_long_header=True, version=version, packet_type=packet_type, destination_cid=destination_cid, source_cid=source_cid, original_destination_cid=original_destination_cid, token=token, rest_length=rest_length, ) else: # short header packet if not (first_byte & PACKET_FIXED_BIT): raise ValueError("Packet fixed bit is zero") packet_type = first_byte & PACKET_TYPE_MASK destination_cid = buf.pull_bytes(host_cid_length) return QuicHeader( is_long_header=False, version=None, packet_type=packet_type, destination_cid=destination_cid, source_cid=b"", token=b"", rest_length=buf.capacity - buf.tell(), )
aioquic.packet/encode_quic_version_negotiation
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<1>:<add> capacity=7 <del> capacity=6 <8>:<del> buf.push_uint8( <9>:<del> (encode_cid_length(len(destination_cid)) << 4) <10>:<del> | encode_cid_length(len(source_cid)) <11>:<del> ) <12>:<add> buf.push_uint8(len(destination_cid)) <13>:<add> buf.push_uint8(len(source_cid))
# module: aioquic.packet def encode_quic_version_negotiation( source_cid: bytes, destination_cid: bytes, supported_versions: List[QuicProtocolVersion], ) -> bytes: <0> buf = Buffer( <1> capacity=6 <2> + len(destination_cid) <3> + len(source_cid) <4> + 4 * len(supported_versions) <5> ) <6> buf.push_uint8(os.urandom(1)[0] | PACKET_LONG_HEADER) <7> buf.push_uint32(QuicProtocolVersion.NEGOTIATION) <8> buf.push_uint8( <9> (encode_cid_length(len(destination_cid)) << 4) <10> | encode_cid_length(len(source_cid)) <11> ) <12> buf.push_bytes(destination_cid) <13> buf.push_bytes(source_cid) <14> for version in supported_versions: <15> buf.push_uint32(version) <16> return buf.data <17>
===========unchanged ref 0=========== at: aioquic._buffer.Buffer push_bytes(value: bytes) -> None push_uint8(value: int) -> None push_uint32(v: int) -> None at: aioquic.packet PACKET_LONG_HEADER = 0x80 QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: aioquic.packet.QuicTransportParameters 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 at: aioquic.packet.encode_quic_version_negotiation buf = Buffer( capacity=7 + len(destination_cid) + len(source_cid) + 4 * len(supported_versions) ) ===========unchanged ref 1=========== at: dataclasses field(*, default_factory: Callable[[], _T], init: bool=..., repr: bool=..., hash: Optional[bool]=..., compare: bool=..., metadata: Optional[Mapping[str, Any]]=...) -> _T field(*, init: bool=..., repr: bool=..., hash: Optional[bool]=..., compare: bool=..., metadata: Optional[Mapping[str, Any]]=...) -> Any field(*, default: _T, init: bool=..., repr: bool=..., hash: Optional[bool]=..., compare: bool=..., metadata: Optional[Mapping[str, Any]]=...) -> _T dataclass(*, init: bool=..., repr: bool=..., eq: bool=..., order: bool=..., unsafe_hash: bool=..., frozen: bool=...) -> Callable[[Type[_T]], Type[_T]] dataclass(_cls: None) -> Callable[[Type[_T]], Type[_T]] dataclass(_cls: Type[_T]) -> Type[_T] at: os urandom(size: int, /) -> bytes at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 1=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 2=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 3=========== # module: aioquic.packet def encode_quic_retry( version: int, source_cid: bytes, destination_cid: bytes, original_destination_cid: bytes, retry_token: bytes, ) -> bytes: buf = Buffer( + capacity=8 - capacity=6 + len(destination_cid) + len(source_cid) + len(original_destination_cid) + len(retry_token) ) + buf.push_uint8(PACKET_TYPE_RETRY) - buf.push_uint8(PACKET_TYPE_RETRY | encode_cid_length(len(original_destination_cid))) buf.push_uint32(version) - buf.push_uint8( - (encode_cid_length(len(destination_cid)) << 4) - | encode_cid_length(len(source_cid)) - ) + buf.push_uint8(len(destination_cid)) buf.push_bytes(destination_cid) + buf.push_uint8(len(source_cid)) buf.push_bytes(source_cid) + buf.push_uint8(len(original_destination_cid)) buf.push_bytes(original_destination_cid) buf.push_bytes(retry_token) return buf.data ===========changed ref 4=========== # module: aioquic.packet def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader: first_byte = buf.pull_uint8() original_destination_cid = b"" token = b"" if is_long_header(first_byte): # long header packet version = buf.pull_uint32() - cid_lengths = buf.pull_uint8() + destination_cid_length = buf.pull_uint8() - destination_cid_length = decode_cid_length(cid_lengths // 16) destination_cid = buf.pull_bytes(destination_cid_length) + source_cid_length = buf.pull_uint8() - source_cid_length = decode_cid_length(cid_lengths % 16) source_cid = buf.pull_bytes(source_cid_length) if version == QuicProtocolVersion.NEGOTIATION: # version negotiation packet_type = None rest_length = buf.capacity - buf.tell() else: if not (first_byte & PACKET_FIXED_BIT): raise ValueError("Packet fixed bit is zero") packet_type = first_byte & PACKET_TYPE_MASK if packet_type == PACKET_TYPE_INITIAL: token_length = buf.pull_uint_var() token = buf.pull_bytes(token_length) rest_length = buf.pull_uint_var() elif packet_type == PACKET_TYPE_RETRY: + original_destination_cid_length = buf.pull_uint8() - original_destination_cid_length = decode_cid_length(first_byte & 0xF) original_destination_cid = buf.pull_bytes( original_destination_cid_length ) token = buf.pull_bytes(buf.capacity - buf.tell()) rest_length = 0 else: rest_length = buf.pull_uint_var() return QuicHeader( is_</s>
aioquic.packet/pull_new_connection_id_frame
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<1>:<add> retire_prior_to = buf.pull_uint_var() <4>:<add> return (sequence_number, retire_prior_to, connection_id, stateless_reset_token) <del> return (sequence_number, connection_id, stateless_reset_token)
# module: aioquic.packet + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]: - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, bytes, bytes]: <0> sequence_number = buf.pull_uint_var() <1> length = buf.pull_uint8() <2> connection_id = buf.pull_bytes(length) <3> stateless_reset_token = buf.pull_bytes(16) <4> return (sequence_number, connection_id, stateless_reset_token) <5>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) ===========changed ref 0=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 1=========== # module: aioquic.packet PARAMS = [ ("original_connection_id", bytes), ("idle_timeout", int), ("stateless_reset_token", bytes), ("max_packet_size", int), ("initial_max_data", int), ("initial_max_stream_data_bidi_local", int), ("initial_max_stream_data_bidi_remote", int), ("initial_max_stream_data_uni", int), ("initial_max_streams_bidi", int), ("initial_max_streams_uni", int), ("ack_delay_exponent", int), ("max_ack_delay", int), ("disable_migration", bool), ("preferred_address", bytes), + ("active_connection_id_limit", int), ] ===========changed ref 2=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 3=========== # module: aioquic.packet def encode_quic_version_negotiation( source_cid: bytes, destination_cid: bytes, supported_versions: List[QuicProtocolVersion], ) -> bytes: buf = Buffer( + capacity=7 - capacity=6 + len(destination_cid) + len(source_cid) + 4 * len(supported_versions) ) buf.push_uint8(os.urandom(1)[0] | PACKET_LONG_HEADER) buf.push_uint32(QuicProtocolVersion.NEGOTIATION) - buf.push_uint8( - (encode_cid_length(len(destination_cid)) << 4) - | encode_cid_length(len(source_cid)) - ) + buf.push_uint8(len(destination_cid)) buf.push_bytes(destination_cid) + buf.push_uint8(len(source_cid)) buf.push_bytes(source_cid) for version in supported_versions: buf.push_uint32(version) return buf.data ===========changed ref 4=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 5=========== # module: aioquic.packet # TLS EXTENSION @dataclass class 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 ===========changed ref 6=========== # module: aioquic.packet def encode_quic_retry( version: int, source_cid: bytes, destination_cid: bytes, original_destination_cid: bytes, retry_token: bytes, ) -> bytes: buf = Buffer( + capacity=8 - capacity=6 + len(destination_cid) + len(source_cid) + len(original_destination_cid) + len(retry_token) ) + buf.push_uint8(PACKET_TYPE_RETRY) - buf.push_uint8(PACKET_TYPE_RETRY | encode_cid_length(len(original_destination_cid))) buf.push_uint32(version) - buf.push_uint8( - (encode_cid_length(len(destination_cid)) << 4) - | encode_cid_length(len(source_cid)) - ) + buf.push_uint8(len(destination_cid)) buf.push_bytes(destination_cid) + buf.push_uint8(len(source_cid)) buf.push_bytes(source_cid) + buf.push_uint8(len(original_destination_cid)) buf.push_bytes(original_destination_cid) buf.push_bytes(retry_token) return buf.data ===========changed ref 7=========== # module: aioquic.packet def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader: first_byte = buf.pull_uint8() original_destination_cid = b"" token = b"" if is_long_header(first_byte): # long header packet version = buf.pull_uint32() - cid_lengths = buf.pull_uint8() + destination_cid_length = buf.pull_uint8() - destination_cid_length = decode_cid_length(cid_lengths // 16) destination_cid = buf.pull_bytes(destination_cid_length) + source_cid_length = buf.pull_uint8() - source_cid_length = decode_cid_length(cid_lengths % 16) source_cid = buf.pull_bytes(source_cid_length) if version == QuicProtocolVersion.NEGOTIATION: # version negotiation packet_type = None rest_length = buf.capacity - buf.tell() else: if not (first_byte & PACKET_FIXED_BIT): raise ValueError("Packet fixed bit is zero") packet_type = first_byte & PACKET_TYPE_MASK if packet_type == PACKET_TYPE_INITIAL: token_length = buf.pull_uint_var() token = buf.pull_bytes(token_length) rest_length = buf.pull_uint_var() elif packet_type == PACKET_TYPE_RETRY: + original_destination_cid_length = buf.pull_uint8() - original_destination_cid_length = decode_cid_length(first_byte & 0xF) original_destination_cid = buf.pull_bytes( original_destination_cid_length ) token = buf.pull_bytes(buf.capacity - buf.tell()) rest_length = 0 else: rest_length = buf.pull_uint_var() return QuicHeader( is_</s>
aioquic.packet/push_new_connection_id_frame
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<2>:<add> buf.push_uint_var(retire_prior_to)
# module: aioquic.packet def push_new_connection_id_frame( buf: Buffer, sequence_number: int, + retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes, ) -> None: <0> assert len(stateless_reset_token) == 16 <1> buf.push_uint_var(sequence_number) <2> buf.push_uint8(len(connection_id)) <3> buf.push_bytes(connection_id) <4> buf.push_bytes(stateless_reset_token) <5>
===========unchanged ref 0=========== at: aioquic._buffer.Buffer push_bytes(value: bytes) -> None push_uint8(value: int) -> None push_uint_var(value: int) -> None ===========changed ref 0=========== # module: aioquic.packet + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]: - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[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 (sequence_number, retire_prior_to, connection_id, stateless_reset_token) - return (sequence_number, connection_id, stateless_reset_token) ===========changed ref 1=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 2=========== # module: aioquic.packet PARAMS = [ ("original_connection_id", bytes), ("idle_timeout", int), ("stateless_reset_token", bytes), ("max_packet_size", int), ("initial_max_data", int), ("initial_max_stream_data_bidi_local", int), ("initial_max_stream_data_bidi_remote", int), ("initial_max_stream_data_uni", int), ("initial_max_streams_bidi", int), ("initial_max_streams_uni", int), ("ack_delay_exponent", int), ("max_ack_delay", int), ("disable_migration", bool), ("preferred_address", bytes), + ("active_connection_id_limit", int), ] ===========changed ref 3=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 4=========== # module: aioquic.packet def encode_quic_version_negotiation( source_cid: bytes, destination_cid: bytes, supported_versions: List[QuicProtocolVersion], ) -> bytes: buf = Buffer( + capacity=7 - capacity=6 + len(destination_cid) + len(source_cid) + 4 * len(supported_versions) ) buf.push_uint8(os.urandom(1)[0] | PACKET_LONG_HEADER) buf.push_uint32(QuicProtocolVersion.NEGOTIATION) - buf.push_uint8( - (encode_cid_length(len(destination_cid)) << 4) - | encode_cid_length(len(source_cid)) - ) + buf.push_uint8(len(destination_cid)) buf.push_bytes(destination_cid) + buf.push_uint8(len(source_cid)) buf.push_bytes(source_cid) for version in supported_versions: buf.push_uint32(version) return buf.data ===========changed ref 5=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 6=========== # module: aioquic.packet # TLS EXTENSION @dataclass class 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 ===========changed ref 7=========== # module: aioquic.packet def encode_quic_retry( version: int, source_cid: bytes, destination_cid: bytes, original_destination_cid: bytes, retry_token: bytes, ) -> bytes: buf = Buffer( + capacity=8 - capacity=6 + len(destination_cid) + len(source_cid) + len(original_destination_cid) + len(retry_token) ) + buf.push_uint8(PACKET_TYPE_RETRY) - buf.push_uint8(PACKET_TYPE_RETRY | encode_cid_length(len(original_destination_cid))) buf.push_uint32(version) - buf.push_uint8( - (encode_cid_length(len(destination_cid)) << 4) - | encode_cid_length(len(source_cid)) - ) + buf.push_uint8(len(destination_cid)) buf.push_bytes(destination_cid) + buf.push_uint8(len(source_cid)) buf.push_bytes(source_cid) + buf.push_uint8(len(original_destination_cid)) buf.push_bytes(original_destination_cid) buf.push_bytes(retry_token) return buf.data
aioquic.packet/pull_transport_close_frame
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<0>:<add> error_code = buf.pull_uint_var() <del> error_code = buf.pull_uint16()
# module: aioquic.packet def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]: <0> error_code = buf.pull_uint16() <1> frame_type = buf.pull_uint_var() <2> reason_length = buf.pull_uint_var() <3> reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) <4> return (error_code, frame_type, reason_phrase) <5>
===========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.packet.pull_transport_close_frame error_code = buf.pull_uint_var() frame_type = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) at: typing Tuple = _TupleType(tuple, -1, inst=False, name='Tuple') ===========changed ref 0=========== # module: aioquic.packet def push_new_connection_id_frame( buf: Buffer, sequence_number: int, + retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes, ) -> None: assert len(stateless_reset_token) == 16 buf.push_uint_var(sequence_number) + buf.push_uint_var(retire_prior_to) buf.push_uint8(len(connection_id)) buf.push_bytes(connection_id) buf.push_bytes(stateless_reset_token) ===========changed ref 1=========== # module: aioquic.packet + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]: - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[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 (sequence_number, retire_prior_to, connection_id, stateless_reset_token) - return (sequence_number, connection_id, stateless_reset_token) ===========changed ref 2=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 3=========== # module: aioquic.packet PARAMS = [ ("original_connection_id", bytes), ("idle_timeout", int), ("stateless_reset_token", bytes), ("max_packet_size", int), ("initial_max_data", int), ("initial_max_stream_data_bidi_local", int), ("initial_max_stream_data_bidi_remote", int), ("initial_max_stream_data_uni", int), ("initial_max_streams_bidi", int), ("initial_max_streams_uni", int), ("ack_delay_exponent", int), ("max_ack_delay", int), ("disable_migration", bool), ("preferred_address", bytes), + ("active_connection_id_limit", int), ] ===========changed ref 4=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 5=========== # module: aioquic.packet def encode_quic_version_negotiation( source_cid: bytes, destination_cid: bytes, supported_versions: List[QuicProtocolVersion], ) -> bytes: buf = Buffer( + capacity=7 - capacity=6 + len(destination_cid) + len(source_cid) + 4 * len(supported_versions) ) buf.push_uint8(os.urandom(1)[0] | PACKET_LONG_HEADER) buf.push_uint32(QuicProtocolVersion.NEGOTIATION) - buf.push_uint8( - (encode_cid_length(len(destination_cid)) << 4) - | encode_cid_length(len(source_cid)) - ) + buf.push_uint8(len(destination_cid)) buf.push_bytes(destination_cid) + buf.push_uint8(len(source_cid)) buf.push_bytes(source_cid) for version in supported_versions: buf.push_uint32(version) return buf.data ===========changed ref 6=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 7=========== # module: aioquic.packet # TLS EXTENSION @dataclass class 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 ===========changed ref 8=========== # module: aioquic.packet def encode_quic_retry( version: int, source_cid: bytes, destination_cid: bytes, original_destination_cid: bytes, retry_token: bytes, ) -> bytes: buf = Buffer( + capacity=8 - capacity=6 + len(destination_cid) + len(source_cid) + len(original_destination_cid) + len(retry_token) ) + buf.push_uint8(PACKET_TYPE_RETRY) - buf.push_uint8(PACKET_TYPE_RETRY | encode_cid_length(len(original_destination_cid))) buf.push_uint32(version) - buf.push_uint8( - (encode_cid_length(len(destination_cid)) << 4) - | encode_cid_length(len(source_cid)) - ) + buf.push_uint8(len(destination_cid)) buf.push_bytes(destination_cid) + buf.push_uint8(len(source_cid)) buf.push_bytes(source_cid) + buf.push_uint8(len(original_destination_cid)) buf.push_bytes(original_destination_cid) buf.push_bytes(retry_token) return buf.data
aioquic.packet/pull_application_close_frame
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<0>:<add> error_code = buf.pull_uint_var() <del> error_code = buf.pull_uint16()
# module: aioquic.packet def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]: <0> error_code = buf.pull_uint16() <1> reason_length = buf.pull_uint_var() <2> reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) <3> return (error_code, reason_phrase) <4>
===========changed ref 0=========== # module: aioquic.packet def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() frame_type = buf.pull_uint_var() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, frame_type, reason_phrase) ===========changed ref 1=========== # module: aioquic.packet def push_new_connection_id_frame( buf: Buffer, sequence_number: int, + retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes, ) -> None: assert len(stateless_reset_token) == 16 buf.push_uint_var(sequence_number) + buf.push_uint_var(retire_prior_to) buf.push_uint8(len(connection_id)) buf.push_bytes(connection_id) buf.push_bytes(stateless_reset_token) ===========changed ref 2=========== # module: aioquic.packet + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]: - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[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 (sequence_number, retire_prior_to, connection_id, stateless_reset_token) - return (sequence_number, connection_id, stateless_reset_token) ===========changed ref 3=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 4=========== # module: aioquic.packet PARAMS = [ ("original_connection_id", bytes), ("idle_timeout", int), ("stateless_reset_token", bytes), ("max_packet_size", int), ("initial_max_data", int), ("initial_max_stream_data_bidi_local", int), ("initial_max_stream_data_bidi_remote", int), ("initial_max_stream_data_uni", int), ("initial_max_streams_bidi", int), ("initial_max_streams_uni", int), ("ack_delay_exponent", int), ("max_ack_delay", int), ("disable_migration", bool), ("preferred_address", bytes), + ("active_connection_id_limit", int), ] ===========changed ref 5=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 6=========== # module: aioquic.packet def encode_quic_version_negotiation( source_cid: bytes, destination_cid: bytes, supported_versions: List[QuicProtocolVersion], ) -> bytes: buf = Buffer( + capacity=7 - capacity=6 + len(destination_cid) + len(source_cid) + 4 * len(supported_versions) ) buf.push_uint8(os.urandom(1)[0] | PACKET_LONG_HEADER) buf.push_uint32(QuicProtocolVersion.NEGOTIATION) - buf.push_uint8( - (encode_cid_length(len(destination_cid)) << 4) - | encode_cid_length(len(source_cid)) - ) + buf.push_uint8(len(destination_cid)) buf.push_bytes(destination_cid) + buf.push_uint8(len(source_cid)) buf.push_bytes(source_cid) for version in supported_versions: buf.push_uint32(version) return buf.data ===========changed ref 7=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 8=========== # module: aioquic.packet # TLS EXTENSION @dataclass class 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 ===========changed ref 9=========== # module: aioquic.packet def encode_quic_retry( version: int, source_cid: bytes, destination_cid: bytes, original_destination_cid: bytes, retry_token: bytes, ) -> bytes: buf = Buffer( + capacity=8 - capacity=6 + len(destination_cid) + len(source_cid) + len(original_destination_cid) + len(retry_token) ) + buf.push_uint8(PACKET_TYPE_RETRY) - buf.push_uint8(PACKET_TYPE_RETRY | encode_cid_length(len(original_destination_cid))) buf.push_uint32(version) - buf.push_uint8( - (encode_cid_length(len(destination_cid)) << 4) - | encode_cid_length(len(source_cid)) - ) + buf.push_uint8(len(destination_cid)) buf.push_bytes(destination_cid) + buf.push_uint8(len(source_cid)) buf.push_bytes(source_cid) + buf.push_uint8(len(original_destination_cid)) buf.push_bytes(original_destination_cid) buf.push_bytes(retry_token) return buf.data
aioquic.packet_builder/QuicPacketBuilder.start_packet
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<28>:<add> header_size = 11 + len(self._peer_cid) + len(self._host_cid) <del> header_size = 10 + len(self._peer_cid) + len(self._host_cid)
# module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: <0> """ <1> Starts a new packet. <2> """ <3> buf = self.buffer <4> self._ack_eliciting = False <5> <6> # if there is too little space remaining, start a new datagram <7> # FIXME: the limit is arbitrary! <8> packet_start = buf.tell() <9> if self._buffer_capacity - packet_start < 128: <10> self._flush_current_datagram() <11> packet_start = 0 <12> <13> # initialize datagram if needed <14> if self._datagram_init: <15> if self.max_flight_bytes is not None: <16> remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes <17> if remaining_flight_bytes < self._buffer_capacity: <18> self._buffer_capacity = remaining_flight_bytes <19> if self.max_total_bytes is not None: <20> remaining_total_bytes = self.max_total_bytes - self._total_bytes <21> if remaining_total_bytes < self._buffer_capacity: <22> self._buffer_capacity = remaining_total_bytes <23> self._datagram_init = False <24> <25> # calculate header size <26> packet_long_header = is_long_header(packet_type) <27> if packet_long_header: <28> header_size = 10 + len(self._peer_cid) + len(self._host_cid) <29> if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: <30> token_length = len(self._peer_token) <31> header_size += size_uint_var(token_length) + token_length <32> else: <33> header_size = 3 + len(self._peer_cid) <34> <35> # check we have enough space <36> if packet_start + header_size >= self._buffer_capacity: <37> raise QuicPacketBuilderStop <38> <39> </s>
===========below chunk 0=========== # module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: # offset: 1 if packet_type == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHAKE: epoch = Epoch.HANDSHAKE else: epoch = Epoch.ONE_RTT 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, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type buf.seek(self._packet_start + self._header_size) ===========unchanged ref 0=========== at: aioquic._buffer.Buffer seek(pos: int) -> None tell() -> int at: aioquic.buffer size_uint_var(value: int) -> int at: aioquic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20 PACKET_TYPE_MASK = 0xF0 is_long_header(first_byte: int) -> bool at: aioquic.packet_builder QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field( default_factory=list )) QuicPacketBuilderStop(*args: object) at: aioquic.packet_builder.QuicPacketBuilder _flush_current_datagram() -> None _flush_current_datagram(self) -> None at: aioquic.packet_builder.QuicPacketBuilder.__init__ self.max_flight_bytes: Optional[int] = None self.max_total_bytes: Optional[int] = None self._host_cid = host_cid self._peer_cid = peer_cid self._peer_token = peer_token self._ack_eliciting = False self._datagram_init = True self._flight_bytes = 0 self._total_bytes = 0 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) self._buffer_capacity = PACKET_MAX_SIZE at: aioquic.packet_builder.QuicPacketBuilder._flush_current_datagram self._datagram_init = True self._flight_bytes += datagram_bytes self._total_bytes += datagram_bytes at: aioquic.packet_builder.QuicPacketBuilder.end_packet self._packet_number += 1 self._packet = None at: aioquic.packet_builder.QuicPacketBuilder.start_frame self._ack_eliciting = True at: aioquic.packet_builder.QuicSentPacket epoch: Epoch in_flight: bool is_ack_eliciting: bool is_crypto_packet: bool packet_number: int sent_time: Optional[float] = None sent_bytes: int = 0 delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field( default_factory=list ) at: aioquic.tls Epoch() ===========changed ref 0=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 1=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 2=========== # module: aioquic.packet def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, reason_phrase) ===========changed ref 3=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 4=========== # module: aioquic.packet def push_new_connection_id_frame( buf: Buffer, sequence_number: int, + retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes, ) -> None: assert len(stateless_reset_token) == 16 buf.push_uint_var(sequence_number) + buf.push_uint_var(retire_prior_to) buf.push_uint8(len(connection_id)) buf.push_bytes(connection_id) buf.push_bytes(stateless_reset_token) ===========changed ref 5=========== # module: aioquic.packet def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() frame_type = buf.pull_uint_var() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, frame_type, reason_phrase) ===========changed ref 6=========== # module: aioquic.packet + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]: - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[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 (sequence_number, retire_prior_to, connection_id, stateless_reset_token) - return (sequence_number, connection_id, stateless_reset_token)
aioquic.packet_builder/QuicPacketBuilder.end_packet
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<29>:<add> buf.push_uint8(len(self._peer_cid)) <del> buf.push_uint8( <30>:<del> (encode_cid_length(len(self._peer_cid)) << 4) <31>:<del> | encode_cid_length(len(self._host_cid)) <32>:<del> ) <34>:<add> buf.push_uint8(len(self._host_cid))
# module: aioquic.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( <30> (encode_cid_length(len(self._peer_cid)) << 4) <31> | encode_cid_length(len(self._host_cid)) <32> ) <33> buf.push_bytes(self._peer_cid) <34> buf.push_bytes(self._host_cid) <35> if (self._packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: <36> buf.push_uint_var(len(self._peer_token)) <37> buf.push_bytes(self._peer_token) <38> buf.push_uint16(length | 0x4000) <39> buf.push_uint16(self._packet_number & 0xFFFF) <40> else: <41> buf.seek(self</s>
===========below chunk 0=========== # module: aioquic.packet_builder class QuicPacketBuilder: def end_packet(self) -> bool: # offset: 1 buf.push_uint8( 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.crypto.CryptoPair encrypt_packet(plain_header: bytes, plain_payload: bytes, packet_number: int) -> bytes at: aioquic.crypto.CryptoPair.__init__ self.aead_tag_size = 16 at: aioquic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 PACKET_TYPE_MASK = 0xF0 PACKET_NUMBER_MAX_SIZE = 4 at: aioquic.packet_builder PACKET_NUMBER_SEND_SIZE = 2 at: aioquic.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._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 self._packet_type = 0 self.buffer = Buffer(PACKET_MAX_SIZE) at: aioquic.packet_builder.QuicPacketBuilder.flush self._packets = [] ===========unchanged ref 1=========== at: aioquic.packet_builder.QuicPacketBuilder.start_packet 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, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type at: aioquic.packet_builder.QuicSentPacket sent_bytes: int = 0 ===========changed ref 0=========== # module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: """ Starts a new packet. """ buf = self.buffer self._ack_eliciting = False # if there is too little space remaining, start a new datagram # FIXME: the limit is arbitrary! packet_start = buf.tell() if self._buffer_capacity - packet_start < 128: self._flush_current_datagram() packet_start = 0 # initialize datagram if needed if self._datagram_init: if self.max_flight_bytes is not None: remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes if remaining_flight_bytes < self._buffer_capacity: self._buffer_capacity = remaining_flight_bytes if self.max_total_bytes is not None: remaining_total_bytes = self.max_total_bytes - self._total_bytes if remaining_total_bytes < self._buffer_capacity: self._buffer_capacity = remaining_total_bytes self._datagram_init = False # calculate header size packet_long_header = is_long_header(packet_type) if packet_long_header: + header_size = 11 + len(self._peer_cid) + len(self._host_cid) - header_size = 10 + len(self._peer_cid) + len(self._host_cid) if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: token_length = len(self._peer_token) header_size += size_uint_var(token_length) + token_length else: header_size = 3 + len(self._peer_cid) # check we have enough space if packet_start + header_size >= self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if packet_type == PACKET</s> ===========changed ref 1=========== # module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: # offset: 1 <s> self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if packet_type == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHAKE: epoch = Epoch.HANDSHAKE else: epoch = Epoch.ONE_RTT 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, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type buf.seek(self._packet_start + self._header_size) ===========changed ref 2=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 3=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 -
aioquic.connection/write_close_frame
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<6>:<add> buf.push_uint_var(error_code) <del> buf.push_uint16(error_code) <11>:<add> buf.push_uint_var(error_code) <del> buf.push_uint16(error_code)
# module: aioquic.connection def write_close_frame( builder: QuicPacketBuilder, error_code: int, frame_type: Optional[int], reason_phrase: str, ) -> None: <0> buf = builder.buffer <1> <2> reason_bytes = reason_phrase.encode("utf8") <3> <4> if frame_type is None: <5> builder.start_frame(QuicFrameType.APPLICATION_CLOSE) <6> buf.push_uint16(error_code) <7> buf.push_uint_var(len(reason_bytes)) <8> buf.push_bytes(reason_bytes) <9> else: <10> builder.start_frame(QuicFrameType.TRANSPORT_CLOSE) <11> buf.push_uint16(error_code) <12> buf.push_uint_var(frame_type) <13> buf.push_uint_var(len(reason_bytes)) <14> buf.push_bytes(reason_bytes) <15>
===========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.packet QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) at: aioquic.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) at: aioquic.packet_builder.QuicPacketBuilder start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None at: aioquic.packet_builder.QuicPacketBuilder.__init__ self.buffer = Buffer(PACKET_MAX_SIZE) ===========changed ref 0=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 1=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 2=========== # module: aioquic.packet def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, reason_phrase) ===========changed ref 3=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 4=========== # module: aioquic.packet def push_new_connection_id_frame( buf: Buffer, sequence_number: int, + retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes, ) -> None: assert len(stateless_reset_token) == 16 buf.push_uint_var(sequence_number) + buf.push_uint_var(retire_prior_to) buf.push_uint8(len(connection_id)) buf.push_bytes(connection_id) buf.push_bytes(stateless_reset_token) ===========changed ref 5=========== # module: aioquic.packet def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() frame_type = buf.pull_uint_var() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, frame_type, reason_phrase) ===========changed ref 6=========== # module: aioquic.packet + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]: - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[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 (sequence_number, retire_prior_to, connection_id, stateless_reset_token) - return (sequence_number, connection_id, stateless_reset_token) ===========changed ref 7=========== # module: aioquic.configuration @dataclass class QuicConfiguration: alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( - default_factory=lambda: [ - QuicProtocolVersion.DRAFT_19, - QuicProtocolVersion.DRAFT_20, - ] + default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) ===========changed ref 8=========== # module: aioquic.packet PARAMS = [ ("original_connection_id", bytes), ("idle_timeout", int), ("stateless_reset_token", bytes), ("max_packet_size", int), ("initial_max_data", int), ("initial_max_stream_data_bidi_local", int), ("initial_max_stream_data_bidi_remote", int), ("initial_max_stream_data_uni", int), ("initial_max_streams_bidi", int), ("initial_max_streams_uni", int), ("ack_delay_exponent", int), ("max_ack_delay", int), ("disable_migration", bool), ("preferred_address", bytes), + ("active_connection_id_limit", int), ] ===========changed ref 9=========== # module: aioquic.packet def encode_quic_version_negotiation( source_cid: bytes, destination_cid: bytes, supported_versions: List[QuicProtocolVersion], ) -> bytes: buf = Buffer( + capacity=7 - capacity=6 + len(destination_cid) + len(source_cid) + 4 * len(supported_versions) ) buf.push_uint8(os.urandom(1)[0] | PACKET_LONG_HEADER) buf.push_uint32(QuicProtocolVersion.NEGOTIATION) - buf.push_uint8( - (encode_cid_length(len(destination_cid)) << 4) - | encode_cid_length(len(source_cid)) - ) + buf.push_uint8(len(destination_cid)) buf.push_bytes(destination_cid) + buf.push_uint8(len(source_cid)) buf.push_bytes(source_cid) for version in supported_versions: buf.push_uint32(version) return buf.data ===========changed ref 10=========== # module: aioquic.crypto CIPHER_SUITES = { CipherSuite.AES_128_GCM_SHA256: (b"aes-128-ecb", b"aes-128-gcm"), CipherSuite.AES_256_GCM_SHA384: (b"aes-256-ecb", b"aes-256-gcm"), CipherSuite.CHACHA20_POLY1305_SHA256: (b"chacha20", b"chacha20-poly1305"), } INITIAL_CIPHER_SUITE = CipherSuite.AES_128_GCM_SHA256 + INITIAL_SALT = binascii.unhexlify("7fbcdb0e7c66bbe9193a96cd21519ebd7a02644a") - INITIAL_SALT = binascii.unhexlify("ef4fb0abb47470c41befcf8031334fae485e09a0") SAMPLE_SIZE = 16
aioquic.connection/QuicConnection.__init__
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
# module: aioquic.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._stateless_retry_count = 0 <14> self._version_negotiation_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.Event] = 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.host_cid = self._</s>
===========below chunk 0=========== # module: aioquic.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_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, 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_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</s> ===========below chunk 1=========== # module: aioquic.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>max_data_used = 0 self._remote_max_stream_data_bidi_local = 0 self._remote_max_stream_data_bidi_remote = 0 self._remote_max_stream_data_uni = 0 self._remote_max_streams_bidi = 0 self._remote_max_streams_uni = 0 self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._spin_bit = False self._spin_bit_peer = False self._spin_highest_pn = 0 self._state = QuicConnectionState.FIRSTFLIGHT self._streams: Dict[int, QuicStream] = {} self._streams_blocked_bidi: List[QuicStream] = [] self._streams_blocked_uni: List[QuicStream] = [] self._version: Optional[int] = None # things to send self._close_pending = False self._ping_pending: List[int] = [] self._probe_pending = False self._retire_connection_ids: List[int] = [] self._streams_blocked_pending = False # callbacks self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler # frame handlers self.__frame_handlers = [ (self._handle_padding_frame, EPOCHS("IZHO")), (self._handle_padding_frame, EPOCHS("ZO")),</s> ===========below chunk 2=========== # module: aioquic.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_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, EPOCHS("ZO")), (self._handle_max_streams_uni_frame, EPOCHS("ZO")), (self._handle_data_blocked_frame,</s> ===========below chunk 3=========== # module: aioquic.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_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.connection/QuicConnection._handle_new_connection_id_frame
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<3>:<add> sequence_number, retire_prior_to, cid, stateless_reset_token = pull_new_connection_id_frame( <del> sequence_number, cid, stateless_reset_token = pull_new_connection_id_frame(buf) <4>:<add> buf <add> )
# module: aioquic.connection class QuicConnection: def _handle_new_connection_id_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: <0> """ <1> Handle a NEW_CONNECTION_ID frame. <2> """ <3> sequence_number, cid, stateless_reset_token = pull_new_connection_id_frame(buf) <4> self._logger.debug( <5> "New connection ID received %d %s", sequence_number, dump_cid(cid) <6> ) <7> self._peer_cid_available.append( <8> QuicConnectionId( <9> cid=cid, <10> sequence_number=sequence_number, <11> stateless_reset_token=stateless_reset_token, <12> ) <13> ) <14>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.connection dump_cid(cid: bytes) -> str QuicConnectionId(cid: bytes, sequence_number: int, stateless_reset_token: bytes=b"", was_sent: bool=False) QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, time: float) at: aioquic.connection.QuicConnection.__init__ self._logger = QuicConnectionAdapter( logger, {"host_cid": dump_cid(self.host_cid)} ) self._peer_cid_available: List[QuicConnectionId] = [] at: aioquic.packet pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes] at: logging.LoggerAdapter logger: Logger extra: Mapping[str, Any] debug(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None ===========changed ref 0=========== # module: aioquic.packet + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]: - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[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 (sequence_number, retire_prior_to, connection_id, stateless_reset_token) - return (sequence_number, connection_id, stateless_reset_token) ===========changed ref 1=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 2=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 3=========== # module: aioquic.packet def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, reason_phrase) ===========changed ref 4=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 5=========== # module: aioquic.packet def push_new_connection_id_frame( buf: Buffer, sequence_number: int, + retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes, ) -> None: assert len(stateless_reset_token) == 16 buf.push_uint_var(sequence_number) + buf.push_uint_var(retire_prior_to) buf.push_uint8(len(connection_id)) buf.push_bytes(connection_id) buf.push_bytes(stateless_reset_token) ===========changed ref 6=========== # module: aioquic.packet def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() frame_type = buf.pull_uint_var() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, frame_type, reason_phrase) ===========changed ref 7=========== # module: aioquic.configuration @dataclass class QuicConfiguration: alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( - default_factory=lambda: [ - QuicProtocolVersion.DRAFT_19, - QuicProtocolVersion.DRAFT_20, - ] + default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) ===========changed ref 8=========== # module: aioquic.packet PARAMS = [ ("original_connection_id", bytes), ("idle_timeout", int), ("stateless_reset_token", bytes), ("max_packet_size", int), ("initial_max_data", int), ("initial_max_stream_data_bidi_local", int), ("initial_max_stream_data_bidi_remote", int), ("initial_max_stream_data_uni", int), ("initial_max_streams_bidi", int), ("initial_max_streams_uni", int), ("ack_delay_exponent", int), ("max_ack_delay", int), ("disable_migration", bool), ("preferred_address", bytes), + ("active_connection_id_limit", int), ] ===========changed ref 9=========== # module: aioquic.connection def write_close_frame( builder: QuicPacketBuilder, error_code: int, frame_type: Optional[int], reason_phrase: str, ) -> None: buf = builder.buffer reason_bytes = reason_phrase.encode("utf8") if frame_type is None: builder.start_frame(QuicFrameType.APPLICATION_CLOSE) + buf.push_uint_var(error_code) - buf.push_uint16(error_code) buf.push_uint_var(len(reason_bytes)) buf.push_bytes(reason_bytes) else: builder.start_frame(QuicFrameType.TRANSPORT_CLOSE) + buf.push_uint_var(error_code) - buf.push_uint16(error_code) buf.push_uint_var(frame_type) buf.push_uint_var(len(reason_bytes)) buf.push_bytes(reason_bytes) ===========changed ref 10=========== # module: aioquic.packet def encode_quic_version_negotiation( source_cid: bytes, destination_cid: bytes, supported_versions: List[QuicProtocolVersion], ) -> bytes: buf = Buffer( + capacity=7 - capacity=6 + len(destination_cid) + len(source_cid) + 4 * len(supported_versions) ) buf.push_uint8(os.urandom(1)[0] | PACKET_LONG_HEADER) buf.push_uint32(QuicProtocolVersion.NEGOTIATION) - buf.push_uint8( - (encode_cid_length(len(destination_cid)) << 4) - | encode_cid_length(len(source_cid)) - ) + buf.push_uint8(len(destination_cid)) buf.push_bytes(destination_cid) + buf.push_uint8(len(source_cid)) buf.push_bytes(source_cid) for version in supported_versions: buf.push_uint32(version) return buf.data
aioquic.connection/QuicConnection._handle_reset_stream_frame
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<4>:<add> error_code = buf.pull_uint_var() <del> error_code = buf.pull_uint16()
# module: aioquic.connection class QuicConnection: def _handle_reset_stream_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: <0> """ <1> Handle a RESET_STREAM frame. <2> """ <3> stream_id = buf.pull_uint_var() <4> error_code = buf.pull_uint16() <5> final_size = buf.pull_uint_var() <6> <7> # check stream direction <8> self._assert_stream_can_receive(frame_type, stream_id) <9> <10> self._logger.info( <11> "Stream %d reset by peer (error code %d, final size %d)", <12> stream_id, <13> error_code, <14> final_size, <15> ) <16> # stream = self._get_or_create_stream(frame_type, stream_id) <17> self._events.append(events.StreamReset(stream_id=stream_id)) <18>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer pull_uint16() -> int pull_uint_var() -> int at: aioquic.connection QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, time: float) at: aioquic.connection.QuicConnection _assert_stream_can_receive(frame_type: int, stream_id: int) -> None at: aioquic.connection.QuicConnection.__init__ self._events: Deque[events.Event] = deque() self._logger = QuicConnectionAdapter( logger, {"host_cid": dump_cid(self.host_cid)} ) at: aioquic.events StreamReset(stream_id: int) at: aioquic.events.StreamReset stream_id: int at: collections.deque append(x: _T) -> None at: logging.LoggerAdapter info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None ===========changed ref 0=========== # module: aioquic.connection class QuicConnection: def _handle_new_connection_id_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a NEW_CONNECTION_ID frame. """ + sequence_number, retire_prior_to, cid, stateless_reset_token = pull_new_connection_id_frame( - sequence_number, cid, stateless_reset_token = pull_new_connection_id_frame(buf) + buf + ) self._logger.debug( "New connection ID received %d %s", sequence_number, dump_cid(cid) ) self._peer_cid_available.append( QuicConnectionId( cid=cid, sequence_number=sequence_number, stateless_reset_token=stateless_reset_token, ) ) ===========changed ref 1=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 2=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 3=========== # module: aioquic.packet def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, reason_phrase) ===========changed ref 4=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 5=========== # module: aioquic.packet def push_new_connection_id_frame( buf: Buffer, sequence_number: int, + retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes, ) -> None: assert len(stateless_reset_token) == 16 buf.push_uint_var(sequence_number) + buf.push_uint_var(retire_prior_to) buf.push_uint8(len(connection_id)) buf.push_bytes(connection_id) buf.push_bytes(stateless_reset_token) ===========changed ref 6=========== # module: aioquic.packet def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() frame_type = buf.pull_uint_var() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, frame_type, reason_phrase) ===========changed ref 7=========== # module: aioquic.packet + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]: - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[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 (sequence_number, retire_prior_to, connection_id, stateless_reset_token) - return (sequence_number, connection_id, stateless_reset_token) ===========changed ref 8=========== # module: aioquic.configuration @dataclass class QuicConfiguration: alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( - default_factory=lambda: [ - QuicProtocolVersion.DRAFT_19, - QuicProtocolVersion.DRAFT_20, - ] + default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) ===========changed ref 9=========== # module: aioquic.packet PARAMS = [ ("original_connection_id", bytes), ("idle_timeout", int), ("stateless_reset_token", bytes), ("max_packet_size", int), ("initial_max_data", int), ("initial_max_stream_data_bidi_local", int), ("initial_max_stream_data_bidi_remote", int), ("initial_max_stream_data_uni", int), ("initial_max_streams_bidi", int), ("initial_max_streams_uni", int), ("ack_delay_exponent", int), ("max_ack_delay", int), ("disable_migration", bool), ("preferred_address", bytes), + ("active_connection_id_limit", int), ] ===========changed ref 10=========== # module: aioquic.connection def write_close_frame( builder: QuicPacketBuilder, error_code: int, frame_type: Optional[int], reason_phrase: str, ) -> None: buf = builder.buffer reason_bytes = reason_phrase.encode("utf8") if frame_type is None: builder.start_frame(QuicFrameType.APPLICATION_CLOSE) + buf.push_uint_var(error_code) - buf.push_uint16(error_code) buf.push_uint_var(len(reason_bytes)) buf.push_bytes(reason_bytes) else: builder.start_frame(QuicFrameType.TRANSPORT_CLOSE) + buf.push_uint_var(error_code) - buf.push_uint16(error_code) buf.push_uint_var(frame_type) buf.push_uint_var(len(reason_bytes)) buf.push_bytes(reason_bytes)
aioquic.connection/QuicConnection._handle_stop_sending_frame
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<4>:<add> buf.pull_uint_var() # application error code <del> buf.pull_uint16() # application error code
# module: aioquic.connection class QuicConnection: def _handle_stop_sending_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: <0> """ <1> Handle a STOP_SENDING frame. <2> """ <3> stream_id = buf.pull_uint_var() <4> buf.pull_uint16() # application error code <5> <6> # check stream direction <7> self._assert_stream_can_send(frame_type, stream_id) <8> <9> self._get_or_create_stream(frame_type, stream_id) <10>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer pull_uint16() -> int pull_uint_var() -> int at: aioquic.connection QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, time: float) at: aioquic.connection.QuicConnection _assert_stream_can_send(frame_type: int, stream_id: int) -> None _get_or_create_stream(frame_type: int, stream_id: int) -> QuicStream ===========changed ref 0=========== # module: aioquic.connection class QuicConnection: def _handle_reset_stream_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a RESET_STREAM frame. """ stream_id = buf.pull_uint_var() + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() final_size = buf.pull_uint_var() # check stream direction self._assert_stream_can_receive(frame_type, stream_id) self._logger.info( "Stream %d reset by peer (error code %d, final size %d)", stream_id, error_code, final_size, ) # stream = self._get_or_create_stream(frame_type, stream_id) self._events.append(events.StreamReset(stream_id=stream_id)) ===========changed ref 1=========== # module: aioquic.connection class QuicConnection: def _handle_new_connection_id_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a NEW_CONNECTION_ID frame. """ + sequence_number, retire_prior_to, cid, stateless_reset_token = pull_new_connection_id_frame( - sequence_number, cid, stateless_reset_token = pull_new_connection_id_frame(buf) + buf + ) self._logger.debug( "New connection ID received %d %s", sequence_number, dump_cid(cid) ) self._peer_cid_available.append( QuicConnectionId( cid=cid, sequence_number=sequence_number, stateless_reset_token=stateless_reset_token, ) ) ===========changed ref 2=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 3=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 4=========== # module: aioquic.packet def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, reason_phrase) ===========changed ref 5=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 6=========== # module: aioquic.packet def push_new_connection_id_frame( buf: Buffer, sequence_number: int, + retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes, ) -> None: assert len(stateless_reset_token) == 16 buf.push_uint_var(sequence_number) + buf.push_uint_var(retire_prior_to) buf.push_uint8(len(connection_id)) buf.push_bytes(connection_id) buf.push_bytes(stateless_reset_token) ===========changed ref 7=========== # module: aioquic.packet def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() frame_type = buf.pull_uint_var() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, frame_type, reason_phrase) ===========changed ref 8=========== # module: aioquic.packet + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]: - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[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 (sequence_number, retire_prior_to, connection_id, stateless_reset_token) - return (sequence_number, connection_id, stateless_reset_token) ===========changed ref 9=========== # module: aioquic.configuration @dataclass class QuicConfiguration: alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( - default_factory=lambda: [ - QuicProtocolVersion.DRAFT_19, - QuicProtocolVersion.DRAFT_20, - ] + default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) ===========changed ref 10=========== # module: aioquic.packet PARAMS = [ ("original_connection_id", bytes), ("idle_timeout", int), ("stateless_reset_token", bytes), ("max_packet_size", int), ("initial_max_data", int), ("initial_max_stream_data_bidi_local", int), ("initial_max_stream_data_bidi_remote", int), ("initial_max_stream_data_uni", int), ("initial_max_streams_bidi", int), ("initial_max_streams_uni", int), ("ack_delay_exponent", int), ("max_ack_delay", int), ("disable_migration", bool), ("preferred_address", bytes), + ("active_connection_id_limit", int), ]
aioquic.connection/QuicConnection._replenish_connection_ids
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<3>:<add> while len(self._host_cids) < self._remote_active_connection_id_limit: <del> while len(self._host_cids) < 8:
# module: aioquic.connection class QuicConnection: def _replenish_connection_ids(self) -> None: <0> """ <1> Generate new connection IDs. <2> """ <3> while len(self._host_cids) < 8: <4> self._host_cids.append( <5> QuicConnectionId( <6> cid=os.urandom(8), <7> sequence_number=self._host_cid_seq, <8> stateless_reset_token=os.urandom(16), <9> ) <10> ) <11> self._host_cid_seq += 1 <12>
===========unchanged ref 0=========== at: aioquic.connection QuicConnectionId(cid: bytes, sequence_number: int, stateless_reset_token: bytes=b"", was_sent: bool=False) at: aioquic.connection.QuicConnection.__init__ 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 at: os urandom(size: int, /) -> bytes ===========changed ref 0=========== # module: aioquic.connection class QuicConnection: def _handle_stop_sending_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a STOP_SENDING frame. """ stream_id = buf.pull_uint_var() + buf.pull_uint_var() # application error code - buf.pull_uint16() # application error code # check stream direction self._assert_stream_can_send(frame_type, stream_id) self._get_or_create_stream(frame_type, stream_id) ===========changed ref 1=========== # module: aioquic.connection class QuicConnection: def _handle_reset_stream_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a RESET_STREAM frame. """ stream_id = buf.pull_uint_var() + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() final_size = buf.pull_uint_var() # check stream direction self._assert_stream_can_receive(frame_type, stream_id) self._logger.info( "Stream %d reset by peer (error code %d, final size %d)", stream_id, error_code, final_size, ) # stream = self._get_or_create_stream(frame_type, stream_id) self._events.append(events.StreamReset(stream_id=stream_id)) ===========changed ref 2=========== # module: aioquic.connection class QuicConnection: def _handle_new_connection_id_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a NEW_CONNECTION_ID frame. """ + sequence_number, retire_prior_to, cid, stateless_reset_token = pull_new_connection_id_frame( - sequence_number, cid, stateless_reset_token = pull_new_connection_id_frame(buf) + buf + ) self._logger.debug( "New connection ID received %d %s", sequence_number, dump_cid(cid) ) self._peer_cid_available.append( QuicConnectionId( cid=cid, sequence_number=sequence_number, stateless_reset_token=stateless_reset_token, ) ) ===========changed ref 3=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 4=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 5=========== # module: aioquic.packet def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, reason_phrase) ===========changed ref 6=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 7=========== # module: aioquic.packet def push_new_connection_id_frame( buf: Buffer, sequence_number: int, + retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes, ) -> None: assert len(stateless_reset_token) == 16 buf.push_uint_var(sequence_number) + buf.push_uint_var(retire_prior_to) buf.push_uint8(len(connection_id)) buf.push_bytes(connection_id) buf.push_bytes(stateless_reset_token) ===========changed ref 8=========== # module: aioquic.packet def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() frame_type = buf.pull_uint_var() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, frame_type, reason_phrase) ===========changed ref 9=========== # module: aioquic.packet + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]: - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[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 (sequence_number, retire_prior_to, connection_id, stateless_reset_token) - return (sequence_number, connection_id, stateless_reset_token) ===========changed ref 10=========== # module: aioquic.configuration @dataclass class QuicConfiguration: alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( - default_factory=lambda: [ - QuicProtocolVersion.DRAFT_19, - QuicProtocolVersion.DRAFT_20, - ] + default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) ===========changed ref 11=========== # module: aioquic.packet PARAMS = [ ("original_connection_id", bytes), ("idle_timeout", int), ("stateless_reset_token", bytes), ("max_packet_size", int), ("initial_max_data", int), ("initial_max_stream_data_bidi_local", int), ("initial_max_stream_data_bidi_remote", int), ("initial_max_stream_data_uni", int), ("initial_max_streams_bidi", int), ("initial_max_streams_uni", int), ("ack_delay_exponent", int), ("max_ack_delay", int), ("disable_migration", bool), ("preferred_address", bytes), + ("active_connection_id_limit", int), ]
aioquic.connection/QuicConnection._parse_transport_parameters
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<18>:<add> if quic_transport_parameters.active_connection_id_limit is not None: <add> self._remote_active_connection_id_limit = ( <add> quic_transport_parameters.active_connection_id_limit <add> )
# module: aioquic.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.idle_timeout is not None: <19> self._remote_idle_timeout = quic_transport_parameters.idle_timeout / 1000.0 <20> for param in ["ack_delay_exponent", "max_ack_delay"]: <21> value = getattr(quic_transport_parameters, param) <22> if value is not None: <23> setattr(self._loss, param, value) <24> for param in [ <25> "max_data", <26> "max_stream_data_bidi_local", <27> "max_stream_data_bidi_remote", <28> "max_stream_data_uni", <29> "max_streams_bidi", <30> "max_streams_uni", <31> ]: <32> value = getattr(quic_transport_parameters, "initial_" + param) <33> if value is not None: <34> setattr(self, "_remote_" + param, value) <35>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.connection QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) at: aioquic.connection.QuicConnection.__init__ self._is_client = configuration.is_client self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, send_probe=self._send_probe ) self._original_connection_id = original_connection_id self._remote_idle_timeout = 0.0 # seconds at: aioquic.connection.QuicConnection.receive_datagram self._original_connection_id = self._peer_cid at: aioquic.packet QuicErrorCode(x: Union[str, bytes, bytearray], base: int) QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) pull_quic_transport_parameters(buf: Buffer) -> QuicTransportParameters QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) at: aioquic.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 1=========== 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.connection class QuicConnection: def _replenish_connection_ids(self) -> None: """ Generate new connection IDs. """ + while len(self._host_cids) < self._remote_active_connection_id_limit: - while len(self._host_cids) < 8: self._host_cids.append( QuicConnectionId( cid=os.urandom(8), sequence_number=self._host_cid_seq, stateless_reset_token=os.urandom(16), ) ) self._host_cid_seq += 1 ===========changed ref 1=========== # module: aioquic.connection class QuicConnection: def _handle_stop_sending_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a STOP_SENDING frame. """ stream_id = buf.pull_uint_var() + buf.pull_uint_var() # application error code - buf.pull_uint16() # application error code # check stream direction self._assert_stream_can_send(frame_type, stream_id) self._get_or_create_stream(frame_type, stream_id) ===========changed ref 2=========== # module: aioquic.connection class QuicConnection: def _handle_reset_stream_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a RESET_STREAM frame. """ stream_id = buf.pull_uint_var() + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() final_size = buf.pull_uint_var() # check stream direction self._assert_stream_can_receive(frame_type, stream_id) self._logger.info( "Stream %d reset by peer (error code %d, final size %d)", stream_id, error_code, final_size, ) # stream = self._get_or_create_stream(frame_type, stream_id) self._events.append(events.StreamReset(stream_id=stream_id)) ===========changed ref 3=========== # module: aioquic.connection class QuicConnection: def _handle_new_connection_id_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a NEW_CONNECTION_ID frame. """ + sequence_number, retire_prior_to, cid, stateless_reset_token = pull_new_connection_id_frame( - sequence_number, cid, stateless_reset_token = pull_new_connection_id_frame(buf) + buf + ) self._logger.debug( "New connection ID received %d %s", sequence_number, dump_cid(cid) ) self._peer_cid_available.append( QuicConnectionId( cid=cid, sequence_number=sequence_number, stateless_reset_token=stateless_reset_token, ) ) ===========changed ref 4=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 5=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 6=========== # module: aioquic.packet def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, reason_phrase) ===========changed ref 7=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 8=========== # module: aioquic.packet def push_new_connection_id_frame( buf: Buffer, sequence_number: int, + retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes, ) -> None: assert len(stateless_reset_token) == 16 buf.push_uint_var(sequence_number) + buf.push_uint_var(retire_prior_to) buf.push_uint8(len(connection_id)) buf.push_bytes(connection_id) buf.push_bytes(stateless_reset_token)
aioquic.connection/QuicConnection._serialize_transport_parameters
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<1>:<add> active_connection_id_limit=self._local_active_connection_id_limit,
# module: aioquic.connection class QuicConnection: def _serialize_transport_parameters(self) -> bytes: <0> quic_transport_parameters = QuicTransportParameters( <1> idle_timeout=int(self._configuration.idle_timeout * 1000), <2> initial_max_data=self._local_max_data, <3> initial_max_stream_data_bidi_local=self._local_max_stream_data_bidi_local, <4> initial_max_stream_data_bidi_remote=self._local_max_stream_data_bidi_remote, <5> initial_max_stream_data_uni=self._local_max_stream_data_uni, <6> initial_max_streams_bidi=self._local_max_streams_bidi, <7> initial_max_streams_uni=self._local_max_streams_uni, <8> ack_delay_exponent=10, <9> ) <10> if not self._is_client: <11> quic_transport_parameters.original_connection_id = ( <12> self._original_connection_id <13> ) <14> <15> buf = Buffer(capacity=512) <16> push_quic_transport_parameters(buf, quic_transport_parameters) <17> return buf.data <18>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.configuration.QuicConfiguration idle_timeout: float = 60.0 at: aioquic.connection.QuicConnection.__init__ self._configuration = configuration 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._original_connection_id = original_connection_id at: aioquic.connection.QuicConnection._write_connection_limits self._local_max_data *= 2 at: aioquic.connection.QuicConnection.receive_datagram self._original_connection_id = self._peer_cid ===========unchanged ref 1=========== at: aioquic.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, 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) push_quic_transport_parameters(buf: Buffer, params: QuicTransportParameters) -> None at: aioquic.packet.QuicTransportParameters original_connection_id: Optional[bytes] = None ===========changed ref 0=========== # module: aioquic.packet # TLS EXTENSION @dataclass class 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 ===========changed ref 1=========== # module: aioquic.connection class QuicConnection: def _replenish_connection_ids(self) -> None: """ Generate new connection IDs. """ + while len(self._host_cids) < self._remote_active_connection_id_limit: - while len(self._host_cids) < 8: self._host_cids.append( QuicConnectionId( cid=os.urandom(8), sequence_number=self._host_cid_seq, stateless_reset_token=os.urandom(16), ) ) self._host_cid_seq += 1 ===========changed ref 2=========== # module: aioquic.connection class QuicConnection: def _handle_stop_sending_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a STOP_SENDING frame. """ stream_id = buf.pull_uint_var() + buf.pull_uint_var() # application error code - buf.pull_uint16() # application error code # check stream direction self._assert_stream_can_send(frame_type, stream_id) self._get_or_create_stream(frame_type, stream_id) ===========changed ref 3=========== # module: aioquic.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.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) for param in [ "max_data", "max_stream_data_bidi_local", "max_stream_data_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 4=========== # module: aioquic.connection class QuicConnection: def _handle_reset_stream_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a RESET_STREAM frame. """ stream_id = buf.pull_uint_var() + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() final_size = buf.pull_uint_var() # check stream direction self._assert_stream_can_receive(frame_type, stream_id) self._logger.info( "Stream %d reset by peer (error code %d, final size %d)", stream_id, error_code, final_size, ) # stream = self._get_or_create_stream(frame_type, stream_id) self._events.append(events.StreamReset(stream_id=stream_id))
aioquic.connection/QuicConnection._write_application
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
# module: aioquic.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> # PATH CHALLENGE <30> if ( <31> not network_path.is_validated <32> and network_path.local_challenge is None <33> ): <34> self._logger.info( <35> "Network path %s sending challenge", network_path.addr <36> ) <37> network_path.local_challenge = os.urandom(8) <38> builder.start_frame(QuicFrameType.PATH_CHALLENGE) <39> buf.push_bytes</s>
===========below chunk 0=========== # module: aioquic.connection class QuicConnection: def _write_application( self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float ) -> None: # offset: 1 # 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, 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_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_</s> ===========below chunk 1=========== # module: aioquic.connection class QuicConnection: def _write_application( self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float ) -> None: # offset: 2 <s>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.values(): # 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 </s> ===========below chunk 2=========== # module: aioquic.connection class QuicConnection: def _write_application( self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float ) -> None: # offset: 3 <s> 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.connection write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None write_stream_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream, max_offset: int) -> int QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None) at: aioquic.connection.QuicConnection _on_ack_delivery(delivery: QuicDeliveryState, space: QuicPacketSpace, highest_acked: int) -> None _on_new_connection_id_delivery(delivery: QuicDeliveryState, connection_id: QuicConnectionId) -> None _on_ping_delivery(delivery: QuicDeliveryState, uids: Sequence[int]) -> None _on_retire_connection_id_delivery(delivery: QuicDeliveryState, sequence_number: int) -> None _write_connection_limits(builder: QuicPacketBuilder, space: QuicPacketSpace) -> None _write_stream_limits(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None at: aioquic.connection.QuicConnection.__init__ self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} self._events: Deque[events.Event] = deque() self._handshake_complete = False
examples.http3-client/run
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<17>:<add> alpn_protocols=["h3-22"], is_client=True, server_name=server_name, **kwargs <del> alpn_protocols=["h3-20"], is_client=True, server_name=server_name, **kwargs
# module: examples.http3-client def run(url: str, **kwargs) -> None: <0> # parse URL <1> parsed = urlparse(url) <2> assert parsed.scheme == "https", "Only HTTPS URLs are supported." <3> if ":" in parsed.netloc: <4> server_name, port_str = parsed.netloc.split(":") <5> port = int(port_str) <6> else: <7> server_name = parsed.netloc <8> port = 443 <9> <10> # prepare socket <11> server_addr = (socket.gethostbyname(server_name), port) <12> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <13> <14> # prepare QUIC connection <15> quic = QuicConnection( <16> configuration=QuicConfiguration( <17> alpn_protocols=["h3-20"], is_client=True, server_name=server_name, **kwargs <18> ), <19> session_ticket_handler=save_session_ticket, <20> ) <21> quic.connect(server_addr, now=time.time()) <22> <23> # send request <24> http = H3Connection(quic) <25> stream_id = quic.get_next_available_stream_id() <26> http.send_headers( <27> stream_id=stream_id, <28> headers=[ <29> (b":method", b"GET"), <30> (b":scheme", parsed.scheme.encode("utf8")), <31> (b":authority", parsed.netloc.encode("utf8")), <32> (b":path", parsed.path.encode("utf8")), <33> ], <34> ) <35> http.send_data(stream_id=stream_id, data=b"", end_stream=True) <36> for data, addr in quic.datagrams_to_send(now=time.time()): <37> sock.sendto(data, addr) <38> <39> # handle events <40> stream_ended = False <41> while not stream_ended: <42> </s>
===========below chunk 0=========== # module: examples.http3-client def run(url: str, **kwargs) -> None: # offset: 1 quic.receive_datagram(data, addr, now=time.time()) for event in http.handle_events(): print(event) if isinstance(event, (DataReceived, ResponseReceived)): stream_ended = event.stream_ended for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) ===========unchanged ref 0=========== at: aioquic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.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.connection.QuicConnection connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_next_available_stream_id(is_unidirectional=False) -> int receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection handle_events() -> List[Event] ===========unchanged ref 1=========== send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers) -> None at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: examples.http3-client save_session_ticket(ticket) at: socket AF_INET: AddressFamily SOCK_DGRAM: SocketKind socket(family: int=..., type: int=..., proto: int=..., fileno: Optional[int]=...) gethostbyname(hostname: str) -> str at: socket.socket family: int type: int proto: int recvfrom(bufsize: int, flags: int=...) -> Tuple[bytes, _RetAddress] sendto(data: bytes, address: _Address) -> int sendto(data: bytes, flags: int, address: _Address) -> int at: time time() -> float at: urllib.parse urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes ===========changed ref 0=========== # module: aioquic.configuration @dataclass class QuicConfiguration: alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( - default_factory=lambda: [ - QuicProtocolVersion.DRAFT_19, - QuicProtocolVersion.DRAFT_20, - ] + default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) ===========changed ref 1=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 2=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 3=========== # module: aioquic.packet def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, reason_phrase) ===========changed ref 4=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 5=========== # module: aioquic.packet def push_new_connection_id_frame( buf: Buffer, sequence_number: int, + retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes, ) -> None: assert len(stateless_reset_token) == 16 buf.push_uint_var(sequence_number) + buf.push_uint_var(retire_prior_to) buf.push_uint8(len(connection_id)) buf.push_bytes(connection_id) buf.push_bytes(stateless_reset_token) ===========changed ref 6=========== # module: aioquic.packet def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() frame_type = buf.pull_uint_var() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, frame_type, reason_phrase) ===========changed ref 7=========== # module: aioquic.connection class QuicConnection: def _handle_stop_sending_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a STOP_SENDING frame. """ stream_id = buf.pull_uint_var() + buf.pull_uint_var() # application error code - buf.pull_uint16() # application error code # check stream direction self._assert_stream_can_send(frame_type, stream_id) self._get_or_create_stream(frame_type, stream_id)
tests.test_connection/QuicConnectionTest.test_connect_with_alpn
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<1>:<add> client_options={"alpn_protocols": ["hq-22", "h3-22"]}, <del> client_options={"alpn_protocols": ["hq-20", "h3-20"]}, <2>:<add> server_options={"alpn_protocols": ["hq-22"]}, <del> server_options={"alpn_protocols": ["hq-20"]}, <7>:<add> self.assertEqual(event.alpn_protocol, "hq-22") <del> self.assertEqual(event.alpn_protocol, "hq-20") <14>:<add> self.assertEqual(event.alpn_protocol, "hq-22") <del> self.assertEqual(event.alpn_protocol, "hq-20")
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_alpn(self): <0> with client_and_server( <1> client_options={"alpn_protocols": ["hq-20", "h3-20"]}, <2> server_options={"alpn_protocols": ["hq-20"]}, <3> ) as (client, server): <4> # check handshake completed <5> event = client.next_event() <6> self.assertEqual(type(event), events.HandshakeCompleted) <7> self.assertEqual(event.alpn_protocol, "hq-20") <8> for i in range(7): <9> self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) <10> self.assertIsNone(client.next_event()) <11> <12> event = server.next_event() <13> self.assertEqual(type(event), events.HandshakeCompleted) <14> self.assertEqual(event.alpn_protocol, "hq-20") <15> for i in range(7): <16> self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) <17> self.assertIsNone(server.next_event()) <18>
===========unchanged ref 0=========== at: aioquic.events ConnectionIdIssued(connection_id: bytes) at: io StringIO(initial_value: Optional[str]=..., newline: Optional[str]=...) at: io.StringIO getvalue(self) -> str at: tests.test_connection client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={}) at: tests.test_connection.QuicConnectionTest.test_connect_with_alpn event = server.next_event() at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertIsNone(obj: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_20(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_20], - server_versions=[QuicProtocolVersion.DRAFT_20], - ) - ===========changed ref 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_19(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_19], - server_versions=[QuicProtocolVersion.DRAFT_19], - ) - ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_connect(self): + with client_and_server() as (client, server): + # check handshake completed + event = client.next_event() + self.assertEqual(type(event), events.HandshakeCompleted) + self.assertEqual(event.alpn_protocol, None) + self.assertEqual(event.early_data_accepted, False) + self.assertEqual(event.session_resumed, False) + for i in range(7): + self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) + self.assertIsNone(client.next_event()) + + event = server.next_event() + self.assertEqual(type(event), events.HandshakeCompleted) + self.assertEqual(event.alpn_protocol, None) + self.assertEqual(event.early_data_accepted, False) + self.assertEqual(event.session_resumed, False) + for i in range(7): + self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) + self.assertIsNone(server.next_event()) + + # check each endpoint has available connection IDs for the peer + self.assertEqual( + sequence_numbers(client._peer_cid_available), [1, 2, 3, 4, 5, 6, 7] + ) + self.assertEqual( + sequence_numbers(server._peer_cid_available), [1, 2, 3, 4, 5, 6, 7] + ) + + # client closes the connection + client.close() + self.assertEqual(transfer(client, server), 1) + + # check connection closes on the client side + client.handle_timer(client.get_timer()) + event = client.next_event() + self.assertEqual(type(event), events.ConnectionTerminated) + self.assertEqual</s> ===========changed ref 3=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_connect(self): # offset: 1 <s> client.next_event() + self.assertEqual(type(event), events.ConnectionTerminated) + self.assertEqual(event.error_code, QuicErrorCode.NO_ERROR) + self.assertEqual(event.frame_type, None) + self.assertEqual(event.reason_phrase, "") + self.assertIsNone(client.next_event()) + + # check connection closes on the server side + server.handle_timer(server.get_timer()) + event = server.next_event() + self.assertEqual(type(event), events.ConnectionTerminated) + self.assertEqual(event.error_code, QuicErrorCode.NO_ERROR) + self.assertEqual(event.frame_type, None) + self.assertEqual(event.reason_phrase, "") + self.assertIsNone(server.next_event()) + ===========changed ref 4=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def _test_connect_with_version(self, client_versions, server_versions): - with client_and_server( - client_options={"supported_versions": client_versions}, - server_options={"supported_versions": server_versions}, - ) as (client, server): - # check handshake completed - event = client.next_event() - self.assertEqual(type(event), events.HandshakeCompleted) - self.assertEqual(event.alpn_protocol, None) - self.assertEqual(event.early_data_accepted, False) - self.assertEqual(event.session_resumed, False) - for i in range(7): - self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) - self.assertIsNone(client.next_event()) - - event = server.next_event() - self.assertEqual(type(event), events.HandshakeCompleted) - self.assertEqual(event.alpn_protocol, None) - self.assertEqual(event.early_data_accepted, False) - self.assertEqual(event.session_resumed, False) - for i in range(7): - self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) - self.assertIsNone(server.next_event()) - - # check each endpoint has available connection IDs for the peer - self.assertEqual( - sequence_numbers(client._peer_cid_available), [1, 2, 3, 4, 5, 6, 7] - ) - self.assertEqual( - sequence_numbers(server._peer_cid_available), [1, 2, 3, 4, 5, 6, 7] - ) - - # client closes the connection - client.close() - self.assertEqual(transfer(client, server), 1) - - # check connection closes on the client side </s>
tests.test_connection/QuicConnectionTest.test_connect_with_loss_1
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<37>:<add> self.assertEqual(datagram_sizes(items), [1280, 1079]) <del> self.assertEqual(datagram_sizes(items), [1280, 1071])
# 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, 1071]) <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, 216]) 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), [268]) 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.assertTrue(isinstance(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), []) self.assertAlmostEqual(server.get_timer(), 61.5) # idle timeout</s> ===========below chunk 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): # offset: 2 <s>_sizes(items), []) self.assertAlmostEqual(server.get_timer(), 61.5) # idle timeout self.assertTrue(isinstance(server.next_event(), events.HandshakeCompleted)) ===========unchanged ref 0=========== at: aioquic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.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.connection.QuicConnection connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> 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.connection.QuicConnection.__init__ self._ack_delay = K_GRANULARITY ===========unchanged ref 1=========== self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, send_probe=self._send_probe ) at: aioquic.recovery.QuicPacketRecovery.__init__ self.spaces: List[QuicPacketSpace] = [] at: aioquic.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.test_connection.QuicConnectionTest.test_connect_with_loss_1 datagram_sizes(items) client = QuicConnection(configuration=QuicConfiguration(is_client=True)) server = QuicConnection( configuration=QuicConfiguration( is_client=False, certificate=SERVER_CERTIFICATE, private_key=SERVER_PRIVATE_KEY, ) ) 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 ===========changed ref 0=========== # module: aioquic.configuration @dataclass class QuicConfiguration: alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( - default_factory=lambda: [ - QuicProtocolVersion.DRAFT_19, - QuicProtocolVersion.DRAFT_20, - ] + default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) ===========changed ref 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_20(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_20], - server_versions=[QuicProtocolVersion.DRAFT_20], - ) - ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_19(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_19], - server_versions=[QuicProtocolVersion.DRAFT_19], - ) -