code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
async def create_listening_ssl_socket(address, certfile, keyfile):
"""
Create and return a listening TLS socket on a given address.
"""
ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_context.options |= (
ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 | ssl.OP_NO_COMPRESSION
)
ssl_context.set_ciphers("ECDHE+AESGCM")
ssl_context.load_cert_chain(certfile=certfile, keyfile=keyfile)
ssl_context.set_alpn_protocols(["h2"])
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock = await ssl_context.wrap_socket(sock)
sock.bind(address)
sock.listen()
return sock |
Create and return a listening TLS socket on a given address.
| create_listening_ssl_socket | python | python-hyper/h2 | examples/curio/curio-server.py | https://github.com/python-hyper/h2/blob/master/examples/curio/curio-server.py | MIT |
async def h2_server(address, root, certfile, keyfile):
"""
Create an HTTP/2 server at the given address.
"""
sock = await create_listening_ssl_socket(address, certfile, keyfile)
print("Now listening on %s:%d" % address)
async with sock:
while True:
client, _ = await sock.accept()
server = H2Server(client, root)
await spawn(server.run()) |
Create an HTTP/2 server at the given address.
| h2_server | python | python-hyper/h2 | examples/curio/curio-server.py | https://github.com/python-hyper/h2/blob/master/examples/curio/curio-server.py | MIT |
async def run(self):
"""
Loop over the connection, managing it appropriately.
"""
self.conn.initiate_connection()
await self.sock.sendall(self.conn.data_to_send())
while True:
# 65535 is basically arbitrary here: this amounts to "give me
# whatever data you have".
data = await self.sock.recv(65535)
if not data:
break
events = self.conn.receive_data(data)
for event in events:
if isinstance(event, h2.events.RequestReceived):
await spawn(
self.request_received(event.headers, event.stream_id)
)
elif isinstance(event, h2.events.DataReceived):
self.conn.reset_stream(event.stream_id)
elif isinstance(event, h2.events.WindowUpdated):
await self.window_updated(event)
await self.sock.sendall(self.conn.data_to_send()) |
Loop over the connection, managing it appropriately.
| run | python | python-hyper/h2 | examples/curio/curio-server.py | https://github.com/python-hyper/h2/blob/master/examples/curio/curio-server.py | MIT |
async def request_received(self, headers, stream_id):
"""
Handle a request by attempting to serve a suitable file.
"""
headers = dict(headers)
assert headers[':method'] == 'GET'
path = headers[':path'].lstrip('/')
full_path = os.path.join(self.root, path)
if not os.path.exists(full_path):
response_headers = (
(':status', '404'),
('content-length', '0'),
('server', 'curio-h2'),
)
self.conn.send_headers(
stream_id, response_headers, end_stream=True
)
await self.sock.sendall(self.conn.data_to_send())
else:
await self.send_file(full_path, stream_id) |
Handle a request by attempting to serve a suitable file.
| request_received | python | python-hyper/h2 | examples/curio/curio-server.py | https://github.com/python-hyper/h2/blob/master/examples/curio/curio-server.py | MIT |
async def send_file(self, file_path, stream_id):
"""
Send a file, obeying the rules of HTTP/2 flow control.
"""
filesize = os.stat(file_path).st_size
content_type, content_encoding = mimetypes.guess_type(file_path)
response_headers = [
(':status', '200'),
('content-length', str(filesize)),
('server', 'curio-h2'),
]
if content_type:
response_headers.append(('content-type', content_type))
if content_encoding:
response_headers.append(('content-encoding', content_encoding))
self.conn.send_headers(stream_id, response_headers)
await self.sock.sendall(self.conn.data_to_send())
with open(file_path, 'rb', buffering=0) as f:
await self._send_file_data(f, stream_id) |
Send a file, obeying the rules of HTTP/2 flow control.
| send_file | python | python-hyper/h2 | examples/curio/curio-server.py | https://github.com/python-hyper/h2/blob/master/examples/curio/curio-server.py | MIT |
async def _send_file_data(self, fileobj, stream_id):
"""
Send the data portion of a file. Handles flow control rules.
"""
while True:
while self.conn.local_flow_control_window(stream_id) < 1:
await self.wait_for_flow_control(stream_id)
chunk_size = min(
self.conn.local_flow_control_window(stream_id),
READ_CHUNK_SIZE,
)
data = fileobj.read(chunk_size)
keep_reading = (len(data) == chunk_size)
self.conn.send_data(stream_id, data, not keep_reading)
await self.sock.sendall(self.conn.data_to_send())
if not keep_reading:
break |
Send the data portion of a file. Handles flow control rules.
| _send_file_data | python | python-hyper/h2 | examples/curio/curio-server.py | https://github.com/python-hyper/h2/blob/master/examples/curio/curio-server.py | MIT |
async def wait_for_flow_control(self, stream_id):
"""
Blocks until the flow control window for a given stream is opened.
"""
evt = Event()
self.flow_control_events[stream_id] = evt
await evt.wait() |
Blocks until the flow control window for a given stream is opened.
| wait_for_flow_control | python | python-hyper/h2 | examples/curio/curio-server.py | https://github.com/python-hyper/h2/blob/master/examples/curio/curio-server.py | MIT |
async def window_updated(self, event):
"""
Unblock streams waiting on flow control, if needed.
"""
stream_id = event.stream_id
if stream_id and stream_id in self.flow_control_events:
evt = self.flow_control_events.pop(stream_id)
await evt.set()
elif not stream_id:
# Need to keep a real list here to use only the events present at
# this time.
blocked_streams = list(self.flow_control_events.keys())
for stream_id in blocked_streams:
event = self.flow_control_events.pop(stream_id)
await event.set()
return |
Unblock streams waiting on flow control, if needed.
| window_updated | python | python-hyper/h2 | examples/curio/curio-server.py | https://github.com/python-hyper/h2/blob/master/examples/curio/curio-server.py | MIT |
def get_http2_ssl_context():
"""
This function creates an SSLContext object that is suitably configured for
HTTP/2. If you're working with Python TLS directly, you'll want to do the
exact same setup as this function does.
"""
# Get the basic context from the standard library.
ctx = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH)
# RFC 7540 Section 9.2: Implementations of HTTP/2 MUST use TLS version 1.2
# or higher. Disable TLS 1.1 and lower.
ctx.options |= (
ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1
)
# RFC 7540 Section 9.2.1: A deployment of HTTP/2 over TLS 1.2 MUST disable
# compression.
ctx.options |= ssl.OP_NO_COMPRESSION
# RFC 7540 Section 9.2.2: "deployments of HTTP/2 that use TLS 1.2 MUST
# support TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256". In practice, the
# blocklist defined in this section allows only the AES GCM and ChaCha20
# cipher suites with ephemeral key negotiation.
ctx.set_ciphers("ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20")
# We want to negotiate using NPN and ALPN. ALPN is mandatory, but NPN may
# be absent, so allow that. This setup allows for negotiation of HTTP/1.1.
ctx.set_alpn_protocols(["h2", "http/1.1"])
try:
ctx.set_npn_protocols(["h2", "http/1.1"])
except NotImplementedError:
pass
return ctx |
This function creates an SSLContext object that is suitably configured for
HTTP/2. If you're working with Python TLS directly, you'll want to do the
exact same setup as this function does.
| get_http2_ssl_context | python | python-hyper/h2 | examples/fragments/client_https_setup_fragment.py | https://github.com/python-hyper/h2/blob/master/examples/fragments/client_https_setup_fragment.py | MIT |
def send_initial_request(connection, settings):
"""
For the sake of this upgrade demonstration, we're going to issue a GET
request against the root of the site. In principle the best request to
issue for an upgrade is actually ``OPTIONS *``, but this is remarkably
poorly supported and can break in weird ways.
"""
# Craft our initial request per RFC 7540 Section 3.2. This requires two
# special header fields: the Upgrade headre, and the HTTP2-Settings header.
# The value of the HTTP2-Settings header field comes from h2.
request = (
b"GET / HTTP/1.1\r\n" +
b"Host: localhost\r\n" +
b"Upgrade: h2c\r\n" +
b"HTTP2-Settings: " + settings + b"\r\n" +
b"\r\n"
)
connection.sendall(request) |
For the sake of this upgrade demonstration, we're going to issue a GET
request against the root of the site. In principle the best request to
issue for an upgrade is actually ``OPTIONS *``, but this is remarkably
poorly supported and can break in weird ways.
| send_initial_request | python | python-hyper/h2 | examples/fragments/client_upgrade_fragment.py | https://github.com/python-hyper/h2/blob/master/examples/fragments/client_upgrade_fragment.py | MIT |
def get_upgrade_response(connection):
"""
This function reads from the socket until the HTTP/1.1 end-of-headers
sequence (CRLFCRLF) is received. It then checks what the status code of the
response is.
This is not a substitute for proper HTTP/1.1 parsing, but it's good enough
for example purposes.
"""
data = b''
while b'\r\n\r\n' not in data:
data += connection.recv(8192)
headers, rest = data.split(b'\r\n\r\n', 1)
# An upgrade response begins HTTP/1.1 101 Switching Protocols. Look for the
# code. In production code you should also check that the upgrade is to
# h2c, but here we know we only offered one upgrade so there's only one
# possible upgrade in use.
split_headers = headers.split()
if split_headers[1] != b'101':
raise RuntimeError("Not upgrading!")
# We don't care about the HTTP/1.1 data anymore, but we do care about
# any other data we read from the socket: this is going to be HTTP/2 data
# that must be passed to the H2Connection.
return rest |
This function reads from the socket until the HTTP/1.1 end-of-headers
sequence (CRLFCRLF) is received. It then checks what the status code of the
response is.
This is not a substitute for proper HTTP/1.1 parsing, but it's good enough
for example purposes.
| get_upgrade_response | python | python-hyper/h2 | examples/fragments/client_upgrade_fragment.py | https://github.com/python-hyper/h2/blob/master/examples/fragments/client_upgrade_fragment.py | MIT |
def establish_tcp_connection():
"""
This function establishes a server-side TCP connection. How it works isn't
very important to this example.
"""
bind_socket = socket.socket()
bind_socket.bind(('', 443))
bind_socket.listen(5)
return bind_socket.accept()[0] |
This function establishes a server-side TCP connection. How it works isn't
very important to this example.
| establish_tcp_connection | python | python-hyper/h2 | examples/fragments/server_https_setup_fragment.py | https://github.com/python-hyper/h2/blob/master/examples/fragments/server_https_setup_fragment.py | MIT |
def get_http2_ssl_context():
"""
This function creates an SSLContext object that is suitably configured for
HTTP/2. If you're working with Python TLS directly, you'll want to do the
exact same setup as this function does.
"""
# Get the basic context from the standard library.
ctx = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
# RFC 7540 Section 9.2: Implementations of HTTP/2 MUST use TLS version 1.2
# or higher. Disable TLS 1.1 and lower.
ctx.options |= (
ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1
)
# RFC 7540 Section 9.2.1: A deployment of HTTP/2 over TLS 1.2 MUST disable
# compression.
ctx.options |= ssl.OP_NO_COMPRESSION
# RFC 7540 Section 9.2.2: "deployments of HTTP/2 that use TLS 1.2 MUST
# support TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256". In practice, the
# blocklist defined in this section allows only the AES GCM and ChaCha20
# cipher suites with ephemeral key negotiation.
ctx.set_ciphers("ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20")
# We want to negotiate using NPN and ALPN. ALPN is mandatory, but NPN may
# be absent, so allow that. This setup allows for negotiation of HTTP/1.1.
ctx.set_alpn_protocols(["h2", "http/1.1"])
try:
ctx.set_npn_protocols(["h2", "http/1.1"])
except NotImplementedError:
pass
return ctx |
This function creates an SSLContext object that is suitably configured for
HTTP/2. If you're working with Python TLS directly, you'll want to do the
exact same setup as this function does.
| get_http2_ssl_context | python | python-hyper/h2 | examples/fragments/server_https_setup_fragment.py | https://github.com/python-hyper/h2/blob/master/examples/fragments/server_https_setup_fragment.py | MIT |
def establish_tcp_connection():
"""
This function establishes a server-side TCP connection. How it works isn't
very important to this example.
"""
bind_socket = socket.socket()
bind_socket.bind(('', 443))
bind_socket.listen(5)
return bind_socket.accept()[0] |
This function establishes a server-side TCP connection. How it works isn't
very important to this example.
| establish_tcp_connection | python | python-hyper/h2 | examples/fragments/server_upgrade_fragment.py | https://github.com/python-hyper/h2/blob/master/examples/fragments/server_upgrade_fragment.py | MIT |
def receive_initial_request(connection):
"""
We're going to receive a request. For the sake of this example, we're going
to assume that the first request has no body. If it doesn't have the
Upgrade: h2c header field and the HTTP2-Settings header field, we'll throw
errors.
In production code, you should use a proper HTTP/1.1 parser and actually
serve HTTP/1.1 requests!
Returns the value of the HTTP2-Settings header field.
"""
data = b''
while not data.endswith(b'\r\n\r\n'):
data += connection.recv(8192)
match = re.search(b'Upgrade: h2c\r\n', data)
if match is None:
raise RuntimeError("HTTP/2 upgrade not requested!")
# We need to look for the HTTP2-Settings header field. Again, in production
# code you shouldn't use regular expressions for this, but it's good enough
# for the example.
match = re.search(b'HTTP2-Settings: (\\S+)\r\n', data)
if match is None:
raise RuntimeError("HTTP2-Settings header field not present!")
return match.group(1) |
We're going to receive a request. For the sake of this example, we're going
to assume that the first request has no body. If it doesn't have the
Upgrade: h2c header field and the HTTP2-Settings header field, we'll throw
errors.
In production code, you should use a proper HTTP/1.1 parser and actually
serve HTTP/1.1 requests!
Returns the value of the HTTP2-Settings header field.
| receive_initial_request | python | python-hyper/h2 | examples/fragments/server_upgrade_fragment.py | https://github.com/python-hyper/h2/blob/master/examples/fragments/server_upgrade_fragment.py | MIT |
def send_upgrade_response(connection):
"""
This function writes the 101 Switching Protocols response.
"""
response = (
b"HTTP/1.1 101 Switching Protocols\r\n"
b"Upgrade: h2c\r\n"
b"\r\n"
)
connection.sendall(response) |
This function writes the 101 Switching Protocols response.
| send_upgrade_response | python | python-hyper/h2 | examples/fragments/server_upgrade_fragment.py | https://github.com/python-hyper/h2/blob/master/examples/fragments/server_upgrade_fragment.py | MIT |
def _send_file(self, file_path: Path, stream_id: int) -> None:
"""
Send a file, obeying the rules of HTTP/2 flow control.
"""
file_size = file_path.stat().st_size
content_type, content_encoding = mimetypes.guess_type(str(file_path))
response_headers = [
(':status', '200'),
('content-length', str(file_size)),
('server', self._server_name)
]
if content_type:
response_headers.append(('content-type', content_type))
if content_encoding:
response_headers.append(('content-encoding', content_encoding))
self._connection.send_headers(stream_id, response_headers)
self._sock.sendall(self._connection.data_to_send())
with file_path.open(mode='rb', buffering=0) as f:
self._send_file_data(f, stream_id) |
Send a file, obeying the rules of HTTP/2 flow control.
| _send_file | python | python-hyper/h2 | examples/gevent/gevent-server.py | https://github.com/python-hyper/h2/blob/master/examples/gevent/gevent-server.py | MIT |
def _send_file_data(self, file_obj, stream_id: int) -> None:
"""
Send the data portion of a file. Handles flow control rules.
"""
while True:
while self._connection.local_flow_control_window(stream_id) < 1:
self._wait_for_flow_control(stream_id)
chunk_size = min(self._connection.local_flow_control_window(stream_id), self._read_chunk_size)
data = file_obj.read(chunk_size)
keep_reading = (len(data) == chunk_size)
self._connection.send_data(stream_id, data, not keep_reading)
self._sock.sendall(self._connection.data_to_send())
if not keep_reading:
break |
Send the data portion of a file. Handles flow control rules.
| _send_file_data | python | python-hyper/h2 | examples/gevent/gevent-server.py | https://github.com/python-hyper/h2/blob/master/examples/gevent/gevent-server.py | MIT |
def _wait_for_flow_control(self, stream_id: int) -> None:
"""
Blocks until the flow control window for a given stream is opened.
"""
event = Event()
self._flow_control_events[stream_id] = event
event.wait() |
Blocks until the flow control window for a given stream is opened.
| _wait_for_flow_control | python | python-hyper/h2 | examples/gevent/gevent-server.py | https://github.com/python-hyper/h2/blob/master/examples/gevent/gevent-server.py | MIT |
def _handle_window_update(self, event: events.WindowUpdated) -> None:
"""
Unblock streams waiting on flow control, if needed.
"""
stream_id = event.stream_id
if stream_id and stream_id in self._flow_control_events:
g_event = self._flow_control_events.pop(stream_id)
g_event.set()
elif not stream_id:
# Need to keep a real list here to use only the events present at this time.
blocked_streams = list(self._flow_control_events.keys())
for stream_id in blocked_streams:
g_event = self._flow_control_events.pop(stream_id)
g_event.set() |
Unblock streams waiting on flow control, if needed.
| _handle_window_update | python | python-hyper/h2 | examples/gevent/gevent-server.py | https://github.com/python-hyper/h2/blob/master/examples/gevent/gevent-server.py | MIT |
def dataReceived(self, data):
"""
Called by Twisted when data is received on the connection.
We need to check a few things here. Firstly, we want to validate that
we actually negotiated HTTP/2: if we didn't, we shouldn't proceed!
Then, we want to pass the data to the protocol stack and check what
events occurred.
"""
if not self.known_proto:
self.known_proto = self.transport.negotiatedProtocol
assert self.known_proto == b'h2'
events = self.conn.receive_data(data)
for event in events:
if isinstance(event, ResponseReceived):
self.handleResponse(event.headers)
elif isinstance(event, DataReceived):
self.handleData(event.data)
elif isinstance(event, StreamEnded):
self.endStream()
elif isinstance(event, SettingsAcknowledged):
self.settingsAcked(event)
elif isinstance(event, StreamReset):
reactor.stop()
raise RuntimeError("Stream reset: %d" % event.error_code)
elif isinstance(event, WindowUpdated):
self.windowUpdated(event)
data = self.conn.data_to_send()
if data:
self.transport.write(data) |
Called by Twisted when data is received on the connection.
We need to check a few things here. Firstly, we want to validate that
we actually negotiated HTTP/2: if we didn't, we shouldn't proceed!
Then, we want to pass the data to the protocol stack and check what
events occurred.
| dataReceived | python | python-hyper/h2 | examples/twisted/post_request.py | https://github.com/python-hyper/h2/blob/master/examples/twisted/post_request.py | MIT |
def handleResponse(self, response_headers):
"""
Handle the response by printing the response headers.
"""
for name, value in response_headers:
print("%s: %s" % (name.decode('utf-8'), value.decode('utf-8')))
print("") |
Handle the response by printing the response headers.
| handleResponse | python | python-hyper/h2 | examples/twisted/post_request.py | https://github.com/python-hyper/h2/blob/master/examples/twisted/post_request.py | MIT |
def endStream(self):
"""
We call this when the stream is cleanly ended by the remote peer. That
means that the response is complete.
Because this code only makes a single HTTP/2 request, once we receive
the complete response we can safely tear the connection down and stop
the reactor. We do that as cleanly as possible.
"""
self.request_complete = True
self.conn.close_connection()
self.transport.write(self.conn.data_to_send())
self.transport.loseConnection() |
We call this when the stream is cleanly ended by the remote peer. That
means that the response is complete.
Because this code only makes a single HTTP/2 request, once we receive
the complete response we can safely tear the connection down and stop
the reactor. We do that as cleanly as possible.
| endStream | python | python-hyper/h2 | examples/twisted/post_request.py | https://github.com/python-hyper/h2/blob/master/examples/twisted/post_request.py | MIT |
def windowUpdated(self, event):
"""
We call this when the flow control window for the connection or the
stream has been widened. If there's a flow control deferred present
(that is, if we're blocked behind the flow control), we fire it.
Otherwise, we do nothing.
"""
if self.flow_control_deferred is None:
return
# Make sure we remove the flow control deferred to avoid firing it
# more than once.
flow_control_deferred = self.flow_control_deferred
self.flow_control_deferred = None
flow_control_deferred.callback(None) |
We call this when the flow control window for the connection or the
stream has been widened. If there's a flow control deferred present
(that is, if we're blocked behind the flow control), we fire it.
Otherwise, we do nothing.
| windowUpdated | python | python-hyper/h2 | examples/twisted/post_request.py | https://github.com/python-hyper/h2/blob/master/examples/twisted/post_request.py | MIT |
def connectionLost(self, reason=None):
"""
Called by Twisted when the connection is gone. Regardless of whether
it was clean or not, we want to stop the reactor.
"""
if self.fileobj is not None:
self.fileobj.close()
if reactor.running:
reactor.stop() |
Called by Twisted when the connection is gone. Regardless of whether
it was clean or not, we want to stop the reactor.
| connectionLost | python | python-hyper/h2 | examples/twisted/post_request.py | https://github.com/python-hyper/h2/blob/master/examples/twisted/post_request.py | MIT |
def sendRequest(self):
"""
Send the POST request.
A POST request is made up of one headers frame, and then 0+ data
frames. This method begins by sending the headers, and then starts a
series of calls to send data.
"""
# First, we need to work out how large the file is.
self.file_size = os.stat(self.file_path).st_size
# Next, we want to guess a content-type and content-encoding.
content_type, content_encoding = mimetypes.guess_type(self.file_path)
# Now we can build a header block.
request_headers = [
(':method', 'POST'),
(':authority', AUTHORITY),
(':scheme', 'https'),
(':path', PATH),
('content-length', str(self.file_size)),
]
if content_type is not None:
request_headers.append(('content-type', content_type))
if content_encoding is not None:
request_headers.append(('content-encoding', content_encoding))
self.conn.send_headers(1, request_headers)
self.request_made = True
# We can now open the file.
self.fileobj = open(self.file_path, 'rb')
# We now need to send all the relevant data. We do this by checking
# what the acceptable amount of data is to send, and sending it. If we
# find ourselves blocked behind flow control, we then place a deferred
# and wait until that deferred fires.
self.sendFileData() |
Send the POST request.
A POST request is made up of one headers frame, and then 0+ data
frames. This method begins by sending the headers, and then starts a
series of calls to send data.
| sendRequest | python | python-hyper/h2 | examples/twisted/post_request.py | https://github.com/python-hyper/h2/blob/master/examples/twisted/post_request.py | MIT |
def sendFileData(self):
"""
Send some file data on the connection.
"""
# Firstly, check what the flow control window is for stream 1.
window_size = self.conn.local_flow_control_window(stream_id=1)
# Next, check what the maximum frame size is.
max_frame_size = self.conn.max_outbound_frame_size
# We will send no more than the window size or the remaining file size
# of data in this call, whichever is smaller.
bytes_to_send = min(window_size, self.file_size)
# We now need to send a number of data frames.
while bytes_to_send > 0:
chunk_size = min(bytes_to_send, max_frame_size)
data_chunk = self.fileobj.read(chunk_size)
self.conn.send_data(stream_id=1, data=data_chunk)
bytes_to_send -= chunk_size
self.file_size -= chunk_size
# We've prepared a whole chunk of data to send. If the file is fully
# sent, we also want to end the stream: we're done here.
if self.file_size == 0:
self.conn.end_stream(stream_id=1)
else:
# We've still got data left to send but the window is closed. Save
# a Deferred that will call us when the window gets opened.
self.flow_control_deferred = defer.Deferred()
self.flow_control_deferred.addCallback(self.sendFileData)
self.transport.write(self.conn.data_to_send()) |
Send some file data on the connection.
| sendFileData | python | python-hyper/h2 | examples/twisted/post_request.py | https://github.com/python-hyper/h2/blob/master/examples/twisted/post_request.py | MIT |
def windowUpdated(self, event):
"""
Handle a WindowUpdated event by firing any waiting data sending
callbacks.
"""
stream_id = event.stream_id
if stream_id and stream_id in self._flow_control_deferreds:
d = self._flow_control_deferreds.pop(stream_id)
d.callback(event.delta)
elif not stream_id:
for d in self._flow_control_deferreds.values():
d.callback(event.delta)
self._flow_control_deferreds = {}
return |
Handle a WindowUpdated event by firing any waiting data sending
callbacks.
| windowUpdated | python | python-hyper/h2 | examples/twisted/twisted-server.py | https://github.com/python-hyper/h2/blob/master/examples/twisted/twisted-server.py | MIT |
def _send_file(self, file, stream_id):
"""
This callback sends more data for a given file on the stream.
"""
keep_reading = True
while keep_reading:
while not self.conn.remote_flow_control_window(stream_id):
yield self.wait_for_flow_control(stream_id)
chunk_size = min(
self.conn.remote_flow_control_window(stream_id), READ_CHUNK_SIZE
)
data = file.read(chunk_size)
keep_reading = len(data) == chunk_size
self.conn.send_data(stream_id, data, not keep_reading)
self.transport.write(self.conn.data_to_send())
if not keep_reading:
break
file.close() |
This callback sends more data for a given file on the stream.
| _send_file | python | python-hyper/h2 | examples/twisted/twisted-server.py | https://github.com/python-hyper/h2/blob/master/examples/twisted/twisted-server.py | MIT |
def wait_for_flow_control(self, stream_id):
"""
Returns a Deferred that fires when the flow control window is opened.
"""
d = Deferred()
self._flow_control_deferreds[stream_id] = d
return d |
Returns a Deferred that fires when the flow control window is opened.
| wait_for_flow_control | python | python-hyper/h2 | examples/twisted/twisted-server.py | https://github.com/python-hyper/h2/blob/master/examples/twisted/twisted-server.py | MIT |
def debug(self, *vargs, **kwargs) -> None: # type: ignore
"""
No-op logging. Only level needed for now.
""" |
No-op logging. Only level needed for now.
| debug | python | python-hyper/h2 | src/h2/config.py | https://github.com/python-hyper/h2/blob/master/src/h2/config.py | MIT |
def trace(self, *vargs, **kwargs) -> None: # type: ignore
"""
No-op logging. Only level needed for now.
""" |
No-op logging. Only level needed for now.
| trace | python | python-hyper/h2 | src/h2/config.py | https://github.com/python-hyper/h2/blob/master/src/h2/config.py | MIT |
def header_encoding(self, value: bool | str | None) -> None:
"""
Enforces constraints on the value of header encoding.
"""
if not isinstance(value, (bool, str, type(None))):
msg = "header_encoding must be bool, string, or None"
raise ValueError(msg) # noqa: TRY004
if value is True:
msg = "header_encoding cannot be True"
raise ValueError(msg)
self._header_encoding = value |
Enforces constraints on the value of header encoding.
| header_encoding | python | python-hyper/h2 | src/h2/config.py | https://github.com/python-hyper/h2/blob/master/src/h2/config.py | MIT |
def process_input(self, input_: ConnectionInputs) -> list[Event]:
"""
Process a specific input in the state machine.
"""
if not isinstance(input_, ConnectionInputs):
msg = "Input must be an instance of ConnectionInputs"
raise ValueError(msg) # noqa: TRY004
try:
func, target_state = self._transitions[(self.state, input_)]
except KeyError as e:
old_state = self.state
self.state = ConnectionState.CLOSED
msg = f"Invalid input {input_} in state {old_state}"
raise ProtocolError(msg) from e
else:
self.state = target_state
if func is not None: # pragma: no cover
return func()
return [] |
Process a specific input in the state machine.
| process_input | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _open_streams(self, remainder: int) -> int:
"""
A common method of counting number of open streams. Returns the number
of streams that are open *and* that have (stream ID % 2) == remainder.
While it iterates, also deletes any closed streams.
"""
count = 0
to_delete = []
for stream_id, stream in self.streams.items():
if stream.open and (stream_id % 2 == remainder):
count += 1
elif stream.closed:
to_delete.append(stream_id)
for stream_id in to_delete:
stream = self.streams.pop(stream_id)
self._closed_streams[stream_id] = stream.closed_by
return count |
A common method of counting number of open streams. Returns the number
of streams that are open *and* that have (stream ID % 2) == remainder.
While it iterates, also deletes any closed streams.
| _open_streams | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _begin_new_stream(self, stream_id: int, allowed_ids: AllowedStreamIDs) -> H2Stream:
"""
Initiate a new stream.
.. versionchanged:: 2.0.0
Removed this function from the public API.
:param stream_id: The ID of the stream to open.
:param allowed_ids: What kind of stream ID is allowed.
"""
self.config.logger.debug(
"Attempting to initiate stream ID %d", stream_id,
)
outbound = self._stream_id_is_outbound(stream_id)
highest_stream_id = (
self.highest_outbound_stream_id if outbound else
self.highest_inbound_stream_id
)
if stream_id <= highest_stream_id:
raise StreamIDTooLowError(stream_id, highest_stream_id)
if (stream_id % 2) != int(allowed_ids):
msg = "Invalid stream ID for peer."
raise ProtocolError(msg)
s = H2Stream(
stream_id,
config=self.config,
inbound_window_size=self.local_settings.initial_window_size,
outbound_window_size=self.remote_settings.initial_window_size,
)
self.config.logger.debug("Stream ID %d created", stream_id)
s.max_outbound_frame_size = self.max_outbound_frame_size
self.streams[stream_id] = s
self.config.logger.debug("Current streams: %s", self.streams.keys())
if outbound:
self.highest_outbound_stream_id = stream_id
else:
self.highest_inbound_stream_id = stream_id
return s |
Initiate a new stream.
.. versionchanged:: 2.0.0
Removed this function from the public API.
:param stream_id: The ID of the stream to open.
:param allowed_ids: What kind of stream ID is allowed.
| _begin_new_stream | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def initiate_connection(self) -> None:
"""
Provides any data that needs to be sent at the start of the connection.
Must be called for both clients and servers.
"""
self.config.logger.debug("Initializing connection")
self.state_machine.process_input(ConnectionInputs.SEND_SETTINGS)
if self.config.client_side:
preamble = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
else:
preamble = b""
f = SettingsFrame(0)
for setting, value in self.local_settings.items():
f.settings[setting] = value
self.config.logger.debug(
"Send Settings frame: %s", self.local_settings,
)
self._data_to_send += preamble + f.serialize() |
Provides any data that needs to be sent at the start of the connection.
Must be called for both clients and servers.
| initiate_connection | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def initiate_upgrade_connection(self, settings_header: bytes | None = None) -> bytes | None:
"""
Call to initialise the connection object for use with an upgraded
HTTP/2 connection (i.e. a connection negotiated using the
``Upgrade: h2c`` HTTP header).
This method differs from :meth:`initiate_connection
<h2.connection.H2Connection.initiate_connection>` in several ways.
Firstly, it handles the additional SETTINGS frame that is sent in the
``HTTP2-Settings`` header field. When called on a client connection,
this method will return a bytestring that the caller can put in the
``HTTP2-Settings`` field they send on their initial request. When
called on a server connection, the user **must** provide the value they
received from the client in the ``HTTP2-Settings`` header field to the
``settings_header`` argument, which will be used appropriately.
Additionally, this method sets up stream 1 in a half-closed state
appropriate for this side of the connection, to reflect the fact that
the request is already complete.
Finally, this method also prepares the appropriate preamble to be sent
after the upgrade.
.. versionadded:: 2.3.0
:param settings_header: (optional, server-only): The value of the
``HTTP2-Settings`` header field received from the client.
:type settings_header: ``bytes``
:returns: For clients, a bytestring to put in the ``HTTP2-Settings``.
For servers, returns nothing.
:rtype: ``bytes`` or ``None``
"""
self.config.logger.debug(
"Upgrade connection. Current settings: %s", self.local_settings,
)
frame_data = None
# Begin by getting the preamble in place.
self.initiate_connection()
if self.config.client_side:
f = SettingsFrame(0)
for setting, value in self.local_settings.items():
f.settings[setting] = value
frame_data = f.serialize_body()
frame_data = base64.urlsafe_b64encode(frame_data)
elif settings_header:
# We have a settings header from the client. This needs to be
# applied, but we want to throw away the ACK. We do this by
# inserting the data into a Settings frame and then passing it to
# the state machine, but ignoring the return value.
settings_header = base64.urlsafe_b64decode(settings_header)
f = SettingsFrame(0)
f.parse_body(memoryview(settings_header))
self._receive_settings_frame(f)
# Set up appropriate state. Stream 1 in a half-closed state:
# half-closed(local) for clients, half-closed(remote) for servers.
# Additionally, we need to set up the Connection state machine.
connection_input = (
ConnectionInputs.SEND_HEADERS if self.config.client_side
else ConnectionInputs.RECV_HEADERS
)
self.config.logger.debug("Process input %s", connection_input)
self.state_machine.process_input(connection_input)
# Set up stream 1.
self._begin_new_stream(stream_id=1, allowed_ids=AllowedStreamIDs.ODD)
self.streams[1].upgrade(self.config.client_side)
return frame_data |
Call to initialise the connection object for use with an upgraded
HTTP/2 connection (i.e. a connection negotiated using the
``Upgrade: h2c`` HTTP header).
This method differs from :meth:`initiate_connection
<h2.connection.H2Connection.initiate_connection>` in several ways.
Firstly, it handles the additional SETTINGS frame that is sent in the
``HTTP2-Settings`` header field. When called on a client connection,
this method will return a bytestring that the caller can put in the
``HTTP2-Settings`` field they send on their initial request. When
called on a server connection, the user **must** provide the value they
received from the client in the ``HTTP2-Settings`` header field to the
``settings_header`` argument, which will be used appropriately.
Additionally, this method sets up stream 1 in a half-closed state
appropriate for this side of the connection, to reflect the fact that
the request is already complete.
Finally, this method also prepares the appropriate preamble to be sent
after the upgrade.
.. versionadded:: 2.3.0
:param settings_header: (optional, server-only): The value of the
``HTTP2-Settings`` header field received from the client.
:type settings_header: ``bytes``
:returns: For clients, a bytestring to put in the ``HTTP2-Settings``.
For servers, returns nothing.
:rtype: ``bytes`` or ``None``
| initiate_upgrade_connection | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _get_or_create_stream(self, stream_id: int, allowed_ids: AllowedStreamIDs) -> H2Stream:
"""
Gets a stream by its stream ID. Will create one if one does not already
exist. Use allowed_ids to circumvent the usual stream ID rules for
clients and servers.
.. versionchanged:: 2.0.0
Removed this function from the public API.
"""
try:
return self.streams[stream_id]
except KeyError:
return self._begin_new_stream(stream_id, allowed_ids) |
Gets a stream by its stream ID. Will create one if one does not already
exist. Use allowed_ids to circumvent the usual stream ID rules for
clients and servers.
.. versionchanged:: 2.0.0
Removed this function from the public API.
| _get_or_create_stream | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _get_stream_by_id(self, stream_id: int | None) -> H2Stream:
"""
Gets a stream by its stream ID. Raises NoSuchStreamError if the stream
ID does not correspond to a known stream and is higher than the current
maximum: raises if it is lower than the current maximum.
.. versionchanged:: 2.0.0
Removed this function from the public API.
"""
if not stream_id:
raise NoSuchStreamError(-1) # pragma: no cover
try:
return self.streams[stream_id]
except KeyError as e:
outbound = self._stream_id_is_outbound(stream_id)
highest_stream_id = (
self.highest_outbound_stream_id if outbound else
self.highest_inbound_stream_id
)
if stream_id > highest_stream_id:
raise NoSuchStreamError(stream_id) from e
raise StreamClosedError(stream_id) from e |
Gets a stream by its stream ID. Raises NoSuchStreamError if the stream
ID does not correspond to a known stream and is higher than the current
maximum: raises if it is lower than the current maximum.
.. versionchanged:: 2.0.0
Removed this function from the public API.
| _get_stream_by_id | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def get_next_available_stream_id(self) -> int:
"""
Returns an integer suitable for use as the stream ID for the next
stream created by this endpoint. For server endpoints, this stream ID
will be even. For client endpoints, this stream ID will be odd. If no
stream IDs are available, raises :class:`NoAvailableStreamIDError
<h2.exceptions.NoAvailableStreamIDError>`.
.. warning:: The return value from this function does not change until
the stream ID has actually been used by sending or pushing
headers on that stream. For that reason, it should be
called as close as possible to the actual use of the
stream ID.
.. versionadded:: 2.0.0
:raises: :class:`NoAvailableStreamIDError
<h2.exceptions.NoAvailableStreamIDError>`
:returns: The next free stream ID this peer can use to initiate a
stream.
:rtype: ``int``
"""
# No streams have been opened yet, so return the lowest allowed stream
# ID.
if not self.highest_outbound_stream_id:
next_stream_id = 1 if self.config.client_side else 2
else:
next_stream_id = self.highest_outbound_stream_id + 2
self.config.logger.debug(
"Next available stream ID %d", next_stream_id,
)
if next_stream_id > self.HIGHEST_ALLOWED_STREAM_ID:
msg = "Exhausted allowed stream IDs"
raise NoAvailableStreamIDError(msg)
return next_stream_id |
Returns an integer suitable for use as the stream ID for the next
stream created by this endpoint. For server endpoints, this stream ID
will be even. For client endpoints, this stream ID will be odd. If no
stream IDs are available, raises :class:`NoAvailableStreamIDError
<h2.exceptions.NoAvailableStreamIDError>`.
.. warning:: The return value from this function does not change until
the stream ID has actually been used by sending or pushing
headers on that stream. For that reason, it should be
called as close as possible to the actual use of the
stream ID.
.. versionadded:: 2.0.0
:raises: :class:`NoAvailableStreamIDError
<h2.exceptions.NoAvailableStreamIDError>`
:returns: The next free stream ID this peer can use to initiate a
stream.
:rtype: ``int``
| get_next_available_stream_id | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def send_headers(self,
stream_id: int,
headers: Iterable[HeaderWeaklyTyped],
end_stream: bool = False,
priority_weight: int | None = None,
priority_depends_on: int | None = None,
priority_exclusive: bool | None = None) -> None:
"""
Send headers on a given stream.
This function can be used to send request or response headers: the kind
that are sent depends on whether this connection has been opened as a
client or server connection, and whether the stream was opened by the
remote peer or not.
If this is a client connection, calling ``send_headers`` will send the
headers as a request. It will also implicitly open the stream being
used. If this is a client connection and ``send_headers`` has *already*
been called, this will send trailers instead.
If this is a server connection, calling ``send_headers`` will send the
headers as a response. It is a protocol error for a server to open a
stream by sending headers. If this is a server connection and
``send_headers`` has *already* been called, this will send trailers
instead.
When acting as a server, you may call ``send_headers`` any number of
times allowed by the following rules, in this order:
- zero or more times with ``(':status', '1XX')`` (where ``1XX`` is a
placeholder for any 100-level status code).
- once with any other status header.
- zero or one time for trailers.
That is, you are allowed to send as many informational responses as you
like, followed by one complete response and zero or one HTTP trailer
blocks.
Clients may send one or two header blocks: one request block, and
optionally one trailer block.
If it is important to send HPACK "never indexed" header fields (as
defined in `RFC 7451 Section 7.1.3
<https://tools.ietf.org/html/rfc7541#section-7.1.3>`_), the user may
instead provide headers using the HPACK library's :class:`HeaderTuple
<hpack:hpack.HeaderTuple>` and :class:`NeverIndexedHeaderTuple
<hpack:hpack.NeverIndexedHeaderTuple>` objects.
This method also allows users to prioritize the stream immediately,
by sending priority information on the HEADERS frame directly. To do
this, any one of ``priority_weight``, ``priority_depends_on``, or
``priority_exclusive`` must be set to a value that is not ``None``. For
more information on the priority fields, see :meth:`prioritize
<h2.connection.H2Connection.prioritize>`.
.. warning:: In HTTP/2, it is mandatory that all the HTTP/2 special
headers (that is, ones whose header keys begin with ``:``) appear
at the start of the header block, before any normal headers.
.. versionchanged:: 2.3.0
Added support for using :class:`HeaderTuple
<hpack:hpack.HeaderTuple>` objects to store headers.
.. versionchanged:: 2.4.0
Added the ability to provide priority keyword arguments:
``priority_weight``, ``priority_depends_on``, and
``priority_exclusive``.
:param stream_id: The stream ID to send the headers on. If this stream
does not currently exist, it will be created.
:type stream_id: ``int``
:param headers: The request/response headers to send.
:type headers: An iterable of two tuples of bytestrings or
:class:`HeaderTuple <hpack:hpack.HeaderTuple>` objects.
:param end_stream: Whether this headers frame should end the stream
immediately (that is, whether no more data will be sent after this
frame). Defaults to ``False``.
:type end_stream: ``bool``
:param priority_weight: Sets the priority weight of the stream. See
:meth:`prioritize <h2.connection.H2Connection.prioritize>` for more
about how this field works. Defaults to ``None``, which means that
no priority information will be sent.
:type priority_weight: ``int`` or ``None``
:param priority_depends_on: Sets which stream this one depends on for
priority purposes. See :meth:`prioritize
<h2.connection.H2Connection.prioritize>` for more about how this
field works. Defaults to ``None``, which means that no priority
information will be sent.
:type priority_depends_on: ``int`` or ``None``
:param priority_exclusive: Sets whether this stream exclusively depends
on the stream given in ``priority_depends_on`` for priority
purposes. See :meth:`prioritize
<h2.connection.H2Connection.prioritize>` for more about how this
field workds. Defaults to ``None``, which means that no priority
information will be sent.
:type priority_depends_on: ``bool`` or ``None``
:returns: Nothing
"""
self.config.logger.debug(
"Send headers on stream ID %d", stream_id,
)
# Check we can open the stream.
if stream_id not in self.streams:
max_open_streams = self.remote_settings.max_concurrent_streams
value = self.open_outbound_streams # take a copy due to the property accessor having side affects
if (value + 1) > max_open_streams:
msg = f"Max outbound streams is {max_open_streams}, {value} open"
raise TooManyStreamsError(msg)
self.state_machine.process_input(ConnectionInputs.SEND_HEADERS)
stream = self._get_or_create_stream(
stream_id, AllowedStreamIDs(self.config.client_side),
)
frames: list[Frame] = []
frames.extend(stream.send_headers(
headers, self.encoder, end_stream,
))
# We may need to send priority information.
priority_present = (
(priority_weight is not None) or
(priority_depends_on is not None) or
(priority_exclusive is not None)
)
if priority_present:
if not self.config.client_side:
msg = "Servers SHOULD NOT prioritize streams."
raise RFC1122Error(msg)
headers_frame = frames[0]
assert isinstance(headers_frame, HeadersFrame)
headers_frame.flags.add("PRIORITY")
frames[0] = _add_frame_priority(
headers_frame,
priority_weight,
priority_depends_on,
priority_exclusive,
)
self._prepare_for_sending(frames) |
Send headers on a given stream.
This function can be used to send request or response headers: the kind
that are sent depends on whether this connection has been opened as a
client or server connection, and whether the stream was opened by the
remote peer or not.
If this is a client connection, calling ``send_headers`` will send the
headers as a request. It will also implicitly open the stream being
used. If this is a client connection and ``send_headers`` has *already*
been called, this will send trailers instead.
If this is a server connection, calling ``send_headers`` will send the
headers as a response. It is a protocol error for a server to open a
stream by sending headers. If this is a server connection and
``send_headers`` has *already* been called, this will send trailers
instead.
When acting as a server, you may call ``send_headers`` any number of
times allowed by the following rules, in this order:
- zero or more times with ``(':status', '1XX')`` (where ``1XX`` is a
placeholder for any 100-level status code).
- once with any other status header.
- zero or one time for trailers.
That is, you are allowed to send as many informational responses as you
like, followed by one complete response and zero or one HTTP trailer
blocks.
Clients may send one or two header blocks: one request block, and
optionally one trailer block.
If it is important to send HPACK "never indexed" header fields (as
defined in `RFC 7451 Section 7.1.3
<https://tools.ietf.org/html/rfc7541#section-7.1.3>`_), the user may
instead provide headers using the HPACK library's :class:`HeaderTuple
<hpack:hpack.HeaderTuple>` and :class:`NeverIndexedHeaderTuple
<hpack:hpack.NeverIndexedHeaderTuple>` objects.
This method also allows users to prioritize the stream immediately,
by sending priority information on the HEADERS frame directly. To do
this, any one of ``priority_weight``, ``priority_depends_on``, or
``priority_exclusive`` must be set to a value that is not ``None``. For
more information on the priority fields, see :meth:`prioritize
<h2.connection.H2Connection.prioritize>`.
.. warning:: In HTTP/2, it is mandatory that all the HTTP/2 special
headers (that is, ones whose header keys begin with ``:``) appear
at the start of the header block, before any normal headers.
.. versionchanged:: 2.3.0
Added support for using :class:`HeaderTuple
<hpack:hpack.HeaderTuple>` objects to store headers.
.. versionchanged:: 2.4.0
Added the ability to provide priority keyword arguments:
``priority_weight``, ``priority_depends_on``, and
``priority_exclusive``.
:param stream_id: The stream ID to send the headers on. If this stream
does not currently exist, it will be created.
:type stream_id: ``int``
:param headers: The request/response headers to send.
:type headers: An iterable of two tuples of bytestrings or
:class:`HeaderTuple <hpack:hpack.HeaderTuple>` objects.
:param end_stream: Whether this headers frame should end the stream
immediately (that is, whether no more data will be sent after this
frame). Defaults to ``False``.
:type end_stream: ``bool``
:param priority_weight: Sets the priority weight of the stream. See
:meth:`prioritize <h2.connection.H2Connection.prioritize>` for more
about how this field works. Defaults to ``None``, which means that
no priority information will be sent.
:type priority_weight: ``int`` or ``None``
:param priority_depends_on: Sets which stream this one depends on for
priority purposes. See :meth:`prioritize
<h2.connection.H2Connection.prioritize>` for more about how this
field works. Defaults to ``None``, which means that no priority
information will be sent.
:type priority_depends_on: ``int`` or ``None``
:param priority_exclusive: Sets whether this stream exclusively depends
on the stream given in ``priority_depends_on`` for priority
purposes. See :meth:`prioritize
<h2.connection.H2Connection.prioritize>` for more about how this
field workds. Defaults to ``None``, which means that no priority
information will be sent.
:type priority_depends_on: ``bool`` or ``None``
:returns: Nothing
| send_headers | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def send_data(self,
stream_id: int,
data: bytes | memoryview,
end_stream: bool = False,
pad_length: Any = None) -> None:
"""
Send data on a given stream.
This method does no breaking up of data: if the data is larger than the
value returned by :meth:`local_flow_control_window
<h2.connection.H2Connection.local_flow_control_window>` for this stream
then a :class:`FlowControlError <h2.exceptions.FlowControlError>` will
be raised. If the data is larger than :data:`max_outbound_frame_size
<h2.connection.H2Connection.max_outbound_frame_size>` then a
:class:`FrameTooLargeError <h2.exceptions.FrameTooLargeError>` will be
raised.
h2 does this to avoid buffering the data internally. If the user
has more data to send than h2 will allow, consider breaking it up
and buffering it externally.
:param stream_id: The ID of the stream on which to send the data.
:type stream_id: ``int``
:param data: The data to send on the stream.
:type data: ``bytes``
:param end_stream: (optional) Whether this is the last data to be sent
on the stream. Defaults to ``False``.
:type end_stream: ``bool``
:param pad_length: (optional) Length of the padding to apply to the
data frame. Defaults to ``None`` for no use of padding. Note that
a value of ``0`` results in padding of length ``0``
(with the "padding" flag set on the frame).
.. versionadded:: 2.6.0
:type pad_length: ``int``
:returns: Nothing
"""
self.config.logger.debug(
"Send data on stream ID %d with len %d", stream_id, len(data),
)
frame_size = len(data)
if pad_length is not None:
if not isinstance(pad_length, int):
msg = "pad_length must be an int"
raise TypeError(msg)
if pad_length < 0 or pad_length > 255:
msg = "pad_length must be within range: [0, 255]"
raise ValueError(msg)
# Account for padding bytes plus the 1-byte padding length field.
frame_size += pad_length + 1
self.config.logger.debug(
"Frame size on stream ID %d is %d", stream_id, frame_size,
)
if frame_size > self.local_flow_control_window(stream_id):
msg = f"Cannot send {frame_size} bytes, flow control window is {self.local_flow_control_window(stream_id)}"
raise FlowControlError(msg)
if frame_size > self.max_outbound_frame_size:
msg = f"Cannot send frame size {frame_size}, max frame size is {self.max_outbound_frame_size}"
raise FrameTooLargeError(msg)
self.state_machine.process_input(ConnectionInputs.SEND_DATA)
frames = self.streams[stream_id].send_data(
data, end_stream, pad_length=pad_length,
)
self._prepare_for_sending(frames)
self.outbound_flow_control_window -= frame_size
self.config.logger.debug(
"Outbound flow control window size is %d",
self.outbound_flow_control_window,
)
assert self.outbound_flow_control_window >= 0 |
Send data on a given stream.
This method does no breaking up of data: if the data is larger than the
value returned by :meth:`local_flow_control_window
<h2.connection.H2Connection.local_flow_control_window>` for this stream
then a :class:`FlowControlError <h2.exceptions.FlowControlError>` will
be raised. If the data is larger than :data:`max_outbound_frame_size
<h2.connection.H2Connection.max_outbound_frame_size>` then a
:class:`FrameTooLargeError <h2.exceptions.FrameTooLargeError>` will be
raised.
h2 does this to avoid buffering the data internally. If the user
has more data to send than h2 will allow, consider breaking it up
and buffering it externally.
:param stream_id: The ID of the stream on which to send the data.
:type stream_id: ``int``
:param data: The data to send on the stream.
:type data: ``bytes``
:param end_stream: (optional) Whether this is the last data to be sent
on the stream. Defaults to ``False``.
:type end_stream: ``bool``
:param pad_length: (optional) Length of the padding to apply to the
data frame. Defaults to ``None`` for no use of padding. Note that
a value of ``0`` results in padding of length ``0``
(with the "padding" flag set on the frame).
.. versionadded:: 2.6.0
:type pad_length: ``int``
:returns: Nothing
| send_data | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def end_stream(self, stream_id: int) -> None:
"""
Cleanly end a given stream.
This method ends a stream by sending an empty DATA frame on that stream
with the ``END_STREAM`` flag set.
:param stream_id: The ID of the stream to end.
:type stream_id: ``int``
:returns: Nothing
"""
self.config.logger.debug("End stream ID %d", stream_id)
self.state_machine.process_input(ConnectionInputs.SEND_DATA)
frames = self.streams[stream_id].end_stream()
self._prepare_for_sending(frames) |
Cleanly end a given stream.
This method ends a stream by sending an empty DATA frame on that stream
with the ``END_STREAM`` flag set.
:param stream_id: The ID of the stream to end.
:type stream_id: ``int``
:returns: Nothing
| end_stream | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def increment_flow_control_window(self, increment: int, stream_id: int | None = None) -> None:
"""
Increment a flow control window, optionally for a single stream. Allows
the remote peer to send more data.
.. versionchanged:: 2.0.0
Rejects attempts to increment the flow control window by out of
range values with a ``ValueError``.
:param increment: The amount to increment the flow control window by.
:type increment: ``int``
:param stream_id: (optional) The ID of the stream that should have its
flow control window opened. If not present or ``None``, the
connection flow control window will be opened instead.
:type stream_id: ``int`` or ``None``
:returns: Nothing
:raises: ``ValueError``
"""
if not (1 <= increment <= self.MAX_WINDOW_INCREMENT):
msg = f"Flow control increment must be between 1 and {self.MAX_WINDOW_INCREMENT}"
raise ValueError(msg)
self.state_machine.process_input(ConnectionInputs.SEND_WINDOW_UPDATE)
if stream_id is not None:
stream = self.streams[stream_id]
frames = stream.increase_flow_control_window(
increment,
)
self.config.logger.debug(
"Increase stream ID %d flow control window by %d",
stream_id, increment,
)
else:
self._inbound_flow_control_window_manager.window_opened(increment)
f = WindowUpdateFrame(0)
f.window_increment = increment
frames = [f]
self.config.logger.debug(
"Increase connection flow control window by %d", increment,
)
self._prepare_for_sending(frames) |
Increment a flow control window, optionally for a single stream. Allows
the remote peer to send more data.
.. versionchanged:: 2.0.0
Rejects attempts to increment the flow control window by out of
range values with a ``ValueError``.
:param increment: The amount to increment the flow control window by.
:type increment: ``int``
:param stream_id: (optional) The ID of the stream that should have its
flow control window opened. If not present or ``None``, the
connection flow control window will be opened instead.
:type stream_id: ``int`` or ``None``
:returns: Nothing
:raises: ``ValueError``
| increment_flow_control_window | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def ping(self, opaque_data: bytes | str) -> None:
"""
Send a PING frame.
:param opaque_data: A bytestring of length 8 that will be sent in the
PING frame.
:returns: Nothing
"""
self.config.logger.debug("Send Ping frame")
if not isinstance(opaque_data, bytes) or len(opaque_data) != 8:
msg = f"Invalid value for ping data: {opaque_data!r}"
raise ValueError(msg)
self.state_machine.process_input(ConnectionInputs.SEND_PING)
f = PingFrame(0)
f.opaque_data = opaque_data
self._prepare_for_sending([f]) |
Send a PING frame.
:param opaque_data: A bytestring of length 8 that will be sent in the
PING frame.
:returns: Nothing
| ping | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def reset_stream(self, stream_id: int, error_code: ErrorCodes | int = 0) -> None:
"""
Reset a stream.
This method forcibly closes a stream by sending a RST_STREAM frame for
a given stream. This is not a graceful closure. To gracefully end a
stream, try the :meth:`end_stream
<h2.connection.H2Connection.end_stream>` method.
:param stream_id: The ID of the stream to reset.
:type stream_id: ``int``
:param error_code: (optional) The error code to use to reset the
stream. Defaults to :data:`ErrorCodes.NO_ERROR
<h2.errors.ErrorCodes.NO_ERROR>`.
:type error_code: ``int``
:returns: Nothing
"""
self.config.logger.debug("Reset stream ID %d", stream_id)
self.state_machine.process_input(ConnectionInputs.SEND_RST_STREAM)
stream = self._get_stream_by_id(stream_id)
frames = stream.reset_stream(error_code)
self._prepare_for_sending(frames) |
Reset a stream.
This method forcibly closes a stream by sending a RST_STREAM frame for
a given stream. This is not a graceful closure. To gracefully end a
stream, try the :meth:`end_stream
<h2.connection.H2Connection.end_stream>` method.
:param stream_id: The ID of the stream to reset.
:type stream_id: ``int``
:param error_code: (optional) The error code to use to reset the
stream. Defaults to :data:`ErrorCodes.NO_ERROR
<h2.errors.ErrorCodes.NO_ERROR>`.
:type error_code: ``int``
:returns: Nothing
| reset_stream | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def advertise_alternative_service(self,
field_value: bytes | str,
origin: bytes | None = None,
stream_id: int | None = None) -> None:
"""
Notify a client about an available Alternative Service.
An Alternative Service is defined in `RFC 7838
<https://tools.ietf.org/html/rfc7838>`_. An Alternative Service
notification informs a client that a given origin is also available
elsewhere.
Alternative Services can be advertised in two ways. Firstly, they can
be advertised explicitly: that is, a server can say "origin X is also
available at Y". To advertise like this, set the ``origin`` argument
and not the ``stream_id`` argument. Alternatively, they can be
advertised implicitly: that is, a server can say "the origin you're
contacting on stream X is also available at Y". To advertise like this,
set the ``stream_id`` argument and not the ``origin`` argument.
The explicit method of advertising can be done as long as the
connection is active. The implicit method can only be done after the
client has sent the request headers and before the server has sent the
response headers: outside of those points, h2 will forbid sending
the Alternative Service advertisement by raising a ProtocolError.
The ``field_value`` parameter is specified in RFC 7838. h2 does
not validate or introspect this argument: the user is required to
ensure that it's well-formed. ``field_value`` corresponds to RFC 7838's
"Alternative Service Field Value".
.. note:: It is strongly preferred to use the explicit method of
advertising Alternative Services. The implicit method of
advertising Alternative Services has a number of subtleties
and can lead to inconsistencies between the server and
client. h2 allows both mechanisms, but caution is
strongly advised.
.. versionadded:: 2.3.0
:param field_value: The RFC 7838 Alternative Service Field Value. This
argument is not introspected by h2: the user is responsible
for ensuring that it is well-formed.
:type field_value: ``bytes``
:param origin: The origin/authority to which the Alternative Service
being advertised applies. Must not be provided at the same time as
``stream_id``.
:type origin: ``bytes`` or ``None``
:param stream_id: The ID of the stream which was sent to the authority
for which this Alternative Service advertisement applies. Must not
be provided at the same time as ``origin``.
:type stream_id: ``int`` or ``None``
:returns: Nothing.
"""
if not isinstance(field_value, bytes):
msg = "Field must be bytestring."
raise ValueError(msg) # noqa: TRY004
if origin is not None and stream_id is not None:
msg = "Must not provide both origin and stream_id"
raise ValueError(msg)
self.state_machine.process_input(
ConnectionInputs.SEND_ALTERNATIVE_SERVICE,
)
if origin is not None:
# This ALTSVC is sent on stream zero.
f = AltSvcFrame(stream_id=0)
f.origin = origin
f.field = field_value
frames: list[Frame] = [f]
else:
stream = self._get_stream_by_id(stream_id)
frames = stream.advertise_alternative_service(field_value)
self._prepare_for_sending(frames) |
Notify a client about an available Alternative Service.
An Alternative Service is defined in `RFC 7838
<https://tools.ietf.org/html/rfc7838>`_. An Alternative Service
notification informs a client that a given origin is also available
elsewhere.
Alternative Services can be advertised in two ways. Firstly, they can
be advertised explicitly: that is, a server can say "origin X is also
available at Y". To advertise like this, set the ``origin`` argument
and not the ``stream_id`` argument. Alternatively, they can be
advertised implicitly: that is, a server can say "the origin you're
contacting on stream X is also available at Y". To advertise like this,
set the ``stream_id`` argument and not the ``origin`` argument.
The explicit method of advertising can be done as long as the
connection is active. The implicit method can only be done after the
client has sent the request headers and before the server has sent the
response headers: outside of those points, h2 will forbid sending
the Alternative Service advertisement by raising a ProtocolError.
The ``field_value`` parameter is specified in RFC 7838. h2 does
not validate or introspect this argument: the user is required to
ensure that it's well-formed. ``field_value`` corresponds to RFC 7838's
"Alternative Service Field Value".
.. note:: It is strongly preferred to use the explicit method of
advertising Alternative Services. The implicit method of
advertising Alternative Services has a number of subtleties
and can lead to inconsistencies between the server and
client. h2 allows both mechanisms, but caution is
strongly advised.
.. versionadded:: 2.3.0
:param field_value: The RFC 7838 Alternative Service Field Value. This
argument is not introspected by h2: the user is responsible
for ensuring that it is well-formed.
:type field_value: ``bytes``
:param origin: The origin/authority to which the Alternative Service
being advertised applies. Must not be provided at the same time as
``stream_id``.
:type origin: ``bytes`` or ``None``
:param stream_id: The ID of the stream which was sent to the authority
for which this Alternative Service advertisement applies. Must not
be provided at the same time as ``origin``.
:type stream_id: ``int`` or ``None``
:returns: Nothing.
| advertise_alternative_service | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def prioritize(self,
stream_id: int,
weight: int | None = None,
depends_on: int | None = None,
exclusive: bool | None = None) -> None:
"""
Notify a server about the priority of a stream.
Stream priorities are a form of guidance to a remote server: they
inform the server about how important a given response is, so that the
server may allocate its resources (e.g. bandwidth, CPU time, etc.)
accordingly. This exists to allow clients to ensure that the most
important data arrives earlier, while less important data does not
starve out the more important data.
Stream priorities are explained in depth in `RFC 7540 Section 5.3
<https://tools.ietf.org/html/rfc7540#section-5.3>`_.
This method updates the priority information of a single stream. It may
be called well before a stream is actively in use, or well after a
stream is closed.
.. warning:: RFC 7540 allows for servers to change the priority of
streams. However, h2 **does not** allow server
stacks to do this. This is because most clients do not
adequately know how to respond when provided conflicting
priority information, and relatively little utility is
provided by making that functionality available.
.. note:: h2 **does not** maintain any information about the
RFC 7540 priority tree. That means that h2 does not
prevent incautious users from creating invalid priority
trees, particularly by creating priority loops. While some
basic error checking is provided by h2, users are
strongly recommended to understand their prioritisation
strategies before using the priority tools here.
.. note:: Priority information is strictly advisory. Servers are
allowed to disregard it entirely. Avoid relying on the idea
that your priority signaling will definitely be obeyed.
.. versionadded:: 2.4.0
:param stream_id: The ID of the stream to prioritize.
:type stream_id: ``int``
:param weight: The weight to give the stream. Defaults to ``16``, the
default weight of any stream. May be any value between ``1`` and
``256`` inclusive. The relative weight of a stream indicates what
proportion of available resources will be allocated to that
stream.
:type weight: ``int``
:param depends_on: The ID of the stream on which this stream depends.
This stream will only be progressed if it is impossible to
progress the parent stream (the one on which this one depends).
Passing the value ``0`` means that this stream does not depend on
any other. Defaults to ``0``.
:type depends_on: ``int``
:param exclusive: Whether this stream is an exclusive dependency of its
"parent" stream (i.e. the stream given by ``depends_on``). If a
stream is an exclusive dependency of another, that means that all
previously-set children of the parent are moved to become children
of the new exclusively-dependent stream. Defaults to ``False``.
:type exclusive: ``bool``
"""
if not self.config.client_side:
msg = "Servers SHOULD NOT prioritize streams."
raise RFC1122Error(msg)
self.state_machine.process_input(
ConnectionInputs.SEND_PRIORITY,
)
frame = PriorityFrame(stream_id)
frame_prio = _add_frame_priority(frame, weight, depends_on, exclusive)
self._prepare_for_sending([frame_prio]) |
Notify a server about the priority of a stream.
Stream priorities are a form of guidance to a remote server: they
inform the server about how important a given response is, so that the
server may allocate its resources (e.g. bandwidth, CPU time, etc.)
accordingly. This exists to allow clients to ensure that the most
important data arrives earlier, while less important data does not
starve out the more important data.
Stream priorities are explained in depth in `RFC 7540 Section 5.3
<https://tools.ietf.org/html/rfc7540#section-5.3>`_.
This method updates the priority information of a single stream. It may
be called well before a stream is actively in use, or well after a
stream is closed.
.. warning:: RFC 7540 allows for servers to change the priority of
streams. However, h2 **does not** allow server
stacks to do this. This is because most clients do not
adequately know how to respond when provided conflicting
priority information, and relatively little utility is
provided by making that functionality available.
.. note:: h2 **does not** maintain any information about the
RFC 7540 priority tree. That means that h2 does not
prevent incautious users from creating invalid priority
trees, particularly by creating priority loops. While some
basic error checking is provided by h2, users are
strongly recommended to understand their prioritisation
strategies before using the priority tools here.
.. note:: Priority information is strictly advisory. Servers are
allowed to disregard it entirely. Avoid relying on the idea
that your priority signaling will definitely be obeyed.
.. versionadded:: 2.4.0
:param stream_id: The ID of the stream to prioritize.
:type stream_id: ``int``
:param weight: The weight to give the stream. Defaults to ``16``, the
default weight of any stream. May be any value between ``1`` and
``256`` inclusive. The relative weight of a stream indicates what
proportion of available resources will be allocated to that
stream.
:type weight: ``int``
:param depends_on: The ID of the stream on which this stream depends.
This stream will only be progressed if it is impossible to
progress the parent stream (the one on which this one depends).
Passing the value ``0`` means that this stream does not depend on
any other. Defaults to ``0``.
:type depends_on: ``int``
:param exclusive: Whether this stream is an exclusive dependency of its
"parent" stream (i.e. the stream given by ``depends_on``). If a
stream is an exclusive dependency of another, that means that all
previously-set children of the parent are moved to become children
of the new exclusively-dependent stream. Defaults to ``False``.
:type exclusive: ``bool``
| prioritize | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def local_flow_control_window(self, stream_id: int) -> int:
"""
Returns the maximum amount of data that can be sent on stream
``stream_id``.
This value will never be larger than the total data that can be sent on
the connection: even if the given stream allows more data, the
connection window provides a logical maximum to the amount of data that
can be sent.
The maximum data that can be sent in a single data frame on a stream
is either this value, or the maximum frame size, whichever is
*smaller*.
:param stream_id: The ID of the stream whose flow control window is
being queried.
:type stream_id: ``int``
:returns: The amount of data in bytes that can be sent on the stream
before the flow control window is exhausted.
:rtype: ``int``
"""
stream = self._get_stream_by_id(stream_id)
return min(
self.outbound_flow_control_window,
stream.outbound_flow_control_window,
) |
Returns the maximum amount of data that can be sent on stream
``stream_id``.
This value will never be larger than the total data that can be sent on
the connection: even if the given stream allows more data, the
connection window provides a logical maximum to the amount of data that
can be sent.
The maximum data that can be sent in a single data frame on a stream
is either this value, or the maximum frame size, whichever is
*smaller*.
:param stream_id: The ID of the stream whose flow control window is
being queried.
:type stream_id: ``int``
:returns: The amount of data in bytes that can be sent on the stream
before the flow control window is exhausted.
:rtype: ``int``
| local_flow_control_window | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def remote_flow_control_window(self, stream_id: int) -> int:
"""
Returns the maximum amount of data the remote peer can send on stream
``stream_id``.
This value will never be larger than the total data that can be sent on
the connection: even if the given stream allows more data, the
connection window provides a logical maximum to the amount of data that
can be sent.
The maximum data that can be sent in a single data frame on a stream
is either this value, or the maximum frame size, whichever is
*smaller*.
:param stream_id: The ID of the stream whose flow control window is
being queried.
:type stream_id: ``int``
:returns: The amount of data in bytes that can be received on the
stream before the flow control window is exhausted.
:rtype: ``int``
"""
stream = self._get_stream_by_id(stream_id)
return min(
self.inbound_flow_control_window,
stream.inbound_flow_control_window,
) |
Returns the maximum amount of data the remote peer can send on stream
``stream_id``.
This value will never be larger than the total data that can be sent on
the connection: even if the given stream allows more data, the
connection window provides a logical maximum to the amount of data that
can be sent.
The maximum data that can be sent in a single data frame on a stream
is either this value, or the maximum frame size, whichever is
*smaller*.
:param stream_id: The ID of the stream whose flow control window is
being queried.
:type stream_id: ``int``
:returns: The amount of data in bytes that can be received on the
stream before the flow control window is exhausted.
:rtype: ``int``
| remote_flow_control_window | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def acknowledge_received_data(self, acknowledged_size: int, stream_id: int) -> None:
"""
Inform the :class:`H2Connection <h2.connection.H2Connection>` that a
certain number of flow-controlled bytes have been processed, and that
the space should be handed back to the remote peer at an opportune
time.
.. versionadded:: 2.5.0
:param acknowledged_size: The total *flow-controlled size* of the data
that has been processed. Note that this must include the amount of
padding that was sent with that data.
:type acknowledged_size: ``int``
:param stream_id: The ID of the stream on which this data was received.
:type stream_id: ``int``
:returns: Nothing
:rtype: ``None``
"""
self.config.logger.debug(
"Ack received data on stream ID %d with size %d",
stream_id, acknowledged_size,
)
if stream_id <= 0:
msg = f"Stream ID {stream_id} is not valid for acknowledge_received_data"
raise ValueError(msg)
if acknowledged_size < 0:
msg = "Cannot acknowledge negative data"
raise ValueError(msg)
frames: list[Frame] = []
conn_manager = self._inbound_flow_control_window_manager
conn_increment = conn_manager.process_bytes(acknowledged_size)
if conn_increment:
f = WindowUpdateFrame(0)
f.window_increment = conn_increment
frames.append(f)
try:
stream = self._get_stream_by_id(stream_id)
except StreamClosedError:
# The stream is already gone. We're not worried about incrementing
# the window in this case.
pass
else:
# No point incrementing the windows of closed streams.
if stream.open:
frames.extend(
stream.acknowledge_received_data(acknowledged_size),
)
self._prepare_for_sending(frames) |
Inform the :class:`H2Connection <h2.connection.H2Connection>` that a
certain number of flow-controlled bytes have been processed, and that
the space should be handed back to the remote peer at an opportune
time.
.. versionadded:: 2.5.0
:param acknowledged_size: The total *flow-controlled size* of the data
that has been processed. Note that this must include the amount of
padding that was sent with that data.
:type acknowledged_size: ``int``
:param stream_id: The ID of the stream on which this data was received.
:type stream_id: ``int``
:returns: Nothing
:rtype: ``None``
| acknowledge_received_data | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def data_to_send(self, amount: int | None = None) -> bytes:
"""
Returns some data for sending out of the internal data buffer.
This method is analogous to ``read`` on a file-like object, but it
doesn't block. Instead, it returns as much data as the user asks for,
or less if that much data is not available. It does not perform any
I/O, and so uses a different name.
:param amount: (optional) The maximum amount of data to return. If not
set, or set to ``None``, will return as much data as possible.
:type amount: ``int``
:returns: A bytestring containing the data to send on the wire.
:rtype: ``bytes``
"""
if amount is None:
data = bytes(self._data_to_send)
self._data_to_send = bytearray()
return data
data = bytes(self._data_to_send[:amount])
self._data_to_send = self._data_to_send[amount:]
return data |
Returns some data for sending out of the internal data buffer.
This method is analogous to ``read`` on a file-like object, but it
doesn't block. Instead, it returns as much data as the user asks for,
or less if that much data is not available. It does not perform any
I/O, and so uses a different name.
:param amount: (optional) The maximum amount of data to return. If not
set, or set to ``None``, will return as much data as possible.
:type amount: ``int``
:returns: A bytestring containing the data to send on the wire.
:rtype: ``bytes``
| data_to_send | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _acknowledge_settings(self) -> list[Frame]:
"""
Acknowledge settings that have been received.
.. versionchanged:: 2.0.0
Removed from public API, removed useless ``event`` parameter, made
automatic.
:returns: Nothing
"""
self.state_machine.process_input(ConnectionInputs.SEND_SETTINGS)
changes = self.remote_settings.acknowledge()
if SettingCodes.INITIAL_WINDOW_SIZE in changes:
setting = changes[SettingCodes.INITIAL_WINDOW_SIZE]
self._flow_control_change_from_settings(
setting.original_value,
setting.new_value,
)
# HEADER_TABLE_SIZE changes by the remote part affect our encoder: cf.
# RFC 7540 Section 6.5.2.
if SettingCodes.HEADER_TABLE_SIZE in changes:
setting = changes[SettingCodes.HEADER_TABLE_SIZE]
self.encoder.header_table_size = setting.new_value
if SettingCodes.MAX_FRAME_SIZE in changes:
setting = changes[SettingCodes.MAX_FRAME_SIZE]
self.max_outbound_frame_size = setting.new_value
for stream in self.streams.values():
stream.max_outbound_frame_size = setting.new_value
f = SettingsFrame(0)
f.flags.add("ACK")
return [f] |
Acknowledge settings that have been received.
.. versionchanged:: 2.0.0
Removed from public API, removed useless ``event`` parameter, made
automatic.
:returns: Nothing
| _acknowledge_settings | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _flow_control_change_from_settings(self, old_value: int | None, new_value: int) -> None:
"""
Update flow control windows in response to a change in the value of
SETTINGS_INITIAL_WINDOW_SIZE.
When this setting is changed, it automatically updates all flow control
windows by the delta in the settings values. Note that it does not
increment the *connection* flow control window, per section 6.9.2 of
RFC 7540.
"""
delta = new_value - (old_value or 0)
for stream in self.streams.values():
stream.outbound_flow_control_window = guard_increment_window(
stream.outbound_flow_control_window,
delta,
) |
Update flow control windows in response to a change in the value of
SETTINGS_INITIAL_WINDOW_SIZE.
When this setting is changed, it automatically updates all flow control
windows by the delta in the settings values. Note that it does not
increment the *connection* flow control window, per section 6.9.2 of
RFC 7540.
| _flow_control_change_from_settings | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _inbound_flow_control_change_from_settings(self, old_value: int | None, new_value: int) -> None:
"""
Update remote flow control windows in response to a change in the value
of SETTINGS_INITIAL_WINDOW_SIZE.
When this setting is changed, it automatically updates all remote flow
control windows by the delta in the settings values.
"""
delta = new_value - (old_value or 0)
for stream in self.streams.values():
stream._inbound_flow_control_change_from_settings(delta) |
Update remote flow control windows in response to a change in the value
of SETTINGS_INITIAL_WINDOW_SIZE.
When this setting is changed, it automatically updates all remote flow
control windows by the delta in the settings values.
| _inbound_flow_control_change_from_settings | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def receive_data(self, data: bytes) -> list[Event]:
"""
Pass some received HTTP/2 data to the connection for handling.
:param data: The data received from the remote peer on the network.
:type data: ``bytes``
:returns: A list of events that the remote peer triggered by sending
this data.
"""
self.config.logger.trace(
"Process received data on connection. Received data: %r", data,
)
events: list[Event] = []
self.incoming_buffer.add_data(data)
self.incoming_buffer.max_frame_size = self.max_inbound_frame_size
try:
for frame in self.incoming_buffer:
events.extend(self._receive_frame(frame))
except InvalidPaddingError as e:
self._terminate_connection(ErrorCodes.PROTOCOL_ERROR)
msg = "Received frame with invalid padding."
raise ProtocolError(msg) from e
except ProtocolError as e:
# For whatever reason, receiving the frame caused a protocol error.
# We should prepare to emit a GoAway frame before throwing the
# exception up further. No need for an event: the exception will
# do fine.
self._terminate_connection(e.error_code)
raise
return events |
Pass some received HTTP/2 data to the connection for handling.
:param data: The data received from the remote peer on the network.
:type data: ``bytes``
:returns: A list of events that the remote peer triggered by sending
this data.
| receive_data | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _receive_frame(self, frame: Frame) -> list[Event]:
"""
Handle a frame received on the connection.
.. versionchanged:: 2.0.0
Removed from the public API.
"""
events: list[Event]
self.config.logger.trace("Received frame: %s", repr(frame))
try:
# I don't love using __class__ here, maybe reconsider it.
frames, events = self._frame_dispatch_table[frame.__class__](frame)
except StreamClosedError as e:
# If the stream was closed by RST_STREAM, we just send a RST_STREAM
# to the remote peer. Otherwise, this is a connection error, and so
# we will re-raise to trigger one.
if self._stream_is_closed_by_reset(e.stream_id):
f = RstStreamFrame(e.stream_id)
f.error_code = e.error_code
self._prepare_for_sending([f])
events = e._events
else:
raise
except StreamIDTooLowError as e:
# The stream ID seems invalid. This may happen when the closed
# stream has been cleaned up, or when the remote peer has opened a
# new stream with a higher stream ID than this one, forcing it
# closed implicitly.
#
# Check how the stream was closed: depending on the mechanism, it
# is either a stream error or a connection error.
if self._stream_is_closed_by_reset(e.stream_id):
# Closed by RST_STREAM is a stream error.
f = RstStreamFrame(e.stream_id)
f.error_code = ErrorCodes.STREAM_CLOSED
self._prepare_for_sending([f])
events = []
elif self._stream_is_closed_by_end(e.stream_id):
# Closed by END_STREAM is a connection error.
raise StreamClosedError(e.stream_id) from e
else:
# Closed implicitly, also a connection error, but of type
# PROTOCOL_ERROR.
raise
else:
self._prepare_for_sending(frames)
return events |
Handle a frame received on the connection.
.. versionchanged:: 2.0.0
Removed from the public API.
| _receive_frame | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _terminate_connection(self, error_code: ErrorCodes) -> None:
"""
Terminate the connection early. Used in error handling blocks to send
GOAWAY frames.
"""
f = GoAwayFrame(0)
f.last_stream_id = self.highest_inbound_stream_id
f.error_code = error_code
self.state_machine.process_input(ConnectionInputs.SEND_GOAWAY)
self._prepare_for_sending([f]) |
Terminate the connection early. Used in error handling blocks to send
GOAWAY frames.
| _terminate_connection | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _receive_headers_frame(self, frame: HeadersFrame) -> tuple[list[Frame], list[Event]]:
"""
Receive a headers frame on the connection.
"""
# If necessary, check we can open the stream. Also validate that the
# stream ID is valid.
if frame.stream_id not in self.streams:
max_open_streams = self.local_settings.max_concurrent_streams
value = self.open_inbound_streams # take a copy due to the property accessor having side affects
if (value + 1) > max_open_streams:
msg = f"Max inbound streams is {max_open_streams}, {value} open"
raise TooManyStreamsError(msg)
# Let's decode the headers. We handle headers as bytes internally up
# until we hang them off the event, at which point we may optionally
# convert them to unicode.
headers = _decode_headers(self.decoder, frame.data)
events = self.state_machine.process_input(
ConnectionInputs.RECV_HEADERS,
)
stream = self._get_or_create_stream(
frame.stream_id, AllowedStreamIDs(not self.config.client_side),
)
frames, stream_events = stream.receive_headers(
headers,
"END_STREAM" in frame.flags,
self.config.header_encoding,
)
if "PRIORITY" in frame.flags:
p_frames, p_events = self._receive_priority_frame(frame)
expected_frame_types = (RequestReceived, ResponseReceived, TrailersReceived, InformationalResponseReceived)
assert isinstance(stream_events[0], expected_frame_types)
assert isinstance(p_events[0], PriorityUpdated)
stream_events[0].priority_updated = p_events[0]
stream_events.extend(p_events)
assert not p_frames
return frames, events + stream_events |
Receive a headers frame on the connection.
| _receive_headers_frame | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _receive_data_frame(self, frame: DataFrame) -> tuple[list[Frame], list[Event]]:
"""
Receive a data frame on the connection.
"""
flow_controlled_length = frame.flow_controlled_length
events = self.state_machine.process_input(
ConnectionInputs.RECV_DATA,
)
self._inbound_flow_control_window_manager.window_consumed(
flow_controlled_length,
)
try:
stream = self._get_stream_by_id(frame.stream_id)
frames, stream_events = stream.receive_data(
frame.data,
"END_STREAM" in frame.flags,
flow_controlled_length,
)
except StreamClosedError as e:
# This stream is either marked as CLOSED or already gone from our
# internal state.
return self._handle_data_on_closed_stream(events, e, frame)
return frames, events + stream_events |
Receive a data frame on the connection.
| _receive_data_frame | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _receive_settings_frame(self, frame: SettingsFrame) -> tuple[list[Frame], list[Event]]:
"""
Receive a SETTINGS frame on the connection.
"""
events = self.state_machine.process_input(
ConnectionInputs.RECV_SETTINGS,
)
# This is an ack of the local settings.
if "ACK" in frame.flags:
changed_settings = self._local_settings_acked()
ack_event = SettingsAcknowledged()
ack_event.changed_settings = changed_settings
events.append(ack_event)
return [], events
# Add the new settings.
self.remote_settings.update(frame.settings)
events.append(
RemoteSettingsChanged.from_settings(
self.remote_settings, frame.settings,
),
)
frames = self._acknowledge_settings()
return frames, events |
Receive a SETTINGS frame on the connection.
| _receive_settings_frame | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _receive_ping_frame(self, frame: PingFrame) -> tuple[list[Frame], list[Event]]:
"""
Receive a PING frame on the connection.
"""
events = self.state_machine.process_input(
ConnectionInputs.RECV_PING,
)
frames: list[Frame] = []
evt: PingReceived | PingAckReceived
if "ACK" in frame.flags:
evt = PingAckReceived(ping_data=frame.opaque_data)
else:
evt = PingReceived(ping_data=frame.opaque_data)
# automatically ACK the PING with the same 'opaque data'
f = PingFrame(0)
f.flags.add("ACK")
f.opaque_data = frame.opaque_data
frames.append(f)
events.append(evt)
return frames, events |
Receive a PING frame on the connection.
| _receive_ping_frame | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _receive_priority_frame(self, frame: HeadersFrame | PriorityFrame) -> tuple[list[Frame], list[Event]]:
"""
Receive a PRIORITY frame on the connection.
"""
events = self.state_machine.process_input(
ConnectionInputs.RECV_PRIORITY,
)
event = PriorityUpdated()
event.stream_id = frame.stream_id
event.depends_on = frame.depends_on
event.exclusive = frame.exclusive
# Weight is an integer between 1 and 256, but the byte only allows
# 0 to 255: add one.
event.weight = frame.stream_weight + 1
# A stream may not depend on itself.
if event.depends_on == frame.stream_id:
msg = f"Stream {frame.stream_id} may not depend on itself"
raise ProtocolError(msg)
events.append(event)
return [], events |
Receive a PRIORITY frame on the connection.
| _receive_priority_frame | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _receive_goaway_frame(self, frame: GoAwayFrame) -> tuple[list[Frame], list[Event]]:
"""
Receive a GOAWAY frame on the connection.
"""
events = self.state_machine.process_input(
ConnectionInputs.RECV_GOAWAY,
)
# Clear the outbound data buffer: we cannot send further data now.
self.clear_outbound_data_buffer()
# Fire an appropriate ConnectionTerminated event.
new_event = ConnectionTerminated()
new_event.error_code = _error_code_from_int(frame.error_code)
new_event.last_stream_id = frame.last_stream_id
new_event.additional_data = (frame.additional_data
if frame.additional_data else None)
events.append(new_event)
return [], events |
Receive a GOAWAY frame on the connection.
| _receive_goaway_frame | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _receive_naked_continuation(self, frame: ContinuationFrame) -> None:
"""
A naked CONTINUATION frame has been received. This is always an error,
but the type of error it is depends on the state of the stream and must
transition the state of the stream, so we need to pass it to the
appropriate stream.
"""
stream = self._get_stream_by_id(frame.stream_id)
stream.receive_continuation()
msg = "Should not be reachable" # pragma: no cover
raise AssertionError(msg) # pragma: no cover |
A naked CONTINUATION frame has been received. This is always an error,
but the type of error it is depends on the state of the stream and must
transition the state of the stream, so we need to pass it to the
appropriate stream.
| _receive_naked_continuation | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _receive_alt_svc_frame(self, frame: AltSvcFrame) -> tuple[list[Frame], list[Event]]:
"""
An ALTSVC frame has been received. This frame, specified in RFC 7838,
is used to advertise alternative places where the same service can be
reached.
This frame can optionally be received either on a stream or on stream
0, and its semantics are different in each case.
"""
events = self.state_machine.process_input(
ConnectionInputs.RECV_ALTERNATIVE_SERVICE,
)
frames = []
if frame.stream_id:
# Given that it makes no sense to receive ALTSVC on a stream
# before that stream has been opened with a HEADERS frame, the
# ALTSVC frame cannot create a stream. If the stream is not
# present, we simply ignore the frame.
try:
stream = self._get_stream_by_id(frame.stream_id)
except (NoSuchStreamError, StreamClosedError):
pass
else:
stream_frames, stream_events = stream.receive_alt_svc(frame)
frames.extend(stream_frames)
events.extend(stream_events)
else:
# This frame is sent on stream 0. The origin field on the frame
# must be present, though if it isn't it's not a ProtocolError
# (annoyingly), we just need to ignore it.
if not frame.origin:
return frames, events
# If we're a server, we want to ignore this (RFC 7838 says so).
if not self.config.client_side:
return frames, events
event = AlternativeServiceAvailable()
event.origin = frame.origin
event.field_value = frame.field
events.append(event)
return frames, events |
An ALTSVC frame has been received. This frame, specified in RFC 7838,
is used to advertise alternative places where the same service can be
reached.
This frame can optionally be received either on a stream or on stream
0, and its semantics are different in each case.
| _receive_alt_svc_frame | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _local_settings_acked(self) -> dict[SettingCodes | int, ChangedSetting]:
"""
Handle the local settings being ACKed, update internal state.
"""
changes = self.local_settings.acknowledge()
if SettingCodes.INITIAL_WINDOW_SIZE in changes:
setting = changes[SettingCodes.INITIAL_WINDOW_SIZE]
self._inbound_flow_control_change_from_settings(
setting.original_value,
setting.new_value,
)
if SettingCodes.MAX_HEADER_LIST_SIZE in changes:
setting = changes[SettingCodes.MAX_HEADER_LIST_SIZE]
self.decoder.max_header_list_size = setting.new_value
if SettingCodes.MAX_FRAME_SIZE in changes:
setting = changes[SettingCodes.MAX_FRAME_SIZE]
self.max_inbound_frame_size = setting.new_value
if SettingCodes.HEADER_TABLE_SIZE in changes:
setting = changes[SettingCodes.HEADER_TABLE_SIZE]
# This is safe across all hpack versions: some versions just won't
# respect it.
self.decoder.max_allowed_table_size = setting.new_value
return changes |
Handle the local settings being ACKed, update internal state.
| _local_settings_acked | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _stream_closed_by(self, stream_id: int) -> StreamClosedBy | None:
"""
Returns how the stream was closed.
The return value will be either a member of
``h2.stream.StreamClosedBy`` or ``None``. If ``None``, the stream was
closed implicitly by the peer opening a stream with a higher stream ID
before opening this one.
"""
if stream_id in self.streams:
return self.streams[stream_id].closed_by
if stream_id in self._closed_streams:
return self._closed_streams[stream_id]
return None |
Returns how the stream was closed.
The return value will be either a member of
``h2.stream.StreamClosedBy`` or ``None``. If ``None``, the stream was
closed implicitly by the peer opening a stream with a higher stream ID
before opening this one.
| _stream_closed_by | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _stream_is_closed_by_reset(self, stream_id: int) -> bool:
"""
Returns ``True`` if the stream was closed by sending or receiving a
RST_STREAM frame. Returns ``False`` otherwise.
"""
return self._stream_closed_by(stream_id) in (
StreamClosedBy.RECV_RST_STREAM, StreamClosedBy.SEND_RST_STREAM,
) |
Returns ``True`` if the stream was closed by sending or receiving a
RST_STREAM frame. Returns ``False`` otherwise.
| _stream_is_closed_by_reset | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _stream_is_closed_by_end(self, stream_id: int) -> bool:
"""
Returns ``True`` if the stream was closed by sending or receiving an
END_STREAM flag in a HEADERS or DATA frame. Returns ``False``
otherwise.
"""
return self._stream_closed_by(stream_id) in (
StreamClosedBy.RECV_END_STREAM, StreamClosedBy.SEND_END_STREAM,
) |
Returns ``True`` if the stream was closed by sending or receiving an
END_STREAM flag in a HEADERS or DATA frame. Returns ``False``
otherwise.
| _stream_is_closed_by_end | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _add_frame_priority(frame: PriorityFrame | HeadersFrame,
weight: int | None = None,
depends_on: int | None = None,
exclusive: bool | None = None) -> PriorityFrame | HeadersFrame:
"""
Adds priority data to a given frame. Does not change any flags set on that
frame: if the caller is adding priority information to a HEADERS frame they
must set that themselves.
This method also deliberately sets defaults for anything missing.
This method validates the input values.
"""
# A stream may not depend on itself.
if depends_on == frame.stream_id:
msg = f"Stream {frame.stream_id} may not depend on itself"
raise ProtocolError(msg)
# Weight must be between 1 and 256.
if weight is not None:
if weight > 256 or weight < 1:
msg = f"Weight must be between 1 and 256, not {weight}"
raise ProtocolError(msg)
# Weight is an integer between 1 and 256, but the byte only allows
# 0 to 255: subtract one.
weight -= 1
# Set defaults for anything not provided.
weight = weight if weight is not None else 15
depends_on = depends_on if depends_on is not None else 0
exclusive = exclusive if exclusive is not None else False
frame.stream_weight = weight
frame.depends_on = depends_on
frame.exclusive = exclusive
return frame |
Adds priority data to a given frame. Does not change any flags set on that
frame: if the caller is adding priority information to a HEADERS frame they
must set that themselves.
This method also deliberately sets defaults for anything missing.
This method validates the input values.
| _add_frame_priority | python | python-hyper/h2 | src/h2/connection.py | https://github.com/python-hyper/h2/blob/master/src/h2/connection.py | MIT |
def _error_code_from_int(code: int) -> ErrorCodes | int:
"""
Given an integer error code, returns either one of :class:`ErrorCodes
<h2.errors.ErrorCodes>` or, if not present in the known set of codes,
returns the integer directly.
"""
try:
return ErrorCodes(code)
except ValueError:
return code |
Given an integer error code, returns either one of :class:`ErrorCodes
<h2.errors.ErrorCodes>` or, if not present in the known set of codes,
returns the integer directly.
| _error_code_from_int | python | python-hyper/h2 | src/h2/errors.py | https://github.com/python-hyper/h2/blob/master/src/h2/errors.py | MIT |
def from_settings(cls,
old_settings: Settings | dict[int, int],
new_settings: dict[int, int]) -> RemoteSettingsChanged:
"""
Build a RemoteSettingsChanged event from a set of changed settings.
:param old_settings: A complete collection of old settings, in the form
of a dictionary of ``{setting: value}``.
:param new_settings: All the changed settings and their new values, in
the form of a dictionary of ``{setting: value}``.
"""
e = cls()
for setting, new_value in new_settings.items():
s = _setting_code_from_int(setting)
original_value = old_settings.get(s)
change = ChangedSetting(s, original_value, new_value)
e.changed_settings[s] = change
return e |
Build a RemoteSettingsChanged event from a set of changed settings.
:param old_settings: A complete collection of old settings, in the form
of a dictionary of ``{setting: value}``.
:param new_settings: All the changed settings and their new values, in
the form of a dictionary of ``{setting: value}``.
| from_settings | python | python-hyper/h2 | src/h2/events.py | https://github.com/python-hyper/h2/blob/master/src/h2/events.py | MIT |
def _bytes_representation(data: bytes | None) -> str | None:
"""
Converts a bytestring into something that is safe to print on all Python
platforms.
This function is relatively expensive, so it should not be called on the
mainline of the code. It's safe to use in things like object repr methods
though.
"""
if data is None:
return None
return binascii.hexlify(data).decode("ascii") |
Converts a bytestring into something that is safe to print on all Python
platforms.
This function is relatively expensive, so it should not be called on the
mainline of the code. It's safe to use in things like object repr methods
though.
| _bytes_representation | python | python-hyper/h2 | src/h2/events.py | https://github.com/python-hyper/h2/blob/master/src/h2/events.py | MIT |
def add_data(self, data: bytes) -> None:
"""
Add more data to the frame buffer.
:param data: A bytestring containing the byte buffer.
"""
if self._preamble_len:
data_len = len(data)
of_which_preamble = min(self._preamble_len, data_len)
if self._preamble[:of_which_preamble] != data[:of_which_preamble]:
msg = "Invalid HTTP/2 preamble."
raise ProtocolError(msg)
data = data[of_which_preamble:]
self._preamble_len -= of_which_preamble
self._preamble = self._preamble[of_which_preamble:]
self._data += data |
Add more data to the frame buffer.
:param data: A bytestring containing the byte buffer.
| add_data | python | python-hyper/h2 | src/h2/frame_buffer.py | https://github.com/python-hyper/h2/blob/master/src/h2/frame_buffer.py | MIT |
def _validate_frame_length(self, length: int) -> None:
"""
Confirm that the frame is an appropriate length.
"""
if length > self.max_frame_size:
msg = f"Received overlong frame: length {length}, max {self.max_frame_size}"
raise FrameTooLargeError(msg) |
Confirm that the frame is an appropriate length.
| _validate_frame_length | python | python-hyper/h2 | src/h2/frame_buffer.py | https://github.com/python-hyper/h2/blob/master/src/h2/frame_buffer.py | MIT |
def _update_header_buffer(self, f: Frame | None) -> Frame | None:
"""
Updates the internal header buffer. Returns a frame that should replace
the current one. May throw exceptions if this frame is invalid.
"""
# Check if we're in the middle of a headers block. If we are, this
# frame *must* be a CONTINUATION frame with the same stream ID as the
# leading HEADERS or PUSH_PROMISE frame. Anything else is a
# ProtocolError. If the frame *is* valid, append it to the header
# buffer.
if self._headers_buffer:
stream_id = self._headers_buffer[0].stream_id
valid_frame = (
f is not None and
isinstance(f, ContinuationFrame) and
f.stream_id == stream_id
)
if not valid_frame:
msg = "Invalid frame during header block."
raise ProtocolError(msg)
assert isinstance(f, ContinuationFrame)
# Append the frame to the buffer.
self._headers_buffer.append(f)
if len(self._headers_buffer) > CONTINUATION_BACKLOG:
msg = "Too many continuation frames received."
raise ProtocolError(msg)
# If this is the end of the header block, then we want to build a
# mutant HEADERS frame that's massive. Use the original one we got,
# then set END_HEADERS and set its data appopriately. If it's not
# the end of the block, lose the current frame: we can't yield it.
if "END_HEADERS" in f.flags:
f = self._headers_buffer[0]
f.flags.add("END_HEADERS")
f.data = b"".join(x.data for x in self._headers_buffer)
self._headers_buffer = []
else:
f = None
elif (isinstance(f, (HeadersFrame, PushPromiseFrame)) and
"END_HEADERS" not in f.flags):
# This is the start of a headers block! Save the frame off and then
# act like we didn't receive one.
self._headers_buffer.append(f)
f = None
return f |
Updates the internal header buffer. Returns a frame that should replace
the current one. May throw exceptions if this frame is invalid.
| _update_header_buffer | python | python-hyper/h2 | src/h2/frame_buffer.py | https://github.com/python-hyper/h2/blob/master/src/h2/frame_buffer.py | MIT |
def _setting_code_from_int(code: int) -> SettingCodes | int:
"""
Given an integer setting code, returns either one of :class:`SettingCodes
<h2.settings.SettingCodes>` or, if not present in the known set of codes,
returns the integer directly.
"""
try:
return SettingCodes(code)
except ValueError:
return code |
Given an integer setting code, returns either one of :class:`SettingCodes
<h2.settings.SettingCodes>` or, if not present in the known set of codes,
returns the integer directly.
| _setting_code_from_int | python | python-hyper/h2 | src/h2/settings.py | https://github.com/python-hyper/h2/blob/master/src/h2/settings.py | MIT |
def acknowledge(self) -> dict[SettingCodes | int, ChangedSetting]:
"""
The settings have been acknowledged, either by the user (remote
settings) or by the remote peer (local settings).
:returns: A dict of {setting: ChangedSetting} that were applied.
"""
changed_settings: dict[SettingCodes | int, ChangedSetting] = {}
# If there is more than one setting in the list, we have a setting
# value outstanding. Update them.
for k, v in self._settings.items():
if len(v) > 1:
old_setting = v.popleft()
new_setting = v[0]
changed_settings[k] = ChangedSetting(
k, old_setting, new_setting,
)
return changed_settings |
The settings have been acknowledged, either by the user (remote
settings) or by the remote peer (local settings).
:returns: A dict of {setting: ChangedSetting} that were applied.
| acknowledge | python | python-hyper/h2 | src/h2/settings.py | https://github.com/python-hyper/h2/blob/master/src/h2/settings.py | MIT |
def _validate_setting(setting: SettingCodes | int, value: int) -> ErrorCodes:
"""
Confirms that a specific setting has a well-formed value. If the setting is
invalid, returns an error code. Otherwise, returns 0 (NO_ERROR).
"""
if setting == SettingCodes.ENABLE_PUSH:
if value not in (0, 1):
return ErrorCodes.PROTOCOL_ERROR
elif setting == SettingCodes.INITIAL_WINDOW_SIZE:
if not 0 <= value <= 2147483647: # 2^31 - 1
return ErrorCodes.FLOW_CONTROL_ERROR
elif setting == SettingCodes.MAX_FRAME_SIZE:
if not 16384 <= value <= 16777215: # 2^14 and 2^24 - 1
return ErrorCodes.PROTOCOL_ERROR
elif setting == SettingCodes.MAX_HEADER_LIST_SIZE:
if value < 0:
return ErrorCodes.PROTOCOL_ERROR
elif setting == SettingCodes.ENABLE_CONNECT_PROTOCOL and value not in (0, 1):
return ErrorCodes.PROTOCOL_ERROR
return ErrorCodes.NO_ERROR |
Confirms that a specific setting has a well-formed value. If the setting is
invalid, returns an error code. Otherwise, returns 0 (NO_ERROR).
| _validate_setting | python | python-hyper/h2 | src/h2/settings.py | https://github.com/python-hyper/h2/blob/master/src/h2/settings.py | MIT |
def process_input(self, input_: StreamInputs) -> list[Event]:
"""
Process a specific input in the state machine.
"""
if not isinstance(input_, StreamInputs):
msg = "Input must be an instance of StreamInputs"
raise ValueError(msg) # noqa: TRY004
try:
func, target_state = _transitions[(self.state, input_)]
except KeyError as err:
old_state = self.state
self.state = StreamState.CLOSED
msg = f"Invalid input {input_} in state {old_state}"
raise ProtocolError(msg) from err
else:
previous_state = self.state
self.state = target_state
if func is not None:
try:
return func(self, previous_state)
except ProtocolError:
self.state = StreamState.CLOSED
raise
except AssertionError as err: # pragma: no cover
self.state = StreamState.CLOSED
raise ProtocolError(err) from err
return [] |
Process a specific input in the state machine.
| process_input | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def response_sent(self, previous_state: StreamState) -> list[Event]:
"""
Fires when something that should be a response is sent. This 'response'
may actually be trailers.
"""
if not self.headers_sent:
if self.client is True or self.client is None:
msg = "Client cannot send responses."
raise ProtocolError(msg)
self.headers_sent = True
return [_ResponseSent()]
assert not self.trailers_sent
self.trailers_sent = True
return [_TrailersSent()] |
Fires when something that should be a response is sent. This 'response'
may actually be trailers.
| response_sent | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def response_received(self, previous_state: StreamState) -> list[Event]:
"""
Fires when a response is received. Also disambiguates between responses
and trailers.
"""
event: ResponseReceived | TrailersReceived
if not self.headers_received:
assert self.client is True
self.headers_received = True
event = ResponseReceived(stream_id=self.stream_id)
else:
assert not self.trailers_received
self.trailers_received = True
event = TrailersReceived(stream_id=self.stream_id)
event.stream_id = self.stream_id
return [event] |
Fires when a response is received. Also disambiguates between responses
and trailers.
| response_received | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def stream_ended(self, previous_state: StreamState) -> list[Event]:
"""
Fires when a stream is cleanly ended.
"""
self.stream_closed_by = StreamClosedBy.RECV_END_STREAM
event = StreamEnded(stream_id=self.stream_id)
return [event] |
Fires when a stream is cleanly ended.
| stream_ended | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def send_new_pushed_stream(self, previous_state: StreamState) -> list[Event]:
"""
Fires on the newly pushed stream, when pushed by the local peer.
No event here, but definitionally this peer must be a server.
"""
assert self.client is None
self.client = False
self.headers_received = True
return [] |
Fires on the newly pushed stream, when pushed by the local peer.
No event here, but definitionally this peer must be a server.
| send_new_pushed_stream | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def recv_new_pushed_stream(self, previous_state: StreamState) -> list[Event]:
"""
Fires on the newly pushed stream, when pushed by the remote peer.
No event here, but definitionally this peer must be a client.
"""
assert self.client is None
self.client = True
self.headers_sent = True
return [] |
Fires on the newly pushed stream, when pushed by the remote peer.
No event here, but definitionally this peer must be a client.
| recv_new_pushed_stream | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def send_push_promise(self, previous_state: StreamState) -> list[Event]:
"""
Fires on the already-existing stream when a PUSH_PROMISE frame is sent.
We may only send PUSH_PROMISE frames if we're a server.
"""
if self.client is True:
msg = "Cannot push streams from client peers."
raise ProtocolError(msg)
event = _PushedRequestSent()
return [event] |
Fires on the already-existing stream when a PUSH_PROMISE frame is sent.
We may only send PUSH_PROMISE frames if we're a server.
| send_push_promise | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def recv_push_promise(self, previous_state: StreamState) -> list[Event]:
"""
Fires on the already-existing stream when a PUSH_PROMISE frame is
received. We may only receive PUSH_PROMISE frames if we're a client.
Fires a PushedStreamReceived event.
"""
if not self.client:
if self.client is None: # pragma: no cover
msg = "Idle streams cannot receive pushes"
else: # pragma: no cover
msg = "Cannot receive pushed streams as a server"
raise ProtocolError(msg)
event = PushedStreamReceived()
event.parent_stream_id = self.stream_id
return [event] |
Fires on the already-existing stream when a PUSH_PROMISE frame is
received. We may only receive PUSH_PROMISE frames if we're a client.
Fires a PushedStreamReceived event.
| recv_push_promise | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def recv_push_on_closed_stream(self, previous_state: StreamState) -> list[Event]:
"""
Called when a PUSH_PROMISE frame is received on a full stop
stream.
If the stream was closed by us sending a RST_STREAM frame, then we
presume that the PUSH_PROMISE was in flight when we reset the parent
stream. Rathen than accept the new stream, we just reset it.
Otherwise, we should call this a PROTOCOL_ERROR: pushing a stream on a
naturally closed stream is a real problem because it creates a brand
new stream that the remote peer now believes exists.
"""
assert self.stream_closed_by is not None
if self.stream_closed_by == StreamClosedBy.SEND_RST_STREAM:
raise StreamClosedError(self.stream_id)
msg = "Attempted to push on closed stream."
raise ProtocolError(msg) |
Called when a PUSH_PROMISE frame is received on a full stop
stream.
If the stream was closed by us sending a RST_STREAM frame, then we
presume that the PUSH_PROMISE was in flight when we reset the parent
stream. Rathen than accept the new stream, we just reset it.
Otherwise, we should call this a PROTOCOL_ERROR: pushing a stream on a
naturally closed stream is a real problem because it creates a brand
new stream that the remote peer now believes exists.
| recv_push_on_closed_stream | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def send_informational_response(self, previous_state: StreamState) -> list[Event]:
"""
Called when an informational header block is sent (that is, a block
where the :status header has a 1XX value).
Only enforces that these are sent *before* final headers are sent.
"""
if self.headers_sent:
msg = "Information response after final response"
raise ProtocolError(msg)
event = _ResponseSent()
return [event] |
Called when an informational header block is sent (that is, a block
where the :status header has a 1XX value).
Only enforces that these are sent *before* final headers are sent.
| send_informational_response | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def recv_informational_response(self, previous_state: StreamState) -> list[Event]:
"""
Called when an informational header block is received (that is, a block
where the :status header has a 1XX value).
"""
if self.headers_received:
msg = "Informational response after final response"
raise ProtocolError(msg)
return [InformationalResponseReceived(stream_id=self.stream_id)] |
Called when an informational header block is received (that is, a block
where the :status header has a 1XX value).
| recv_informational_response | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def send_alt_svc(self, previous_state: StreamState) -> list[Event]:
"""
Called when sending an ALTSVC frame on this stream.
For consistency with the restrictions we apply on receiving ALTSVC
frames in ``recv_alt_svc``, we want to restrict when users can send
ALTSVC frames to the situations when we ourselves would accept them.
That means: when we are a server, when we have received the request
headers, and when we have not yet sent our own response headers.
"""
# We should not send ALTSVC after we've sent response headers, as the
# client may have disposed of its state.
if self.headers_sent:
msg = "Cannot send ALTSVC after sending response headers."
raise ProtocolError(msg)
return [] |
Called when sending an ALTSVC frame on this stream.
For consistency with the restrictions we apply on receiving ALTSVC
frames in ``recv_alt_svc``, we want to restrict when users can send
ALTSVC frames to the situations when we ourselves would accept them.
That means: when we are a server, when we have received the request
headers, and when we have not yet sent our own response headers.
| send_alt_svc | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def open(self) -> bool:
"""
Whether the stream is 'open' in any sense: that is, whether it counts
against the number of concurrent streams.
"""
# RFC 7540 Section 5.1.2 defines 'open' for this purpose to mean either
# the OPEN state or either of the HALF_CLOSED states. Perplexingly,
# this excludes the reserved states.
# For more detail on why we're doing this in this slightly weird way,
# see the comment on ``STREAM_OPEN`` at the top of the file.
return STREAM_OPEN[self.state_machine.state] |
Whether the stream is 'open' in any sense: that is, whether it counts
against the number of concurrent streams.
| open | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def upgrade(self, client_side: bool) -> None:
"""
Called by the connection to indicate that this stream is the initial
request/response of an upgraded connection. Places the stream into an
appropriate state.
"""
self.config.logger.debug("Upgrading %r", self)
assert self.stream_id == 1
input_ = (
StreamInputs.UPGRADE_CLIENT if client_side
else StreamInputs.UPGRADE_SERVER
)
# This may return events, we deliberately don't want them.
self.state_machine.process_input(input_) |
Called by the connection to indicate that this stream is the initial
request/response of an upgraded connection. Places the stream into an
appropriate state.
| upgrade | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def locally_pushed(self) -> list[Frame]:
"""
Mark this stream as one that was pushed by this peer. Must be called
immediately after initialization. Sends no frames, simply updates the
state machine.
"""
# This does not trigger any events.
events = self.state_machine.process_input(
StreamInputs.SEND_PUSH_PROMISE,
)
assert not events
return [] |
Mark this stream as one that was pushed by this peer. Must be called
immediately after initialization. Sends no frames, simply updates the
state machine.
| locally_pushed | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def send_data(self,
data: bytes | memoryview,
end_stream: bool = False,
pad_length: int | None = None) -> list[Frame]:
"""
Prepare some data frames. Optionally end the stream.
.. warning:: Does not perform flow control checks.
"""
self.config.logger.debug(
"Send data on %r with end stream set to %s", self, end_stream,
)
self.state_machine.process_input(StreamInputs.SEND_DATA)
df = DataFrame(self.stream_id)
df.data = data
if end_stream:
self.state_machine.process_input(StreamInputs.SEND_END_STREAM)
df.flags.add("END_STREAM")
if pad_length is not None:
df.flags.add("PADDED")
df.pad_length = pad_length
# Subtract flow_controlled_length to account for possible padding
self.outbound_flow_control_window -= df.flow_controlled_length
assert self.outbound_flow_control_window >= 0
return [df] |
Prepare some data frames. Optionally end the stream.
.. warning:: Does not perform flow control checks.
| send_data | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def advertise_alternative_service(self, field_value: bytes) -> list[Frame]:
"""
Advertise an RFC 7838 alternative service. The semantics of this are
better documented in the ``H2Connection`` class.
"""
self.config.logger.debug(
"Advertise alternative service of %r for %r", field_value, self,
)
self.state_machine.process_input(StreamInputs.SEND_ALTERNATIVE_SERVICE)
asf = AltSvcFrame(self.stream_id)
asf.field = field_value
return [asf] |
Advertise an RFC 7838 alternative service. The semantics of this are
better documented in the ``H2Connection`` class.
| advertise_alternative_service | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def increase_flow_control_window(self, increment: int) -> list[Frame]:
"""
Increase the size of the flow control window for the remote side.
"""
self.config.logger.debug(
"Increase flow control window for %r by %d",
self, increment,
)
self.state_machine.process_input(StreamInputs.SEND_WINDOW_UPDATE)
self._inbound_window_manager.window_opened(increment)
wuf = WindowUpdateFrame(self.stream_id)
wuf.window_increment = increment
return [wuf] |
Increase the size of the flow control window for the remote side.
| increase_flow_control_window | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def receive_push_promise_in_band(self,
promised_stream_id: int,
headers: Iterable[Header],
header_encoding: bool | str | None) -> tuple[list[Frame], list[Event]]:
"""
Receives a push promise frame sent on this stream, pushing a remote
stream. This is called on the stream that has the PUSH_PROMISE sent
on it.
"""
self.config.logger.debug(
"Receive Push Promise on %r for remote stream %d",
self, promised_stream_id,
)
events = self.state_machine.process_input(
StreamInputs.RECV_PUSH_PROMISE,
)
push_event = cast("PushedStreamReceived", events[0])
push_event.pushed_stream_id = promised_stream_id
hdr_validation_flags = self._build_hdr_validation_flags(events)
push_event.headers = self._process_received_headers(
headers, hdr_validation_flags, header_encoding,
)
return [], events |
Receives a push promise frame sent on this stream, pushing a remote
stream. This is called on the stream that has the PUSH_PROMISE sent
on it.
| receive_push_promise_in_band | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.