File: test_eventstream_rpc.py

package info (click to toggle)
aws-crt-python 0.20.4%2Bdfsg-1~bpo12%2B1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-backports
  • size: 72,656 kB
  • sloc: ansic: 381,805; python: 23,008; makefile: 6,251; sh: 4,536; cpp: 699; ruby: 208; java: 77; perl: 73; javascript: 46; xml: 11
file content (517 lines) | stat: -rw-r--r-- 21,871 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0.

from awscrt import NativeResource
from awscrt.eventstream import *
from awscrt.eventstream.rpc import *
from awscrt.io import (ClientBootstrap, DefaultHostResolver, EventLoopGroup, init_logging, LogLevel)
from awscrt._test import native_memory_usage
import gc
import os
from queue import Queue
from test import NativeResourceTest, TIMEOUT
from threading import Event
import time
from unittest import skipUnless
from uuid import UUID, uuid4
import weakref

# TODO: setup permanent online echo server we can hit from tests
RUN_LOCALHOST_TESTS = os.getenv('EVENTSTREAM_ECHO_TEST')

# init_logging(LogLevel.Trace, 'stderr')


class ConnectionRecord:
    def __init__(self):
        self.setup_call = None
        self.shutdown_call = None
        self.message_calls = Queue()


class ConnectionHandler(ClientConnectionHandler):
    def __init__(self, fail_test_fn):
        self.record = ConnectionRecord()
        self.fail_test = fail_test_fn
        self.connection = None
        # whether to purposefully raise an exception in a callback
        self.raise_during_setup = False

    def on_connection_setup(self, connection, error, **kwargs):
        if self.record.setup_call is not None:
            self.fail_test("setup can only fire once")
        self.record.setup_call = {'connection': connection, 'error': error}
        self.connection = connection
        if self.raise_during_setup:
            raise RuntimeError("Purposefully raising error in callback")

    def on_connection_shutdown(self, reason, **kwargs):
        if self.record.setup_call is None:
            self.fail_test("if setup doesn't fire, shutdown shouldn't fire")
        if self.record.setup_call['error'] is not None:
            self.fail_test("shutdown shouldn't fire if setup had an error")
        if self.record.shutdown_call is not None:
            self.fail_test("shutdown can only fire once")
        self.record.shutdown_call = {'reason': reason}

    def on_protocol_message(self, headers, payload, message_type, flags, **kwargs):
        if self.record.setup_call is None:
            self.fail_test("setup must fire before messages")
        if self.record.shutdown_call is not None:
            self.fail_test("messages cannot fire after shutdown")
        self.record.message_calls.put(
            {'headers': headers, 'payload': payload, 'message_type': message_type, 'flags': flags})


class ContinuationRecord:
    def __init__(self):
        self.message_calls = Queue()
        self.close_call = Event()


class ContinuationHandler(ClientContinuationHandler):
    def __init__(self, fail_test_fn):
        self.record = ContinuationRecord()
        self.fail_test = fail_test_fn

    def on_continuation_message(
            self,
            headers,
            payload,
            message_type,
            flags,
            **kwargs):
        if self.record.close_call.is_set():
            self.fail_test("messages should not fire after close")
        self.record.message_calls.put(
            {'headers': headers, 'payload': payload, 'message_type': message_type, 'flags': flags})

    def on_continuation_closed(self, **kwargs):
        if self.record.close_call.is_set():
            self.fail_test("shutdown can only fire once")
        self.record.close_call.set()


class FailureClientTests(NativeResourceTest):
    def _fail_test_from_callback(self, msg):
        print("ERROR FROM CALLBACK", msg)
        self._failure_from_callback = msg

    def _assertNoFailuresFromCallbacks(self):
        self.assertIsNone(getattr(self, '_failure_from_callback', None))

    def test_connect_failure(self):
        elg = EventLoopGroup()
        resolver = DefaultHostResolver(elg)
        bootstrap = ClientBootstrap(elg, resolver)
        handler = ConnectionHandler(self._fail_test_from_callback)
        future = ClientConnection.connect(
            handler=handler,
            host_name="fake",
            port=99,
            bootstrap=bootstrap)

        failure = future.exception(TIMEOUT)
        self.assertTrue(isinstance(failure, Exception))
        self.assertIsNotNone(handler.record.setup_call)
        self.assertIsNone(handler.record.setup_call['connection'])
        self.assertTrue(isinstance(handler.record.setup_call['error'], Exception))
        self.assertIsNone(handler.record.shutdown_call)
        self._assertNoFailuresFromCallbacks()


@skipUnless(RUN_LOCALHOST_TESTS, "Skipping until we have permanent echo server")
class TestClient(NativeResourceTest):
    def _fail_test_from_callback(self, msg):
        print("ERROR FROM CALLBACK", msg)
        self._failure_from_callback = msg

    def _assertNoFailuresFromCallbacks(self):
        self.assertIsNone(getattr(self, '_failure_from_callback', None))

    def test_connect_success(self):
        elg = EventLoopGroup()
        resolver = DefaultHostResolver(elg)
        bootstrap = ClientBootstrap(elg, resolver)
        handler = ConnectionHandler(self._fail_test_from_callback)
        future = ClientConnection.connect(
            handler=handler,
            host_name="127.0.0.1",
            port=8033,
            bootstrap=bootstrap)

        self.assertIsNone(future.exception(TIMEOUT))
        self.assertIsNotNone(handler.record.setup_call)
        self.assertTrue(isinstance(handler.record.setup_call['connection'], ClientConnection))
        self.assertIsNone(handler.record.setup_call['error'])
        self.assertTrue(handler.connection.is_open())
        self.assertIsNone(handler.record.shutdown_call)

        # close
        shutdown_future = handler.connection.close()
        self.assertIsNone(shutdown_future.exception(TIMEOUT))
        self.assertIsNotNone(handler.record.shutdown_call)
        self.assertIsNone(handler.record.shutdown_call['reason'])

        self._assertNoFailuresFromCallbacks()

    def _connect_and_return_weakref(self):
        elg = EventLoopGroup()
        resolver = DefaultHostResolver(elg)
        bootstrap = ClientBootstrap(elg, resolver)
        handler = ConnectionHandler(self._fail_test_from_callback)
        future = ClientConnection.connect(
            handler=handler,
            host_name="127.0.0.1",
            port=8033,
            bootstrap=bootstrap)

        # connection should succeed
        self.assertIsNone(future.exception(TIMEOUT))

        return weakref.ref(handler.connection)

    def test_connection_stays_alive_until_close(self):
        # Currently, eventstream connections do NOT close just because their refcount reaches zero.
        # We *could* make it work this way, but it would take some combo of:
        # 1) handler shutdown callbacks aren't guaranteed to fire,
        #    because handler likely has reference to connection, and we want
        #    them to get GC'd together.
        # 2) OR guarantee shutdown callbacks, but explain the subtleties of
        #    avoiding a strong reference cycle involving the handler.
        #    This is not a typical thing Python programmers need to think about.
        # Seems best to keep it simple and just remind the user at every
        # opportunity that connection must be closed to avoid resource leaks.
        connection_weakref = self._connect_and_return_weakref()

        # wait a moment to see if connection gets cleaned up
        time.sleep(1)
        gc.collect()

        connection = connection_weakref()
        self.assertIsNotNone(connection, "open connection should not have been GC'd")
        self.assertTrue(connection.is_open())

        # ok, now shut it down, (and nuke local reference to connection
        # just to be sure we don't crash if both happen simultaneously)
        shutdown_future = connection.close()
        del connection
        self.assertIsNone(shutdown_future.exception(TIMEOUT))

        # GC should have cleaned it up, now that the connection is closed
        # and no strong references remain
        gc.collect()
        self.assertIsNone(connection_weakref())

        self._assertNoFailuresFromCallbacks()

    def test_setup_callback_exception_closes_connection(self):
        elg = EventLoopGroup()
        resolver = DefaultHostResolver(elg)
        bootstrap = ClientBootstrap(elg, resolver)
        handler = ConnectionHandler(self._fail_test_from_callback)

        # tell handler to explode during setup callback
        handler.raise_during_setup = True
        connect_future = ClientConnection.connect(
            handler=handler,
            host_name="127.0.0.1",
            port=8033,
            bootstrap=bootstrap)

        # the connect future does actually succeed, since the user's setup
        # callback got a chance to run.
        connect_future.exception(TIMEOUT)

        # but the unhandled exception should cause the connection to die
        shutdown_reason = handler.connection.shutdown_future.exception(TIMEOUT)
        self.assertTrue("CALLBACK_EXCEPTION" in shutdown_reason.name)
        self.assertTrue("CALLBACK_EXCEPTION" in handler.record.shutdown_call['reason'].name)

    def _connect_fully(self):
        # connect, send CONNECT message, receive CONNECT_ACK
        elg = EventLoopGroup()
        resolver = DefaultHostResolver(elg)
        bootstrap = ClientBootstrap(elg, resolver)
        handler = ConnectionHandler(self._fail_test_from_callback)
        connect_future = ClientConnection.connect(
            handler=handler,
            host_name="127.0.0.1",
            port=8033,
            bootstrap=bootstrap)

        self.assertIsNone(connect_future.exception(TIMEOUT))

        # send CONNECT msg
        msg_future = handler.connection.send_protocol_message(
            message_type=MessageType.CONNECT,
            headers=[Header.from_string(':version', '0.1.0'),
                     Header.from_string('client-name', 'accepted.testy_mc_testerson')])

        self.assertIsNone(msg_future.exception(TIMEOUT))

        # wait to receive CONNECT_ACK
        msg = handler.record.message_calls.get(timeout=TIMEOUT)
        self.assertIs(MessageType.CONNECT_ACK, msg['message_type'])
        self.assertTrue(MessageFlag.CONNECTION_ACCEPTED & msg['flags'])

        return handler

    def test_connection_close_without_waiting_for_completion(self):
        # Regression test: check that it's safe to call close and drop local references,
        # without waiting for close() to complete.
        handler = self._connect_fully()
        handler.connection.close()

    def test_stream_cleans_up_if_never_activated(self):
        # check that there are no resource leaks if a stream/continuation is never activated
        handler = self._connect_fully()

        # create stream, but do not activate it
        stream_handler = ContinuationHandler(self._fail_test_from_callback)
        continuation = handler.connection.new_stream(stream_handler)

        # close connection
        handler.connection.close()
        self.assertIsNone(handler.connection.shutdown_future.exception(TIMEOUT))

        # stream callbacks should not fire because it was never activated
        self.assertFalse(stream_handler.record.close_call.isSet())

        self._assertNoFailuresFromCallbacks()

    def test_stream_message_echo(self):
        # test sending and receiving messages
        handler = self._connect_fully()

        # send PING msg, server will echo back its headers and payload in the PING_RESPONSE.
        # test every single header type
        echo_headers = [
            Header.from_bool('echo-true', True),
            Header.from_bool('echo-false', False),
            Header.from_byte('echo-byte', 127),
            Header.from_int16('echo-int16', 32000),
            Header.from_int32('echo-int32', 2000000000),
            Header.from_int64('echo-int64', 999999999999),
            Header.from_byte_buf('echo-byte-buf', b'\x00\xff\x0f\xf0'),
            Header.from_string('echo-string', 'noodles'),
            # utf-8 breaks echo test. don't get response.
            # Header.from_string('echo-string-utf8', '--\u1234--'),
            Header.from_timestamp('echo-timestamp', time.time()),
            Header.from_uuid('echo-uuid', UUID('01234567-89ab-cdef-0123-456789abcdef')),
        ]
        echo_payload = b'\x00\xDE\xAD\xBE\xEF'
        msg_future = handler.connection.send_protocol_message(
            message_type=MessageType.PING,
            headers=echo_headers,
            payload=echo_payload)

        self.assertIsNone(msg_future.exception(TIMEOUT))

        # wait to receive PING_RESPONSE, which should echo what we sent
        msg = handler.record.message_calls.get(timeout=TIMEOUT)
        self.assertIs(MessageType.PING_RESPONSE, msg['message_type'])
        for sent_header in echo_headers:
            recv_header = next(x for x in msg['headers'] if x.name.lower() == sent_header.name.lower())
            self.assertEqual(sent_header.type, recv_header.type)
            self.assertEqual(sent_header.value, recv_header.value)
        self.assertEqual(echo_payload, msg['payload'])

        # use a stream to execute the "EchoMessage" operation,
        # which takes 1 message and responds with 1 message
        stream_handler = ContinuationHandler(self._fail_test_from_callback)
        continuation = handler.connection.new_stream(stream_handler)
        msg_flushed = Event()

        def on_msg_flush(error, **kwargs):
            msg_flushed.set()

        msg_future = continuation.activate(
            operation='awstest#EchoMessage',
            headers=[],
            payload=b'{}',
            message_type=MessageType.APPLICATION_MESSAGE,
            flags=MessageFlag.NONE,
            on_flush=on_msg_flush)

        self.assertIsNone(msg_future.exception(TIMEOUT))
        self.assertTrue(msg_flushed.wait(TIMEOUT))

        # wait to receive response, which should end the stream
        msg = stream_handler.record.message_calls.get(timeout=TIMEOUT)
        self.assertEqual(MessageType.APPLICATION_MESSAGE, msg['message_type'])
        self.assertTrue(MessageFlag.TERMINATE_STREAM & msg['flags'])
        self.assertIsNone(continuation.closed_future.exception(TIMEOUT))

        # use a stream to execute the "EchoStreamMessages" operation,
        # which has an empty initial request/response, but then allows further messages
        stream_handler = ContinuationHandler(self._fail_test_from_callback)
        continuation = handler.connection.new_stream(stream_handler)
        msg_future = continuation.activate(
            operation='awstest#EchoStreamMessages',
            headers=[],
            payload=b'{}',
            message_type=MessageType.APPLICATION_MESSAGE,
            flags=MessageFlag.NONE)

        self.assertIsNone(msg_future.exception(TIMEOUT))

        # wait to initial response, which should end the stream
        msg = stream_handler.record.message_calls.get(timeout=TIMEOUT)
        self.assertEqual(MessageType.APPLICATION_MESSAGE, msg['message_type'])
        self.assertFalse(MessageFlag.TERMINATE_STREAM & msg['flags'])

        # send a 2nd message on the stream
        msg_future = continuation.send_message(
            headers=[],
            payload=b'{}',
            message_type=MessageType.APPLICATION_MESSAGE,
            flags=MessageFlag.NONE)

        self.assertIsNone(msg_future.exception(TIMEOUT))

        # wait for 2nd response
        msg = stream_handler.record.message_calls.get(timeout=TIMEOUT)
        self.assertEqual(MessageType.APPLICATION_MESSAGE, msg['message_type'])
        self.assertFalse(MessageFlag.TERMINATE_STREAM & msg['flags'])

        # close connection
        handler.connection.close()
        self.assertIsNone(handler.connection.shutdown_future.exception(TIMEOUT))
        self.assertIsNone(continuation.closed_future.exception(TIMEOUT))

        self._assertNoFailuresFromCallbacks()

    def _start_request_and_drop_local_references(self, connection):
        # use a stream to execute the "EchoMessage" operation,
        # which takes 1 message and responds with 1 message
        stream_handler = ContinuationHandler(self._fail_test_from_callback)
        continuation = connection.new_stream(stream_handler)
        msg_future = continuation.activate(
            operation='awstest#EchoMessage',
            headers=[],
            payload=b'{}',
            message_type=MessageType.APPLICATION_MESSAGE,
            flags=MessageFlag.NONE)

        return (continuation.closed_future, stream_handler.record)

    def test_stream_stays_alive_until_close(self):
        # Test checks that stream stays alive, and all callbacks fire,
        # even if there are no local references to stream or its handler.
        handler = self._connect_fully()

        # create new stream and handler, and send request, but don't get back
        # anything that keeps a reference to these things.
        # function returns items that should show side-effects of the
        # request/response continuation to operate to completion.
        # If this test fails, it's because something got GC'd too early and all
        # the callbacks couldn't fire
        stream_closed_future, stream_record = self._start_request_and_drop_local_references(handler.connection)

        # wait to receive response, which should end the stream
        msg = stream_record.message_calls.get(timeout=TIMEOUT)

        # close connection
        handler.connection.close()
        self.assertIsNone(handler.connection.shutdown_future.exception(TIMEOUT))
        self.assertTrue(stream_record.close_call.wait(timeout=TIMEOUT))
        self.assertIsNone(stream_closed_future.result(timeout=TIMEOUT))

        self._assertNoFailuresFromCallbacks()

    def test_stream_cleans_up_on_close(self):
        # ensure that a stream cleans up immediately after it's closed and references to it are dropped
        handler = self._connect_fully()

        # use function to create and run stream.
        # if we just did it in loop below, local references would stick around
        # and show up when we checked for leaks
        def _run_stream_operation():
            stream_handler = ContinuationHandler(self._fail_test_from_callback)
            continuation = handler.connection.new_stream(stream_handler)
            continuation.activate(
                operation='awstest#EchoMessage',
                headers=[],
                payload=b'{}',
                message_type=MessageType.APPLICATION_MESSAGE,
                flags=MessageFlag.NONE)
            self.assertTrue(stream_handler.record.close_call.wait(TIMEOUT))

        living_resources_at_start = len(NativeResource._living)
        native_mem_usage_at_start = native_memory_usage()

        # run a few streams
        for i in range(10):
            _run_stream_operation()
            gc.collect()
            self.assertEqual(living_resources_at_start, len(NativeResource._living))
            self.assertEqual(native_mem_usage_at_start, native_memory_usage())

        handler.connection.close().result(TIMEOUT)
        self._assertNoFailuresFromCallbacks()

    def test_stream_reference_can_outlive_connection(self):
        # Regression test. Ensure we don't crash if a stream reference stays alive
        # after connection has been closed and references to connection have been dropped
        connection_handler = self._connect_fully()

        # run stream and keep its reference around
        stream_handler = ContinuationHandler(self._fail_test_from_callback)
        continuation = connection_handler.connection.new_stream(stream_handler)
        continuation.activate(
            operation='awstest#EchoMessage',
            headers=[],
            payload=b'{}',
            message_type=MessageType.APPLICATION_MESSAGE,
            flags=MessageFlag.NONE)
        self.assertTrue(stream_handler.record.close_call.wait(TIMEOUT))

        # close connection and nuke local references
        connection_handler.connection.close().result(TIMEOUT)
        connection_weakref = weakref.ref(connection_handler.connection)
        del connection_handler
        gc.collect()

        del stream_handler
        del continuation
        gc.collect()

    def test_on_closed_deadlock_regression(self):
        # ensure that during the on_closed() callback of the first stream,
        # we can activate a second stream without deadlocking
        handler = self._connect_fully()

        # create 2 streams but don't activate yet
        first_stream_handler = DeadlockStreamHandler(handler.connection)
        first_stream = handler.connection.new_stream(first_stream_handler)

        second_stream_handler = ContinuationHandler(self._fail_test_from_callback)
        second_stream = handler.connection.new_stream(second_stream_handler)

        # activate first stream with message that closes the stream
        # from the on_closed() callback it will activate the second stream
        first_stream_handler.second_stream = second_stream
        first_stream.activate(operation="first",
                              message_type=MessageType.APPLICATION_MESSAGE)

        self.assertTrue(first_stream_handler.activated_second_stream.wait(TIMEOUT))

        handler.connection.close().result(TIMEOUT)


class DeadlockStreamHandler(ClientContinuationHandler):
    def __init__(self, connection):
        super().__init__()
        self.connection = connection
        self.activated_second_stream = Event()

    def on_continuation_message(self, headers, payload, message_type, flags, **kwargs) -> None:
        pass

    def on_continuation_closed(self, **kwargs) -> None:
        print("ACTIVATING")
        self.second_stream.activate(operation="next",
                                    message_type=MessageType.APPLICATION_MESSAGE)
        print("EVENTING")
        self.activated_second_stream.set()