async def _publish_heartbeat(): channel_stub = get_channel_stub_by_channel_name(channel_name) exception = None while ws.open: try: is_registered = await channel_stub.async_task( ).is_registered_subscriber(peer_id=peer_id) if is_registered: request = Request("node_ws_PublishHeartbeat") await ws.send(json.dumps(request)) heartbeat_time = StubCollection().conf[ ConfigKey.WS_HEARTBEAT_TIME] await asyncio.sleep(heartbeat_time) continue raise RuntimeError("Unregistered") except Exception as e: exception = e traceback.print_exc() break if not exception: exception = ConnectionError("Connection closed.") request = Request("node_ws_PublishHeartbeat", error=str(exception)) await ws.send(json.dumps(request)) raise exception
async def main(): response = await client.send( [Request("ping"), Request("ping"), Request("ping")]) for data in response.data: if data.ok: print("{}: {}".format(data.id, data.result)) else: logging.error("%d: %s", data.id, data.message)
async def main(): async with websockets.connect("ws://localhost:5000") as ws: requests = [Request("ping"), Request("ping"), Request("ping")] response = await WebSocketsClient(ws).send(requests) for data in response.data: if data.ok: print("{}: {}".format(data.id, data.result)) else: logging.error("%d: %s", data.id, data.message)
def test_auto_iterating_id(self): self.assertEqual({ 'jsonrpc': '2.0', 'method': 'go', 'id': 1 }, Request('go')) self.assertEqual({ 'jsonrpc': '2.0', 'method': 'go', 'id': 2 }, Request('go'))
async def main(loop): async with aiohttp.ClientSession(loop=loop) as session: client = AiohttpClient(session, "http://localhost:5000") requests = [Request("ping"), Request("ping"), Request("ping")] response = await client.send(requests) for data in response.data: if data.ok: print("{}: {}".format(data.id, data.result)) else: logging.error("%d: %s", data.id, data.message)
def test_positional(self): assert Request("sqrt", 1) == { "jsonrpc": "2.0", "method": "sqrt", "params": [1], "id": 1, }
async def publish_new_block(ws, channel_name, height, peer_id): exception = None error_code = None channel_stub = get_channel_stub_by_channel_name(channel_name) try: while ws.open: new_block_dumped, confirm_info_bytes = await \ channel_stub.async_task().announce_new_block(subscriber_block_height=height, subscriber_id=peer_id) new_block: dict = json.loads(new_block_dumped) confirm_info = confirm_info_bytes.decode('utf-8') request = Request("node_ws_PublishNewBlock", block=new_block, confirm_info=confirm_info) Logger.debug(f"node_ws_PublishNewBlock: {request}") await ws.send(json.dumps(request)) height += 1 except exceptions.ConnectionClosed as e: exception = e error_code = message_code.Response.fail_connection_closed except Exception as e: exception = e error_code = message_code.Response.fail_announce_block traceback.print_exc() if not exception: exception = ConnectionError("Connection closed.") await WSDispatcher.send_and_raise_exception(ws, "node_ws_PublishNewBlock", exception, error_code)
async def subscribe(self, block_height, event: Event): self.__exception = None try: # set websocket payload maxsize to 4MB. async with websockets.connect( self.__target_uri, max_size=4 * conf.MAX_TX_SIZE_IN_BLOCK) as websocket: event.set() logging.debug(f"Websocket connection is Completed.") request = Request("node_ws_Subscribe", height=block_height, peer_id=ChannelProperty().peer_id) await websocket.send(json.dumps(request)) await self.__subscribe_loop(websocket) except InvalidStatusCode as e: if not self.__tried_with_old_uri: await self.try_subscribe_to_past_uri(block_height, event) return logging.warning( f"websocket subscribe {type(e)} exception, caused by: {e}\n" f"This target({self.__rs_target}) may not support websocket yet." ) raise NotImplementedError except Exception as e: traceback.print_exc() logging.error( f"websocket subscribe exception, caused by: {type(e)}, {e}") raise ConnectionError
def test_specified_id(self): self.assertEqual( { 'jsonrpc': '2.0', 'method': 'get', 'id': 'Request #1' }, Request('get', request_id='Request #1'))
def main(context: click.core.Context, method: str, request_type: str, id: Any, send: str) -> None: """ Create a JSON-RPC request. """ exit_status = 0 # Extract the jsonrpc arguments positional = [a for a in context.args if "=" not in a] named = { a.split("=")[0]: a.split("=")[1] for a in context.args if "=" in a } # Create the request if request_type == "notify": req = Notification(method, *positional, **named) else: req = Request(method, *positional, request_id=id, **named) # type: ignore # Sending? if send: client = HTTPClient(send) try: response = client.send(req) except JsonRpcClientError as e: click.echo(str(e), err=True) exit_status = 1 else: click.echo(response.text) # Otherwise, simply output the JSON-RPC request. else: click.echo(str(req)) sys.exit(exit_status)
async def test_send_exception_check_parameters(self): ws = MockWebSocket() ws.send = AsyncMock() expected_method = "fake_method" expected_exc = RuntimeError("test") expected_error_code = message_code.Response.fail_subscribe_limit expected_request = Request(method=expected_method, error=str(expected_exc), code=expected_error_code) expected_called_params = dict(expected_request) await WSDispatcher.send_exception(ws, method=expected_method, exception=expected_exc, error_code=expected_error_code) actual_called_params, _ = ws.send.call_args actual_called_params: dict = json.loads(actual_called_params[0]) # Remove id because jsonrpc call auto-increments request id. expected_called_params.pop("id") actual_called_params.pop("id") assert actual_called_params == expected_called_params
async def _subscribe_request(self, block_height): request = Request( method="node_ws_Subscribe", height=block_height, peer_id=ChannelProperty().peer_id ) await self._websocket.send(json.dumps(request))
def main(context, method, request_type, id, send): """ Create a JSON-RPC request. """ exit_status = 0 # Extract the jsonrpc arguments positional = [a for a in context.args if '=' not in a] named = {a.split('=')[0]: a.split('=')[1] for a in context.args if '=' in a} # Create the request if request_type == 'notify': req = Notification(method, *positional, **named) else: req = Request(method, request_id=id, *positional, **named) # Sending? if send: client = HTTPClient(send) try: response = client.send(req) except JsonRpcClientError as e: click.echo(str(e), err=True) exit_status = 1 else: click.echo(response) # Otherwise, simply output the JSON-RPC request. else: click.echo(str(req)) sys.exit(exit_status)
async def publish_new_block(ws, channel_name, height, peer_id): call_method = WSDispatcher.PUBLISH_NEW_BLOCK channel_stub = get_channel_stub_by_channel_name(channel_name) try: while True: new_block_dumped, confirm_info_bytes = await channel_stub.async_task().announce_new_block( subscriber_block_height=height, subscriber_id=peer_id ) new_block: dict = json.loads(new_block_dumped) if "error" in new_block: Logger.error(f"announce_new_block error: {new_block}, to citizen({peer_id})") break confirm_info = confirm_info_bytes.decode('utf-8') request = Request(call_method, block=new_block, confirm_info=confirm_info) Logger.debug(f"{call_method}: {request}") await ws.send(json.dumps(request)) height += 1 except exceptions.ConnectionClosed: Logger.debug("Connection Closed by child.") # TODO: Useful message needed. except Exception as e: traceback.print_exc() # TODO: Keep this tb? await WSDispatcher.send_exception( ws, call_method, exception=e, error_code=message_code.Response.fail_announce_block )
def send_message(self): logging.info("Send message....") myrequest = Request('hello', name='world') #self.stream.write(b"Hello Server!" + self.EOF) self.send(myrequest) self.stream.read_until(self.EOF, self.on_receive) logging.info("After send....")
def test_body(self): client = HTTPClient('http://test/') request = PreparedRequest(Request('go')) client.prepare_request(request) with self.assertRaises(requests.exceptions.RequestException): client.send_message(request) self.assertEqual(request, request.prepped.body)
def test_ssl_verification(self): client = HTTPClient('https://test/') client.session.cert = '/path/to/cert' client.session.verify = 'ca-cert' request = PreparedRequest(Request('go')) client.prepare_request(request) with self.assertRaises(OSError): # Invalid certificate client.send_message(request)
def create_task(title, description=None, color_id=None): return Request('createTask', title=title, description=description, color_id=color_id, project_id=env('KANBOARD_PROJECT_ID'), column_id=env('KANBOARD_COLUMN_ID', default=None), swimlane_id=env('KANBOARD_SWIMLANE_ID', default=None))
def test(self): responses.add( responses.POST, "http://foo", status=200, body='{"jsonrpc": "2.0", "result": 5, "id": 1}', ) HTTPClient("http://foo").send_message(str(Request("foo")))
def test_ssl_verification(self): client = HTTPClient('https://test/') client.session.cert = '/path/to/cert' client.session.verify = 'ca-cert' request = PreparedRequest(Request('go')) client.prepare_request(request) with self.assertRaises(requests.exceptions.RequestException): client.send_message(request)
def test_positional(self): self.assertEqual( { 'jsonrpc': '2.0', 'method': 'sqrt', 'params': [1], 'id': 1 }, Request('sqrt', 1))
def test_send_message_conn_error(self): client = ZeroMQClient("tcp://localhost:5555") # Set timeouts client.socket.setsockopt(zmq.RCVTIMEO, 5) client.socket.setsockopt(zmq.SNDTIMEO, 5) client.socket.setsockopt(zmq.LINGER, 5) with pytest.raises(zmq.error.ZMQError): client.send_message(str(Request("go")))
def load_block_info(height_hash, fetch_size=True): block_data = dict() logging.getLogger('jsonrpcclient').setLevel(logging.ERROR) client = HTTPClient("http://127.0.0.1:20206/json_rpc") height_hash = str(height_hash) try: if len(height_hash) == 64: response = client.send(Request("getblock", hash=height_hash)).data.result else: height_hash = int(height_hash) response = client.send(Request("getblock", height=height_hash)).data.result except ReceivedNon2xxResponseError as e: logging.warning(e) return False, None block_data['block_hash'] = response['block_header']['hash'] block_data['block_difficulty'] = response['block_header']['difficulty'] block_data['timestamp'] = response['block_header']['timestamp'] block_data['time'] = datetime.utcfromtimestamp( block_data['timestamp']).strftime('%Y-%m-%d %H:%M:%S') block_data['height'] = response['block_header']['height'] block_data['topo_height'] = response['block_header']['topoheight'] block_data['depth'] = response['block_header']['depth'] block_data['tips'] = response['block_header']['tips'] json_data = json.loads(response['json']) block_data['miner_tx'] = json_data['miner_tx'] block_data[ 'miner_reward'] = response['block_header']['reward'] / 1000000000000 block_data['tx_hashes'] = json_data['tx_hashes'] block_data['size'] = 0 block_data['tx_size_list'] = list() if block_data['tx_hashes'] and fetch_size: block_data['tx_count'] = len(block_data['tx_hashes']) for tx in block_data['tx_hashes']: _, tx_data = load_tx_info(tx) block_data['size'] += tx_data['size'] block_data['tx_size_list'].append(tx_data['size']) block_data['size'] = "{0:.3f}".format(block_data['size']) block_data['hash_size_list'] = zip(block_data['tx_hashes'], block_data['tx_size_list']) else: block_data['tx_count'] = 0 return True, block_data
def test_keyword(self): assert Request("find", name="Foo") == { "jsonrpc": "2.0", "method": "find", "params": { "name": "Foo" }, "id": 1, }
def test_success_200(): client = HTTPClient('http://test/') request = PreparedRequest(Request('go')) client.prepare_request(request) responses.add(responses.POST, 'http://test/', status=200, body='{"jsonrpc": "2.0", "result": 5, "id": 1}') client.send_message(request)
async def handle_client(stop, port=PORT): """Handle for the RPC client""" async with websockets.connect('ws://%s:%d' % (HOST, port)) as websocket: client = WebSocketsClient(websocket) request = Request('ping', duration=3, period=1, message=TEST_MESSAGE) response = await client.send(request) print('Waiting for event with the id %d' % response['id']) await client.wait() stop.set_result(None)
def test_custom_headers(self, *_): response = yield TornadoClient(self.get_url("/echo")).send( Request("foo", 1, [2], { "3": 4, "5": True, "6": None }), headers={"foo": "bar"}, ) assert response.data.result == [1, [2], {"3": 4, "6": None, "5": True}]
def test_keyword(self): self.assertEqual( { 'jsonrpc': '2.0', 'method': 'find', 'params': { 'name': 'Foo' }, 'id': 1 }, Request('find', name='Foo'))
def test_invalid_request(self): client = HTTPClient('http://test/') request = PreparedRequest(Request('go')) client.prepare_request(request) # Impossible to pass an invalid dict, so just assume the exception was raised responses.add(responses.POST, 'http://test/', status=400, body=requests.exceptions.InvalidSchema()) with self.assertRaises(requests.exceptions.InvalidSchema): client.send_message(request)
def test_update_userprefs(): client = HTTPClient('http://*****:*****@steemit.com']}) print('request sent:') pprint.pprint(req) results = client.send(req) print('Server response:') pprint.pprint(results)
def test_method_name_directly(self): self.assertEqual( {'jsonrpc': '2.0', 'method': 'cat', 'id': 1}, Request.cat()) #pylint:disable=no-member