Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(1, self.example_request_headers, end_stream=True)
f = frame_factory.build_headers_frame(
self.example_response_headers,
flags=['END_STREAM']
)
events = c.receive_data(f.serialize())
assert len(events) == 2
response_event = events[0]
end_stream = events[1]
assert isinstance(response_event, h2.events.ResponseReceived)
assert isinstance(end_stream, h2.events.StreamEnded)
self.streams[event.stream_id].receive_data(event)
elif isinstance(event, h2.events.PushedStreamReceived):
if self._enable_push:
self._new_stream(event.pushed_stream_id, local_closed=True)
self.streams[event.parent_stream_id].receive_push(event)
else:
# Servers are forbidden from sending push promises when
# the ENABLE_PUSH setting is 0, but the spec leaves the
# client action undefined when they do it anyway. So we
# just refuse the stream and go about our business.
self._send_rst_frame(event.pushed_stream_id, 7)
elif isinstance(event, h2.events.ResponseReceived):
self.streams[event.stream_id].receive_response(event)
elif isinstance(event, h2.events.TrailersReceived):
self.streams[event.stream_id].receive_trailers(event)
elif isinstance(event, h2.events.StreamEnded):
self.streams[event.stream_id].receive_end_stream(event)
elif isinstance(event, h2.events.StreamReset):
if event.stream_id not in self.reset_streams:
self.reset_streams.add(event.stream_id)
self.streams[event.stream_id].receive_reset(event)
elif isinstance(event, h2.events.ConnectionTerminated):
# If we get GoAway with error code zero, we are doing a
# graceful shutdown and all is well. Otherwise, throw an
# exception.
self.close()
# If an error occured, try to read the error description from
# code registry otherwise use the frame's additional data.
if event.error_code != 0:
try:
name, number, description = errors.get_data(
async def test_server_sends_chunked(nursery: trio._core._run.Nursery) -> None:
connection = MockConnection(framework=chunked_response_framework)
nursery.start_soon(connection.server.handle_connection)
stream_id = await connection.send_request(
BASIC_HEADERS + [(":method", "GET"), (":path", "/")], {}
)
await connection.end_stream(stream_id)
response_data = b""
async for event in connection.get_events():
if isinstance(event, h2.events.DataReceived):
response_data += event.data
elif isinstance(event, h2.events.StreamEnded):
await connection.close()
assert response_data == b"chunked data"
c.send_data(1, b'some data', end_stream=True)
# Server received HEADERS frame but DATA frame is still on the way.
# Stream is in open state on the server-side. In this state server is
# allowed to end stream and after that acknowledge received data by
# sending WINDOW_UPDATE frames.
headers_frame = frame_factory.build_headers_frame(
[(':status', '200')],
flags=['END_STREAM'],
stream_id=1,
)
events = c.receive_data(headers_frame.serialize())
assert len(events) == 2
response_received, stream_ended = events
assert isinstance(response_received, h2.events.ResponseReceived)
assert isinstance(stream_ended, h2.events.StreamEnded)
window_update_frame = frame_factory.build_window_update_frame(
stream_id=1,
increment=1,
)
events = c.receive_data(window_update_frame.serialize())
assert not events
async def _handle_events(self, events: List[h2.events.Event]) -> None:
for event in events:
if isinstance(event, h2.events.RequestReceived):
await self._create_stream(event)
elif isinstance(event, h2.events.DataReceived):
await self.streams[event.stream_id].handle(
Body(stream_id=event.stream_id, data=event.data)
)
self.connection.acknowledge_received_data(
event.flow_controlled_length, event.stream_id
)
elif isinstance(event, h2.events.StreamEnded):
await self.streams[event.stream_id].handle(EndBody(stream_id=event.stream_id))
elif isinstance(event, h2.events.StreamReset):
await self._close_stream(event.stream_id)
await self._window_updated(event.stream_id)
elif isinstance(event, h2.events.WindowUpdated):
await self._window_updated(event.stream_id)
elif isinstance(event, h2.events.PriorityUpdated):
await self._priority_updated(event)
elif isinstance(event, h2.events.RemoteSettingsChanged):
if h2.settings.SettingCodes.INITIAL_WINDOW_SIZE in event.changed_settings:
await self._window_updated(None)
elif isinstance(event, h2.events.ConnectionTerminated):
await self.send(Closed())
await self._flush()
try:
events = self.conn.receive_data(data)
except h2.exceptions.ProtocolError:
# A remote protocol error terminates the connection.
dataToSend = self.conn.data_to_send()
self.transport.write(dataToSend)
self.transport.loseConnection()
self.connectionLost("Protocol error from peer.")
return
for event in events:
if isinstance(event, h2.events.RequestReceived):
self._requestReceived(event)
elif isinstance(event, h2.events.DataReceived):
self._requestDataReceived(event)
elif isinstance(event, h2.events.StreamEnded):
self._requestEnded(event)
elif isinstance(event, h2.events.StreamReset):
self._requestAborted(event)
elif isinstance(event, h2.events.WindowUpdated):
self._handleWindowUpdate(event)
elif isinstance(event, h2.events.PriorityUpdated):
self._handlePriorityUpdate(event)
elif isinstance(event, h2.events.ConnectionTerminated):
self.transport.loseConnection()
self.connectionLost("Shutdown by remote peer")
dataToSend = self.conn.data_to_send()
if dataToSend:
self.transport.write(dataToSend)
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)
try:
events = self.conn.receive_data(data)
except h2.exceptions.ProtocolError:
# A remote protocol error terminates the connection.
dataToSend = self.conn.data_to_send()
self.transport.write(dataToSend)
self.transport.loseConnection()
self.connectionLost("Protocol error from peer.")
return
for event in events:
if isinstance(event, h2.events.RequestReceived):
self._requestReceived(event)
elif isinstance(event, h2.events.DataReceived):
self._requestDataReceived(event)
elif isinstance(event, h2.events.StreamEnded):
self._requestEnded(event)
elif isinstance(event, h2.events.StreamReset):
self._requestAborted(event)
elif isinstance(event, h2.events.WindowUpdated):
self._handleWindowUpdate(event)
elif isinstance(event, h2.events.PriorityUpdated):
self._handlePriorityUpdate(event)
elif isinstance(event, h2.events.ConnectionTerminated):
self.transport.loseConnection()
self.connectionLost("Shutdown by remote peer")
dataToSend = self.conn.data_to_send()
if dataToSend:
self.transport.write(dataToSend)
def handle_events(self, events: List[h2.events.Event]) -> None:
for event in events:
if isinstance(event, h2.events.RequestReceived):
self.stop_keep_alive_timeout()
self.create_stream(event)
elif isinstance(event, h2.events.DataReceived):
self.streams[event.stream_id].data_received(event.data)
self.connection.acknowledge_received_data(
event.flow_controlled_length, event.stream_id
)
elif isinstance(event, h2.events.StreamReset):
self.streams[event.stream_id].reset()
elif isinstance(event, h2.events.StreamEnded):
self.streams[event.stream_id].ended()
elif isinstance(event, h2.events.WindowUpdated):
self.window_updated(event.stream_id)
elif isinstance(event, h2.events.ConnectionTerminated):
self.close()
return
self.flush()
def handle_events(self, events):
for event in events:
logger.debug("event received from {0}: {1}".format(self.conn_type, event))
if isinstance(event, ResponseReceived):
self.handle_response(event)
elif isinstance(event, RequestReceived):
self.handle_request(event)
elif isinstance(event, DataReceived):
self.handle_data(event)
elif isinstance(event, StreamEnded):
self.handle_end_stream(event.stream_id)
elif isinstance(event, StreamReset):
self.handle_reset(event)
elif isinstance(event, RemoteSettingsChanged):
self.handle_update_settings(event)
elif isinstance(event, WindowUpdated):
self.handle_window_updates(event)
elif isinstance(event, PushedStreamReceived):
self.handle_pushed_stream(event)
elif isinstance(event, PriorityUpdated):
self.handle_priority_updates(event)
elif isinstance(event, ConnectionTerminated):
self.on_terminate(
event.additional_data, event.error_code,
event.last_stream_id)
elif isinstance(event, SettingsAcknowledged):