Debian Codegraph @

test/test_eventstream_rpc.py

raw symbols SCIP
1 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 # SPDX-License-Identifier: Apache-2.0.
3
4 from awscrt import NativeResource
5 from awscrt.eventstream import *
6 from awscrt.eventstream.rpc import *
7 from awscrt.io import (ClientBootstrap, DefaultHostResolver, EventLoopGroup, init_logging, LogLevel)
8 from awscrt._test import native_memory_usage
9 import gc
10 import os
11 from queue import Queue
12 from test import NativeResourceTest, TIMEOUT
13 from threading import Event
14 import time
15 from unittest import skipUnless
16 from uuid import UUID, uuid4
17 import weakref
18
19 # TODO: setup permanent online echo server we can hit from tests
20 RUN_LOCALHOST_TESTS = os.getenv('EVENTSTREAM_ECHO_TEST')
21
22 # init_logging(LogLevel.Trace, 'stderr')
23
24
25 class ConnectionRecord:
26 def __init__(self):
27 self.setup_call = None
28 self.shutdown_call = None
29 self.message_calls = Queue()
30
31
32 class ConnectionHandler(ClientConnectionHandler):
33 def __init__(self, fail_test_fn):
34 self.record = ConnectionRecord()
35 self.fail_test = fail_test_fn
36 self.connection = None
37 # whether to purposefully raise an exception in a callback
38 self.raise_during_setup = False
39
40 def on_connection_setup(self, connection, error, **kwargs):
41 if self.record.setup_call is not None:
42 self.fail_test("setup can only fire once")
43 self.record.setup_call = {'connection': connection, 'error': error}
44 self.connection = connection
45 if self.raise_during_setup:
46 raise RuntimeError("Purposefully raising error in callback")
47
48 def on_connection_shutdown(self, reason, **kwargs):
49 if self.record.setup_call is None:
50 self.fail_test("if setup doesn't fire, shutdown shouldn't fire")
51 if self.record.setup_call['error'] is not None:
52 self.fail_test("shutdown shouldn't fire if setup had an error")
53 if self.record.shutdown_call is not None:
54 self.fail_test("shutdown can only fire once")
55 self.record.shutdown_call = {'reason': reason}
56
57 def on_protocol_message(self, headers, payload, message_type, flags, **kwargs):
58 if self.record.setup_call is None:
59 self.fail_test("setup must fire before messages")
60 if self.record.shutdown_call is not None:
61 self.fail_test("messages cannot fire after shutdown")
62 self.record.message_calls.put(
63 {'headers': headers, 'payload': payload, 'message_type': message_type, 'flags': flags})
64
65
66 class ContinuationRecord:
67 def __init__(self):
68 self.message_calls = Queue()
69 self.close_call = Event()
70
71
72 class ContinuationHandler(ClientContinuationHandler):
73 def __init__(self, fail_test_fn):
74 self.record = ContinuationRecord()
75 self.fail_test = fail_test_fn
76
77 def on_continuation_message(
78 self,
79 headers,
80 payload,
81 message_type,
82 flags,
83 **kwargs):
84 if self.record.close_call.is_set():
85 self.fail_test("messages should not fire after close")
86 self.record.message_calls.put(
87 {'headers': headers, 'payload': payload, 'message_type': message_type, 'flags': flags})
88
89 def on_continuation_closed(self, **kwargs):
90 if self.record.close_call.is_set():
91 self.fail_test("shutdown can only fire once")
92 self.record.close_call.set()
93
94
95 class FailureClientTests(NativeResourceTest):
96 def _fail_test_from_callback(self, msg):
97 print("ERROR FROM CALLBACK", msg)
98 self._failure_from_callback = msg
99
100 def _assertNoFailuresFromCallbacks(self):
101 self.assertIsNone(getattr(self, '_failure_from_callback', None))
102
103 def test_connect_failure(self):
104 elg = EventLoopGroup()
105 resolver = DefaultHostResolver(elg)
106 bootstrap = ClientBootstrap(elg, resolver)
107 handler = ConnectionHandler(self._fail_test_from_callback)
108 future = ClientConnection.connect(
109 handler=handler,
110 host_name="fake",
111 port=99,
112 bootstrap=bootstrap)
113
114 failure = future.exception(TIMEOUT)
115 self.assertTrue(isinstance(failure, Exception))
116 self.assertIsNotNone(handler.record.setup_call)
117 self.assertIsNone(handler.record.setup_call['connection'])
118 self.assertTrue(isinstance(handler.record.setup_call['error'], Exception))
119 self.assertIsNone(handler.record.shutdown_call)
120 self._assertNoFailuresFromCallbacks()
121
122
123 @skipUnless(RUN_LOCALHOST_TESTS, "Skipping until we have permanent echo server")
124 class TestClient(NativeResourceTest):
125 def _fail_test_from_callback(self, msg):
126 print("ERROR FROM CALLBACK", msg)
127 self._failure_from_callback = msg
128
129 def _assertNoFailuresFromCallbacks(self):
130 self.assertIsNone(getattr(self, '_failure_from_callback', None))
131
132 def test_connect_success(self):
133 elg = EventLoopGroup()
134 resolver = DefaultHostResolver(elg)
135 bootstrap = ClientBootstrap(elg, resolver)
136 handler = ConnectionHandler(self._fail_test_from_callback)
137 future = ClientConnection.connect(
138 handler=handler,
139 host_name="127.0.0.1",
140 port=8033,
141 bootstrap=bootstrap)
142
143 self.assertIsNone(future.exception(TIMEOUT))
144 self.assertIsNotNone(handler.record.setup_call)
145 self.assertTrue(isinstance(handler.record.setup_call['connection'], ClientConnection))
146 self.assertIsNone(handler.record.setup_call['error'])
147 self.assertTrue(handler.connection.is_open())
148 self.assertIsNone(handler.record.shutdown_call)
149
150 # close
151 shutdown_future = handler.connection.close()
152 self.assertIsNone(shutdown_future.exception(TIMEOUT))
153 self.assertIsNotNone(handler.record.shutdown_call)
154 self.assertIsNone(handler.record.shutdown_call['reason'])
155
156 self._assertNoFailuresFromCallbacks()
157
158 def _connect_and_return_weakref(self):
159 elg = EventLoopGroup()
160 resolver = DefaultHostResolver(elg)
161 bootstrap = ClientBootstrap(elg, resolver)
162 handler = ConnectionHandler(self._fail_test_from_callback)
163 future = ClientConnection.connect(
164 handler=handler,
165 host_name="127.0.0.1",
166 port=8033,
167 bootstrap=bootstrap)
168
169 # connection should succeed
170 self.assertIsNone(future.exception(TIMEOUT))
171
172 return weakref.ref(handler.connection)
173
174 def test_connection_stays_alive_until_close(self):
175 # Currently, eventstream connections do NOT close just because their refcount reaches zero.
176 # We *could* make it work this way, but it would take some combo of:
177 # 1) handler shutdown callbacks aren't guaranteed to fire,
178 # because handler likely has reference to connection, and we want
179 # them to get GC'd together.
180 # 2) OR guarantee shutdown callbacks, but explain the subtleties of
181 # avoiding a strong reference cycle involving the handler.
182 # This is not a typical thing Python programmers need to think about.
183 # Seems best to keep it simple and just remind the user at every
184 # opportunity that connection must be closed to avoid resource leaks.
185 connection_weakref = self._connect_and_return_weakref()
186
187 # wait a moment to see if connection gets cleaned up
188 time.sleep(1)
189 gc.collect()
190
191 connection = connection_weakref()
192 self.assertIsNotNone(connection, "open connection should not have been GC'd")
193 self.assertTrue(connection.is_open())
194
195 # ok, now shut it down, (and nuke local reference to connection
196 # just to be sure we don't crash if both happen simultaneously)
197 shutdown_future = connection.close()
198 del connection
199 self.assertIsNone(shutdown_future.exception(TIMEOUT))
200
201 # GC should have cleaned it up, now that the connection is closed
202 # and no strong references remain
203 gc.collect()
204 self.assertIsNone(connection_weakref())
205
206 self._assertNoFailuresFromCallbacks()
207
208 def test_setup_callback_exception_closes_connection(self):
209 elg = EventLoopGroup()
210 resolver = DefaultHostResolver(elg)
211 bootstrap = ClientBootstrap(elg, resolver)
212 handler = ConnectionHandler(self._fail_test_from_callback)
213
214 # tell handler to explode during setup callback
215 handler.raise_during_setup = True
216 connect_future = ClientConnection.connect(
217 handler=handler,
218 host_name="127.0.0.1",
219 port=8033,
220 bootstrap=bootstrap)
221
222 # the connect future does actually succeed, since the user's setup
223 # callback got a chance to run.
224 connect_future.exception(TIMEOUT)
225
226 # but the unhandled exception should cause the connection to die
227 shutdown_reason = handler.connection.shutdown_future.exception(TIMEOUT)
228 self.assertTrue("CALLBACK_EXCEPTION" in shutdown_reason.name)
229 self.assertTrue("CALLBACK_EXCEPTION" in handler.record.shutdown_call['reason'].name)
230
231 def _connect_fully(self):
232 # connect, send CONNECT message, receive CONNECT_ACK
233 elg = EventLoopGroup()
234 resolver = DefaultHostResolver(elg)
235 bootstrap = ClientBootstrap(elg, resolver)
236 handler = ConnectionHandler(self._fail_test_from_callback)
237 connect_future = ClientConnection.connect(
238 handler=handler,
239 host_name="127.0.0.1",
240 port=8033,
241 bootstrap=bootstrap)
242
243 self.assertIsNone(connect_future.exception(TIMEOUT))
244
245 # send CONNECT msg
246 msg_future = handler.connection.send_protocol_message(
247 message_type=MessageType.CONNECT,
248 headers=[Header.from_string(':version', '0.1.0'),
249 Header.from_string('client-name', 'accepted.testy_mc_testerson')])
250
251 self.assertIsNone(msg_future.exception(TIMEOUT))
252
253 # wait to receive CONNECT_ACK
254 msg = handler.record.message_calls.get(timeout=TIMEOUT)
255 self.assertIs(MessageType.CONNECT_ACK, msg['message_type'])
256 self.assertTrue(MessageFlag.CONNECTION_ACCEPTED & msg['flags'])
257
258 return handler
259
260 def test_connection_close_without_waiting_for_completion(self):
261 # Regression test: check that it's safe to call close and drop local references,
262 # without waiting for close() to complete.
263 handler = self._connect_fully()
264 handler.connection.close()
265
266 def test_stream_cleans_up_if_never_activated(self):
267 # check that there are no resource leaks if a stream/continuation is never activated
268 handler = self._connect_fully()
269
270 # create stream, but do not activate it
271 stream_handler = ContinuationHandler(self._fail_test_from_callback)
272 continuation = handler.connection.new_stream(stream_handler)
273
274 # close connection
275 handler.connection.close()
276 self.assertIsNone(handler.connection.shutdown_future.exception(TIMEOUT))
277
278 # stream callbacks should not fire because it was never activated
279 self.assertFalse(stream_handler.record.close_call.isSet())
280
281 self._assertNoFailuresFromCallbacks()
282
283 def test_stream_message_echo(self):
284 # test sending and receiving messages
285 handler = self._connect_fully()
286
287 # send PING msg, server will echo back its headers and payload in the PING_RESPONSE.
288 # test every single header type
289 echo_headers = [
290 Header.from_bool('echo-true', True),
291 Header.from_bool('echo-false', False),
292 Header.from_byte('echo-byte', 127),
293 Header.from_int16('echo-int16', 32000),
294 Header.from_int32('echo-int32', 2000000000),
295 Header.from_int64('echo-int64', 999999999999),
296 Header.from_byte_buf('echo-byte-buf', b'\x00\xff\x0f\xf0'),
297 Header.from_string('echo-string', 'noodles'),
298 # utf-8 breaks echo test. don't get response.
299 # Header.from_string('echo-string-utf8', '--\u1234--'),
300 Header.from_timestamp('echo-timestamp', time.time()),
301 Header.from_uuid('echo-uuid', UUID('01234567-89ab-cdef-0123-456789abcdef')),
302 ]
303 echo_payload = b'\x00\xDE\xAD\xBE\xEF'
304 msg_future = handler.connection.send_protocol_message(
305 message_type=MessageType.PING,
306 headers=echo_headers,
307 payload=echo_payload)
308
309 self.assertIsNone(msg_future.exception(TIMEOUT))
310
311 # wait to receive PING_RESPONSE, which should echo what we sent
312 msg = handler.record.message_calls.get(timeout=TIMEOUT)
313 self.assertIs(MessageType.PING_RESPONSE, msg['message_type'])
314 for sent_header in echo_headers:
315 recv_header = next(x for x in msg['headers'] if x.name.lower() == sent_header.name.lower())
316 self.assertEqual(sent_header.type, recv_header.type)
317 self.assertEqual(sent_header.value, recv_header.value)
318 self.assertEqual(echo_payload, msg['payload'])
319
320 # use a stream to execute the "EchoMessage" operation,
321 # which takes 1 message and responds with 1 message
322 stream_handler = ContinuationHandler(self._fail_test_from_callback)
323 continuation = handler.connection.new_stream(stream_handler)
324 msg_flushed = Event()
325
326 def on_msg_flush(error, **kwargs):
327 msg_flushed.set()
328
329 msg_future = continuation.activate(
330 operation='awstest#EchoMessage',
331 headers=[],
332 payload=b'{}',
333 message_type=MessageType.APPLICATION_MESSAGE,
334 flags=MessageFlag.NONE,
335 on_flush=on_msg_flush)
336
337 self.assertIsNone(msg_future.exception(TIMEOUT))
338 self.assertTrue(msg_flushed.wait(TIMEOUT))
339
340 # wait to receive response, which should end the stream
341 msg = stream_handler.record.message_calls.get(timeout=TIMEOUT)
342 self.assertEqual(MessageType.APPLICATION_MESSAGE, msg['message_type'])
343 self.assertTrue(MessageFlag.TERMINATE_STREAM & msg['flags'])
344 self.assertIsNone(continuation.closed_future.exception(TIMEOUT))
345
346 # use a stream to execute the "EchoStreamMessages" operation,
347 # which has an empty initial request/response, but then allows further messages
348 stream_handler = ContinuationHandler(self._fail_test_from_callback)
349 continuation = handler.connection.new_stream(stream_handler)
350 msg_future = continuation.activate(
351 operation='awstest#EchoStreamMessages',
352 headers=[],
353 payload=b'{}',
354 message_type=MessageType.APPLICATION_MESSAGE,
355 flags=MessageFlag.NONE)
356
357 self.assertIsNone(msg_future.exception(TIMEOUT))
358
359 # wait to initial response, which should end the stream
360 msg = stream_handler.record.message_calls.get(timeout=TIMEOUT)
361 self.assertEqual(MessageType.APPLICATION_MESSAGE, msg['message_type'])
362 self.assertFalse(MessageFlag.TERMINATE_STREAM & msg['flags'])
363
364 # send a 2nd message on the stream
365 msg_future = continuation.send_message(
366 headers=[],
367 payload=b'{}',
368 message_type=MessageType.APPLICATION_MESSAGE,
369 flags=MessageFlag.NONE)
370
371 self.assertIsNone(msg_future.exception(TIMEOUT))
372
373 # wait for 2nd response
374 msg = stream_handler.record.message_calls.get(timeout=TIMEOUT)
375 self.assertEqual(MessageType.APPLICATION_MESSAGE, msg['message_type'])
376 self.assertFalse(MessageFlag.TERMINATE_STREAM & msg['flags'])
377
378 # close connection
379 handler.connection.close()
380 self.assertIsNone(handler.connection.shutdown_future.exception(TIMEOUT))
381 self.assertIsNone(continuation.closed_future.exception(TIMEOUT))
382
383 self._assertNoFailuresFromCallbacks()
384
385 def _start_request_and_drop_local_references(self, connection):
386 # use a stream to execute the "EchoMessage" operation,
387 # which takes 1 message and responds with 1 message
388 stream_handler = ContinuationHandler(self._fail_test_from_callback)
389 continuation = connection.new_stream(stream_handler)
390 msg_future = continuation.activate(
391 operation='awstest#EchoMessage',
392 headers=[],
393 payload=b'{}',
394 message_type=MessageType.APPLICATION_MESSAGE,
395 flags=MessageFlag.NONE)
396
397 return (continuation.closed_future, stream_handler.record)
398
399 def test_stream_stays_alive_until_close(self):
400 # Test checks that stream stays alive, and all callbacks fire,
401 # even if there are no local references to stream or its handler.
402 handler = self._connect_fully()
403
404 # create new stream and handler, and send request, but don't get back
405 # anything that keeps a reference to these things.
406 # function returns items that should show side-effects of the
407 # request/response continuation to operate to completion.
408 # If this test fails, it's because something got GC'd too early and all
409 # the callbacks couldn't fire
410 stream_closed_future, stream_record = self._start_request_and_drop_local_references(handler.connection)
411
412 # wait to receive response, which should end the stream
413 msg = stream_record.message_calls.get(timeout=TIMEOUT)
414
415 # close connection
416 handler.connection.close()
417 self.assertIsNone(handler.connection.shutdown_future.exception(TIMEOUT))
418 self.assertTrue(stream_record.close_call.wait(timeout=TIMEOUT))
419 self.assertIsNone(stream_closed_future.result(timeout=TIMEOUT))
420
421 self._assertNoFailuresFromCallbacks()
422
423 def test_stream_cleans_up_on_close(self):
424 # ensure that a stream cleans up immediately after it's closed and references to it are dropped
425 handler = self._connect_fully()
426
427 # use function to create and run stream.
428 # if we just did it in loop below, local references would stick around
429 # and show up when we checked for leaks
430 def _run_stream_operation():
431 stream_handler = ContinuationHandler(self._fail_test_from_callback)
432 continuation = handler.connection.new_stream(stream_handler)
433 continuation.activate(
434 operation='awstest#EchoMessage',
435 headers=[],
436 payload=b'{}',
437 message_type=MessageType.APPLICATION_MESSAGE,
438 flags=MessageFlag.NONE)
439 self.assertTrue(stream_handler.record.close_call.wait(TIMEOUT))
440
441 living_resources_at_start = len(NativeResource._living)
442 native_mem_usage_at_start = native_memory_usage()
443
444 # run a few streams
445 for i in range(10):
446 _run_stream_operation()
447 gc.collect()
448 self.assertEqual(living_resources_at_start, len(NativeResource._living))
449 self.assertEqual(native_mem_usage_at_start, native_memory_usage())
450
451 handler.connection.close().result(TIMEOUT)
452 self._assertNoFailuresFromCallbacks()
453
454 def test_stream_reference_can_outlive_connection(self):
455 # Regression test. Ensure we don't crash if a stream reference stays alive
456 # after connection has been closed and references to connection have been dropped
457 connection_handler = self._connect_fully()
458
459 # run stream and keep its reference around
460 stream_handler = ContinuationHandler(self._fail_test_from_callback)
461 continuation = connection_handler.connection.new_stream(stream_handler)
462 continuation.activate(
463 operation='awstest#EchoMessage',
464 headers=[],
465 payload=b'{}',
466 message_type=MessageType.APPLICATION_MESSAGE,
467 flags=MessageFlag.NONE)
468 self.assertTrue(stream_handler.record.close_call.wait(TIMEOUT))
469
470 # close connection and nuke local references
471 connection_handler.connection.close().result(TIMEOUT)
472 connection_weakref = weakref.ref(connection_handler.connection)
473 del connection_handler
474 gc.collect()
475
476 del stream_handler
477 del continuation
478 gc.collect()
479
480 def test_on_closed_deadlock_regression(self):
481 # ensure that during the on_closed() callback of the first stream,
482 # we can activate a second stream without deadlocking
483 handler = self._connect_fully()
484
485 # create 2 streams but don't activate yet
486 first_stream_handler = DeadlockStreamHandler(handler.connection)
487 first_stream = handler.connection.new_stream(first_stream_handler)
488
489 second_stream_handler = ContinuationHandler(self._fail_test_from_callback)
490 second_stream = handler.connection.new_stream(second_stream_handler)
491
492 # activate first stream with message that closes the stream
493 # from the on_closed() callback it will activate the second stream
494 first_stream_handler.second_stream = second_stream
495 first_stream.activate(operation="first",
496 message_type=MessageType.APPLICATION_MESSAGE)
497
498 self.assertTrue(first_stream_handler.activated_second_stream.wait(TIMEOUT))
499
500 handler.connection.close().result(TIMEOUT)
501
502
503 class DeadlockStreamHandler(ClientContinuationHandler):
504 def __init__(self, connection):
505 super().__init__()
506 self.connection = connection
507 self.activated_second_stream = Event()
508
509 def on_continuation_message(self, headers, payload, message_type, flags, **kwargs) -> None:
510 pass
511
512 def on_continuation_closed(self, **kwargs) -> None:
513 print("ACTIVATING")
514 self.second_stream.activate(operation="next",
515 message_type=MessageType.APPLICATION_MESSAGE)
516 print("EVENTING")
517 self.activated_second_stream.set()