Copilot commented on code in PR #13641:
URL: https://github.com/apache/trafficserver/pull/13641#discussion_r4476772457


##########
tests/uranium_tests/h2/test_http2_flow_control.py:
##########
@@ -47,6 +48,38 @@ def invalid_flow_control_policy_configure_ats(ats_factory: 
ATSFactory, *, _case:
 DYNAMIC_WINDOW_SETTINGS_CAP_REPLAY = TEST_DIRECTORY / "replay" / 
"http2_settings_ack_stall.replay.yaml"
 
 
+def test_closed_stream_flow_control(ats_factory: ATSFactory, services: 
ServiceFactory) -> None:
+    """Discarded DATA must replenish the connection window for later requests.
+
+    :param ats_factory: Factory for isolated Traffic Server instances.
+    :param services: Factory owning the HTTP-bin origin.
+    """
+    server = services.httpbin("closed-stream-origin")
+    ats = ats_factory.create("closed-stream-ats", enable_tls=True, 
enable_cache=False)
+    ats.add_default_ssl_files()
+    ats.records.update({
+        "proxy.config.diags.debug.enabled": 1,
+        "proxy.config.diags.debug.tags": "http2",
+    })
+    ats.remap_config.add_line(f"map / http://127.0.0.1:{server.port}";)
+    server.start()
+    ats.start()
+    result = ats.run(
+        sys.executable,
+        TEST_DIRECTORY / "clients" / "h2_closed_stream_window_drain.py",
+        str(ats.https_port),
+        timeout=20,
+    )
+    assert result.returncode == 0, result.output
+    assert "closed-stream DATA sent=131070" in result.stdout
+    assert "stream 3 :status 200" in result.stdout
+    wait_for_file_lines(ats.traffic_out, "Send RST_STREAM frame: Error Code: 
5", 1)
+    wait_for_file_lines(ats.traffic_out, "Discarded DATA 
payload_length=16384", 1)

Review Comment:
   The test asserts a specific discarded DATA payload length (16384). This is 
brittle if SETTINGS_MAX_FRAME_SIZE is changed/negotiated differently (or 
defaults change), because the client adapts `chunk_size` to the peer's 
advertised max frame size. Consider matching the presence of the discard log 
line without hard-coding the length (e.g., regex for `Discarded DATA 
payload_length=\\d+`), or deriving the expected value from what the client 
observed/printed.



##########
tests/uranium_tests/h2/clients/h2_closed_stream_window_drain.py:
##########
@@ -0,0 +1,306 @@
+#!/usr/bin/env python3
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+#  limitations under the License.
+'''
+HTTP/2 client that floods a closed stream with DATA and then verifies the
+connection is still usable.
+'''
+
+import argparse
+import socket
+import ssl
+from typing import Dict, List, Optional, Tuple
+
+import hpack
+
+CONNECTION_PREFACE = b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n'
+
+FRAME_TYPE_DATA = 0
+FRAME_TYPE_HEADERS = 1
+FRAME_TYPE_RST_STREAM = 3
+FRAME_TYPE_SETTINGS = 4
+FRAME_TYPE_PING = 6
+FRAME_TYPE_GOAWAY = 7
+FRAME_TYPE_WINDOW_UPDATE = 8
+
+FLAG_ACK = 0x01
+FLAG_END_STREAM = 0x01
+FLAG_END_HEADERS = 0x04
+
+CONNECTION_STREAM_ID = 0
+CLOSED_STREAM_ID = 1
+PROBE_STREAM_ID = 3
+
+SETTINGS_MAX_FRAME_SIZE = 0x5
+
+# RFC 9113 section 6.5.2: the default SETTINGS_MAX_FRAME_SIZE, used until the
+# peer advertises its own.
+DEFAULT_MAX_FRAME_SIZE = 16384
+
+# RFC 9113 section 6.9.2: the connection window always starts at 65535;
+# SETTINGS_INITIAL_WINDOW_SIZE only applies to stream windows.
+INITIAL_WINDOW_SIZE = 65535
+
+# Send enough DATA to the closed stream to consume the initial connection
+# window twice over. A client that honors the connection-level flow-control
+# window can only do this if the peer credits the discarded bytes back with
+# connection-level WINDOW_UPDATE frames. Stream-level windows are not tracked:
+# the stream is closed, and ATS does not consult its window when discarding.
+CLOSED_STREAM_DATA_TOTAL = 2 * INITIAL_WINDOW_SIZE
+PROBE_BODY = b'p' * 1024
+
+# How long to wait for a WINDOW_UPDATE before concluding the connection window
+# has been drained for good.
+WINDOW_UPDATE_TIMEOUT_SECONDS = 3
+
+Frame = Tuple[int, int, int, bytes]
+
+
+class WindowDrained(Exception):
+    """Raised when the peer never replenishes the connection window."""
+
+
+class Http2Client:
+    """A minimal HTTP/2 client that tracks the connection send window."""
+
+    def __init__(self, port: int) -> None:
+        self._sock = self._make_socket(port)
+        self._encoder = hpack.Encoder()
+        self._decoder = hpack.Decoder()
+        self._send_window = INITIAL_WINDOW_SIZE
+        self._max_frame_size = DEFAULT_MAX_FRAME_SIZE
+        self._window_update_count = 0
+        self._window_update_total = 0
+        self._rst_stream_count: Dict[int, int] = {}
+        self._response_status: Dict[int, Optional[str]] = {}
+        self._response_done: Dict[int, bool] = {}
+
+    @staticmethod
+    def _make_socket(port: int) -> ssl.SSLSocket:
+        socket.setdefaulttimeout(10)
+        ctx = ssl.create_default_context()
+        ctx.check_hostname = False
+        ctx.verify_mode = ssl.CERT_NONE
+        ctx.set_alpn_protocols(['h2'])
+
+        raw_socket = socket.create_connection(('127.0.0.1', port))
+        tls_socket = ctx.wrap_socket(raw_socket, server_hostname='localhost')
+        negotiated = tls_socket.selected_alpn_protocol()
+        if negotiated != 'h2':
+            raise RuntimeError(f'Expected h2 ALPN, negotiated {negotiated!r}')
+        return tls_socket
+
+    def close(self) -> None:
+        self._sock.close()
+
+    @property
+    def window_update_count(self) -> int:
+        return self._window_update_count
+
+    @property
+    def window_update_total(self) -> int:
+        return self._window_update_total
+
+    def rst_stream_count(self, stream_id: int) -> int:
+        return self._rst_stream_count.get(stream_id, 0)
+
+    def response_status(self, stream_id: int) -> Optional[str]:
+        return self._response_status.get(stream_id)
+
+    # Frame plumbing.
+
+    @staticmethod
+    def _make_frame(frame_type: int, flags: int = 0, stream_id: int = 0, 
payload: bytes = b'') -> bytes:
+        return len(payload).to_bytes(3, 'big') + bytes([frame_type, flags]) + 
(stream_id & 0x7fffffff).to_bytes(4, 'big') + payload
+
+    def _send_frame(self, frame_type: int, flags: int = 0, stream_id: int = 0, 
payload: bytes = b'') -> None:
+        self._sock.sendall(self._make_frame(frame_type, flags, stream_id, 
payload))
+
+    def _read_exact(self, size: int) -> bytes:
+        chunks = []
+        remaining = size
+        while remaining > 0:
+            chunk = self._sock.recv(remaining)
+            if not chunk:
+                raise EOFError('socket closed')
+            chunks.append(chunk)
+            remaining -= len(chunk)
+        return b''.join(chunks)
+
+    def _read_frame(self) -> Frame:
+        header = self._read_exact(9)
+        length = int.from_bytes(header[0:3], 'big')
+        frame_type = header[3]
+        flags = header[4]
+        stream_id = int.from_bytes(header[5:9], 'big') & 0x7fffffff
+        payload = self._read_exact(length)
+        return frame_type, flags, stream_id, payload
+
+    def _handle_frame(self, frame: Frame) -> None:
+        frame_type, flags, stream_id, payload = frame
+        if frame_type == FRAME_TYPE_WINDOW_UPDATE and stream_id == 
CONNECTION_STREAM_ID:
+            increment = int.from_bytes(payload[0:4], 'big') & 0x7fffffff
+            self._send_window += increment
+            self._window_update_count += 1
+            self._window_update_total += increment
+            print(f'connection WINDOW_UPDATE increment={increment} 
send_window={self._send_window}')
+        elif frame_type == FRAME_TYPE_RST_STREAM:
+            error_code = int.from_bytes(payload[0:4], 'big')
+            self._rst_stream_count[stream_id] = 
self._rst_stream_count.get(stream_id, 0) + 1
+            if self._rst_stream_count[stream_id] == 1:
+                print(f'stream {stream_id} RST_STREAM error_code={error_code}')
+        elif frame_type == FRAME_TYPE_GOAWAY:
+            error_code = int.from_bytes(payload[4:8], 'big')
+            raise RuntimeError(f'GOAWAY error_code={error_code}')
+        elif frame_type == FRAME_TYPE_SETTINGS and not (flags & FLAG_ACK):
+            for offset in range(0, len(payload) - 5, 6):
+                identifier = int.from_bytes(payload[offset:offset + 2], 'big')
+                value = int.from_bytes(payload[offset + 2:offset + 6], 'big')
+                if identifier == SETTINGS_MAX_FRAME_SIZE:
+                    self._max_frame_size = value
+            self._send_frame(FRAME_TYPE_SETTINGS, FLAG_ACK)
+        elif frame_type == FRAME_TYPE_PING and not (flags & FLAG_ACK):
+            self._send_frame(FRAME_TYPE_PING, FLAG_ACK, CONNECTION_STREAM_ID, 
payload)
+        elif frame_type == FRAME_TYPE_HEADERS:
+            padded = flags & 0x08
+            priority = flags & 0x20
+            block = payload
+            if padded:
+                pad_length = block[0]
+                block = block[1:len(block) - pad_length]
+            if priority:
+                block = block[5:]
+            for name, value in self._decoder.decode(block):

Review Comment:
   HPACK decoder return types can vary by library/version/config (some return 
`bytes` for header names/values). Comparing `name` to the string `':status'` 
and storing `value` unmodified can make the script version-sensitive (e.g., it 
might store `b'200'` and later compare to `'200'`). Consider normalizing 
decoded header names/values to `str` (decode ASCII/UTF-8 as appropriate) before 
comparisons and storage.



##########
tests/uranium_tests/h2/clients/h2_closed_stream_window_drain.py:
##########
@@ -0,0 +1,306 @@
+#!/usr/bin/env python3
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+#  limitations under the License.
+'''
+HTTP/2 client that floods a closed stream with DATA and then verifies the
+connection is still usable.
+'''
+
+import argparse
+import socket
+import ssl
+from typing import Dict, List, Optional, Tuple
+
+import hpack
+
+CONNECTION_PREFACE = b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n'
+
+FRAME_TYPE_DATA = 0
+FRAME_TYPE_HEADERS = 1
+FRAME_TYPE_RST_STREAM = 3
+FRAME_TYPE_SETTINGS = 4
+FRAME_TYPE_PING = 6
+FRAME_TYPE_GOAWAY = 7
+FRAME_TYPE_WINDOW_UPDATE = 8
+
+FLAG_ACK = 0x01
+FLAG_END_STREAM = 0x01
+FLAG_END_HEADERS = 0x04
+
+CONNECTION_STREAM_ID = 0
+CLOSED_STREAM_ID = 1
+PROBE_STREAM_ID = 3
+
+SETTINGS_MAX_FRAME_SIZE = 0x5
+
+# RFC 9113 section 6.5.2: the default SETTINGS_MAX_FRAME_SIZE, used until the
+# peer advertises its own.
+DEFAULT_MAX_FRAME_SIZE = 16384
+
+# RFC 9113 section 6.9.2: the connection window always starts at 65535;
+# SETTINGS_INITIAL_WINDOW_SIZE only applies to stream windows.
+INITIAL_WINDOW_SIZE = 65535
+
+# Send enough DATA to the closed stream to consume the initial connection
+# window twice over. A client that honors the connection-level flow-control
+# window can only do this if the peer credits the discarded bytes back with
+# connection-level WINDOW_UPDATE frames. Stream-level windows are not tracked:
+# the stream is closed, and ATS does not consult its window when discarding.
+CLOSED_STREAM_DATA_TOTAL = 2 * INITIAL_WINDOW_SIZE
+PROBE_BODY = b'p' * 1024
+
+# How long to wait for a WINDOW_UPDATE before concluding the connection window
+# has been drained for good.
+WINDOW_UPDATE_TIMEOUT_SECONDS = 3
+
+Frame = Tuple[int, int, int, bytes]
+
+
+class WindowDrained(Exception):
+    """Raised when the peer never replenishes the connection window."""
+
+
+class Http2Client:
+    """A minimal HTTP/2 client that tracks the connection send window."""
+
+    def __init__(self, port: int) -> None:
+        self._sock = self._make_socket(port)
+        self._encoder = hpack.Encoder()
+        self._decoder = hpack.Decoder()
+        self._send_window = INITIAL_WINDOW_SIZE
+        self._max_frame_size = DEFAULT_MAX_FRAME_SIZE
+        self._window_update_count = 0
+        self._window_update_total = 0
+        self._rst_stream_count: Dict[int, int] = {}
+        self._response_status: Dict[int, Optional[str]] = {}
+        self._response_done: Dict[int, bool] = {}
+
+    @staticmethod
+    def _make_socket(port: int) -> ssl.SSLSocket:
+        socket.setdefaulttimeout(10)
+        ctx = ssl.create_default_context()
+        ctx.check_hostname = False
+        ctx.verify_mode = ssl.CERT_NONE
+        ctx.set_alpn_protocols(['h2'])
+
+        raw_socket = socket.create_connection(('127.0.0.1', port))
+        tls_socket = ctx.wrap_socket(raw_socket, server_hostname='localhost')
+        negotiated = tls_socket.selected_alpn_protocol()
+        if negotiated != 'h2':
+            raise RuntimeError(f'Expected h2 ALPN, negotiated {negotiated!r}')
+        return tls_socket
+
+    def close(self) -> None:
+        self._sock.close()
+
+    @property
+    def window_update_count(self) -> int:
+        return self._window_update_count
+
+    @property
+    def window_update_total(self) -> int:
+        return self._window_update_total
+
+    def rst_stream_count(self, stream_id: int) -> int:
+        return self._rst_stream_count.get(stream_id, 0)
+
+    def response_status(self, stream_id: int) -> Optional[str]:
+        return self._response_status.get(stream_id)
+
+    # Frame plumbing.
+
+    @staticmethod
+    def _make_frame(frame_type: int, flags: int = 0, stream_id: int = 0, 
payload: bytes = b'') -> bytes:
+        return len(payload).to_bytes(3, 'big') + bytes([frame_type, flags]) + 
(stream_id & 0x7fffffff).to_bytes(4, 'big') + payload
+
+    def _send_frame(self, frame_type: int, flags: int = 0, stream_id: int = 0, 
payload: bytes = b'') -> None:
+        self._sock.sendall(self._make_frame(frame_type, flags, stream_id, 
payload))
+
+    def _read_exact(self, size: int) -> bytes:
+        chunks = []
+        remaining = size
+        while remaining > 0:
+            chunk = self._sock.recv(remaining)
+            if not chunk:
+                raise EOFError('socket closed')
+            chunks.append(chunk)
+            remaining -= len(chunk)
+        return b''.join(chunks)
+
+    def _read_frame(self) -> Frame:
+        header = self._read_exact(9)
+        length = int.from_bytes(header[0:3], 'big')
+        frame_type = header[3]
+        flags = header[4]
+        stream_id = int.from_bytes(header[5:9], 'big') & 0x7fffffff
+        payload = self._read_exact(length)
+        return frame_type, flags, stream_id, payload
+
+    def _handle_frame(self, frame: Frame) -> None:
+        frame_type, flags, stream_id, payload = frame
+        if frame_type == FRAME_TYPE_WINDOW_UPDATE and stream_id == 
CONNECTION_STREAM_ID:
+            increment = int.from_bytes(payload[0:4], 'big') & 0x7fffffff
+            self._send_window += increment
+            self._window_update_count += 1
+            self._window_update_total += increment
+            print(f'connection WINDOW_UPDATE increment={increment} 
send_window={self._send_window}')
+        elif frame_type == FRAME_TYPE_RST_STREAM:
+            error_code = int.from_bytes(payload[0:4], 'big')
+            self._rst_stream_count[stream_id] = 
self._rst_stream_count.get(stream_id, 0) + 1
+            if self._rst_stream_count[stream_id] == 1:
+                print(f'stream {stream_id} RST_STREAM error_code={error_code}')
+        elif frame_type == FRAME_TYPE_GOAWAY:
+            error_code = int.from_bytes(payload[4:8], 'big')
+            raise RuntimeError(f'GOAWAY error_code={error_code}')
+        elif frame_type == FRAME_TYPE_SETTINGS and not (flags & FLAG_ACK):
+            for offset in range(0, len(payload) - 5, 6):
+                identifier = int.from_bytes(payload[offset:offset + 2], 'big')
+                value = int.from_bytes(payload[offset + 2:offset + 6], 'big')
+                if identifier == SETTINGS_MAX_FRAME_SIZE:
+                    self._max_frame_size = value
+            self._send_frame(FRAME_TYPE_SETTINGS, FLAG_ACK)

Review Comment:
   The SETTINGS parsing loop uses `range(0, len(payload) - 5, 6)`, which is 
non-obvious and easy to misread. It would be clearer to iterate `range(0, 
len(payload), 6)` and (optionally) validate `len(payload) % 6 == 0` before 
parsing, since SETTINGS payloads are defined as a sequence of 6-byte parameters.



##########
tests/uranium_tests/h2/clients/h2_closed_stream_window_drain.py:
##########
@@ -0,0 +1,306 @@
+#!/usr/bin/env python3
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+#  limitations under the License.
+'''
+HTTP/2 client that floods a closed stream with DATA and then verifies the
+connection is still usable.
+'''
+
+import argparse
+import socket
+import ssl
+from typing import Dict, List, Optional, Tuple
+
+import hpack
+
+CONNECTION_PREFACE = b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n'
+
+FRAME_TYPE_DATA = 0
+FRAME_TYPE_HEADERS = 1
+FRAME_TYPE_RST_STREAM = 3
+FRAME_TYPE_SETTINGS = 4
+FRAME_TYPE_PING = 6
+FRAME_TYPE_GOAWAY = 7
+FRAME_TYPE_WINDOW_UPDATE = 8
+
+FLAG_ACK = 0x01
+FLAG_END_STREAM = 0x01
+FLAG_END_HEADERS = 0x04
+
+CONNECTION_STREAM_ID = 0
+CLOSED_STREAM_ID = 1
+PROBE_STREAM_ID = 3
+
+SETTINGS_MAX_FRAME_SIZE = 0x5
+
+# RFC 9113 section 6.5.2: the default SETTINGS_MAX_FRAME_SIZE, used until the
+# peer advertises its own.
+DEFAULT_MAX_FRAME_SIZE = 16384
+
+# RFC 9113 section 6.9.2: the connection window always starts at 65535;
+# SETTINGS_INITIAL_WINDOW_SIZE only applies to stream windows.
+INITIAL_WINDOW_SIZE = 65535
+
+# Send enough DATA to the closed stream to consume the initial connection
+# window twice over. A client that honors the connection-level flow-control
+# window can only do this if the peer credits the discarded bytes back with
+# connection-level WINDOW_UPDATE frames. Stream-level windows are not tracked:
+# the stream is closed, and ATS does not consult its window when discarding.
+CLOSED_STREAM_DATA_TOTAL = 2 * INITIAL_WINDOW_SIZE
+PROBE_BODY = b'p' * 1024
+
+# How long to wait for a WINDOW_UPDATE before concluding the connection window
+# has been drained for good.
+WINDOW_UPDATE_TIMEOUT_SECONDS = 3
+
+Frame = Tuple[int, int, int, bytes]
+
+
+class WindowDrained(Exception):
+    """Raised when the peer never replenishes the connection window."""
+
+
+class Http2Client:
+    """A minimal HTTP/2 client that tracks the connection send window."""
+
+    def __init__(self, port: int) -> None:
+        self._sock = self._make_socket(port)
+        self._encoder = hpack.Encoder()
+        self._decoder = hpack.Decoder()
+        self._send_window = INITIAL_WINDOW_SIZE
+        self._max_frame_size = DEFAULT_MAX_FRAME_SIZE
+        self._window_update_count = 0
+        self._window_update_total = 0
+        self._rst_stream_count: Dict[int, int] = {}
+        self._response_status: Dict[int, Optional[str]] = {}
+        self._response_done: Dict[int, bool] = {}
+
+    @staticmethod
+    def _make_socket(port: int) -> ssl.SSLSocket:
+        socket.setdefaulttimeout(10)
+        ctx = ssl.create_default_context()
+        ctx.check_hostname = False
+        ctx.verify_mode = ssl.CERT_NONE
+        ctx.set_alpn_protocols(['h2'])
+
+        raw_socket = socket.create_connection(('127.0.0.1', port))
+        tls_socket = ctx.wrap_socket(raw_socket, server_hostname='localhost')

Review Comment:
   `socket.setdefaulttimeout(10)` changes the default timeout globally for the 
entire Python process. Even though this script is typically run in a 
subprocess, it’s still cleaner and less error-prone to set timeouts on the 
specific socket instance (e.g., via `settimeout`) rather than modifying global 
defaults.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to