async def request_slow_stream(client: RSocketClient): payload = Payload( b'The quick brown fox', composite(route('slow_stream'), authenticate_simple('user', '12345'))) completion_event = Event() client.request_stream(payload).subscribe( StreamSubscriber(completion_event)) await completion_event.wait()
async def request_stream_invalid_login(client: RSocketClient): payload = Payload( b'The quick brown fox', composite(route('stream'), authenticate_simple('user', 'wrong_password'))) completion_event = Event() client.request_stream(payload).initial_request_n(1).subscribe( StreamSubscriber(completion_event)) await completion_event.wait()
async def start_quic_client(port: int, generate_test_certificates) -> RSocketClient: certificate, private_key = generate_test_certificates client_configuration = QuicConfiguration( is_client=True ) ca_data = certificate.public_bytes(serialization.Encoding.PEM) client_configuration.load_verify_locations(cadata=ca_data, cafile=None) async def transport_provider(): try: logging.info('Quic connection lost valid connection 1') async with rsocket_connect('localhost', port, configuration=client_configuration) as transport: yield transport logging.info('Quic connection lost invalid connection') yield FailingTransport() logging.info('Quic connection lost valid connection 2') async with rsocket_connect('localhost', port, configuration=client_configuration) as transport: yield transport except Exception: logger().error('Client connection error', exc_info=True) raise return RSocketClient(transport_provider(), handler_factory=ClientHandler)
async def main(server_port): logging.info('Connecting to server at localhost:%s', server_port) client_configuration = QuicConfiguration( is_client=True ) ca_file_path = Path(__file__).parent / 'certificates' / 'pycacert.pem' client_configuration.load_verify_locations(cafile=str(ca_file_path)) async with rsocket_connect('localhost', server_port, configuration=client_configuration) as transport: async with RSocketClient(single_transport_provider(transport)) as client: payload = Payload(b'%Y-%m-%d %H:%M:%S') async def run_request_response(): try: while True: result = await client.request_response(payload) logging.info('Response: {}'.format(result.data)) await asyncio.sleep(1) except asyncio.CancelledError: pass task = asyncio.create_task(run_request_response()) await asyncio.sleep(5) task.cancel() await task
async def main(): connection = await asyncio.open_connection('localhost', 7000) setup_payload = Payload(data=str(uuid4()).encode(), metadata=composite( route('shell-client'), authenticate_simple('user', 'pass'))) async with RSocketClient(single_transport_provider( TransportTCP(*connection)), setup_payload=setup_payload, metadata_encoding=WellKnownMimeTypes. MESSAGE_RSOCKET_COMPOSITE_METADATA): await asyncio.sleep(5)
async def start(): nonlocal service, client service = await asyncio.start_server(session, host, port) connection = await asyncio.open_connection(host, port) nonlocal client_arguments # test_overrides = {'keep_alive_period': timedelta(minutes=20)} client_arguments = client_arguments or {} # client_arguments.update(test_overrides) client = RSocketClient(single_transport_provider(TransportTCP(*connection)), **(client_arguments or {})) if auto_connect_client: await client.connect()
async def start_websocket_client(port: int, generate_test_certificates) -> RSocketClient: url = 'http://localhost:{}'.format(port) async def transport_provider(): try: yield TransportAioHttpClient(url) yield FailingTransport() yield TransportAioHttpClient(url) except Exception: logger().error('Client connection error', exc_info=True) raise return RSocketClient(transport_provider(), handler_factory=ClientHandler)
async def request_channel(client: RSocketClient): channel_completion_event = Event() requester_completion_event = Event() payload = Payload( b'The quick brown fox', composite(route('channel'), authenticate_simple('user', '12345'))) publisher = sample_publisher(requester_completion_event) requested = client.request_channel(payload, publisher) requested.initial_request_n(5).subscribe( ChannelSubscriber(channel_completion_event)) await channel_completion_event.wait() await requester_completion_event.wait()
async def start(): nonlocal service, client service = await asyncio.start_server(session, host, port) async def transport_provider(): while True: try: nonlocal client_connection client_connection = await asyncio.open_connection(host, port) yield TransportTCP(*client_connection) except Exception: logger().error('Client connection error', exc_info=True) raise client = RSocketClient(transport_provider(), handler_factory=ClientHandler)
async def main(server_port): logging.info('Connecting to server at localhost:%s', server_port) connection = await asyncio.open_connection('localhost', server_port) async with RSocketClient(single_transport_provider( TransportTCP(*connection)), metadata_encoding=WellKnownMimeTypes. MESSAGE_RSOCKET_COMPOSITE_METADATA) as client: await request_response(client) await request_stream(client) await request_slow_stream(client) await request_channel(client) await request_stream_invalid_login(client) await request_fragmented_stream(client)
async def start_tcp_client(port: int, generate_test_certificates) -> RSocketClient: async def transport_provider(): try: client_connection = await asyncio.open_connection('localhost', port) yield TransportTCP(*client_connection) yield FailingTransport() client_connection = await asyncio.open_connection('localhost', port) yield TransportTCP(*client_connection) except Exception: logger().error('Client connection error', exc_info=True) raise return RSocketClient(transport_provider(), handler_factory=ClientHandler)
async def pipe_factory_quic(generate_test_certificates, unused_tcp_port, client_arguments=None, server_arguments=None): certificate, private_key = generate_test_certificates server_configuration = QuicConfiguration(certificate=certificate, private_key=private_key, is_client=False) client_configuration = QuicConfiguration(is_client=True) ca_data = certificate.public_bytes(serialization.Encoding.PEM) client_configuration.load_verify_locations(cadata=ca_data, cafile=None) server: Optional[RSocketBase] = None wait_for_server = Event() def store_server(new_server): nonlocal server server = new_server wait_for_server.set() quic_server = await rsocket_serve(host='localhost', port=unused_tcp_port, configuration=server_configuration, on_server_create=store_server, **(server_arguments or {})) # from datetime import timedelta # test_overrides = {'keep_alive_period': timedelta(minutes=20)} client_arguments = client_arguments or {} # client_arguments.update(test_overrides) async with rsocket_connect( 'localhost', unused_tcp_port, configuration=client_configuration) as transport: async with RSocketClient(single_transport_provider(transport), **client_arguments) as client: await wait_for_server.wait() yield server, client await server.close() assert_no_open_streams(client, server) quic_server.close()
async def main(server_port): completion_event = Event() class Subscriber(DefaultSubscriber): def __init__(self): super().__init__() self.values = [] self.subscription: Optional[Subscription] = None def on_next(self, value, is_complete=False): self.values.append(value) self.subscription.request(1) def on_complete(self): completion_event.set() def on_error(self, exception: Exception): completion_event.set() connection = await asyncio.open_connection('localhost', server_port) async with RSocketClient(single_transport_provider( TransportTCP(*connection)), metadata_encoding=WellKnownMimeTypes. MESSAGE_RSOCKET_COMPOSITE_METADATA.value.name, data_encoding=WellKnownMimeTypes.APPLICATION_JSON. value.name) as client: metadata = CompositeMetadata() metadata.append( RoutingMetadata(['investigation.getInvestigationByContext'])) body = json.dumps({'active': True}).encode() request = Payload(body, metadata.serialize()) subscriber = Subscriber() client.request_stream(request).subscribe(subscriber) await completion_event.wait() await asyncio.sleep(4) # Used to show keepalive is working assert len(subscriber.values) == 2
async def test_connection_never_established(unused_tcp_port: int): class ClientHandler(BaseRequestHandler): async def on_connection_lost(self, rsocket, exception: Exception): logger().info('Test Reconnecting') await rsocket.reconnect() async def transport_provider(): try: for i in range(3): client_connection = await asyncio.open_connection( 'localhost', unused_tcp_port) yield TransportTCP(*client_connection) except Exception: logger().error('Client connection error', exc_info=True) raise with pytest.raises(RSocketTransportError): async with RSocketClient(transport_provider(), handler_factory=ClientHandler): await asyncio.sleep(1)
async def main(server_port): logging.info('Connecting to server at localhost:%s', server_port) connection = await asyncio.open_connection('localhost', server_port) async with RSocketClient(single_transport_provider( TransportTCP(*connection)), metadata_encoding=WellKnownMimeTypes. MESSAGE_RSOCKET_COMPOSITE_METADATA) as client: rx_client = RxRSocket(client) await request_response(rx_client) await request_stream(rx_client) await request_slow_stream(rx_client) await request_channel(rx_client) await request_stream_invalid_login(rx_client) await request_fragmented_stream(rx_client) await metadata_push(rx_client, b'audit info') await request_last_metadata(rx_client) await fire_and_forget(rx_client, b'aux data') await request_last_fnf(rx_client)
async def main(server_port): logging.info('Connecting to server at localhost:%s', server_port) connection = await asyncio.open_connection('localhost', server_port) async with RSocketClient( single_transport_provider(TransportTCP(*connection))) as client: payload = Payload(b'%Y-%m-%d %H:%M:%S') async def run_request_response(): try: while True: result = await client.request_response(payload) logging.info('Response: {}'.format(result.data)) await asyncio.sleep(1) except asyncio.CancelledError: pass task = asyncio.create_task(run_request_response()) await asyncio.sleep(5) task.cancel() await task
async def main(server_port): logging.info('Connecting to server at localhost:%s', server_port) async def transport_provider(max_reconnect): for i in range(max_reconnect): connection = await asyncio.open_connection('localhost', server_port) yield TransportTCP(*connection) async with RSocketClient(transport_provider(3), metadata_encoding=WellKnownMimeTypes. MESSAGE_RSOCKET_COMPOSITE_METADATA, handler_factory=Handler) as client: result1 = await request_response(client) assert result1.data == b'single_response' await asyncio.sleep(10) result2 = await request_response(client) assert result2.data == b'single_response' result3 = await request_response(client) assert result3.data == b'single_response'
async def websocket_client(url, **kwargs) -> RSocketClient: async with RSocketClient( single_transport_provider(TransportAioHttpClient(url)), **kwargs) as client: yield client