Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
async def test_explicit_permanent_key_unavailable(
self, server_no_key, server, client_factory
):
"""
Check that the server rejects a permanent key if the server
has none.
"""
key = libnacl.public.SecretKey()
# Expect invalid key
with pytest.raises(websockets.ConnectionClosed) as exc_info:
await client_factory(
server=server_no_key, permanent_key=key.pk, explicit_permanent_key=True,
initiator_handshake=True)
assert exc_info.value.code == CloseCode.invalid_key
await server.wait_connections_closed()
async def send_message(websocket, path):
web_tick_rate = float(global_settings.cfg[C_WEB_SETTINGS][P_WEB_TICK_RATE])
try:
while True:
# web_data = monitor_service.get_hardware_info()
# web_data.update(monitor_service.get_system_info())
web_data = {"cur_time": str(datetime.now()).split('.')[0]}
web_data.update({"bot_uptime": f'{check_up_time()}'})
web_data.update(monitor_service.get_last_command_output())
web_data.update(monitor_service.get_all_online())
packed_data = json.dumps(web_data)
await websocket.send(packed_data)
await asyncio.sleep(web_tick_rate)
except websockets.ConnectionClosed:
return
def run(self):
"""
Handle incoming level 3 data on a separate thread
:return:
"""
while True:
msg = self.queue.get()
if self.book.new_tick(msg) is False:
self.retry_counter += 1
self.book.clear_book()
print('\n[Bitfinex - %s] ...going to try and reload the order book\n' % self.sym)
raise websockets.ConnectionClosed(1006, 'no reason') # raise an exception to invoke reconnecting
async def receive(self) -> IncomingMessageMixin:
"""
Disconnected
"""
# Safeguard
# Note: This should never happen since the receive queue will
# be stopped when a client is being dropped.
assert self.state < ClientState.dropped
# Receive data
try:
data = await self._connection.recv()
except websockets.ConnectionClosed as exc:
self.log.debug('Connection closed while receiving')
disconnected = Disconnected(exc.code)
self.jobs.close(Result(disconnected))
raise disconnected from exc
self.log.debug('Received message')
# Ensure binary
if not isinstance(data, bytes):
raise MessageError("Data must be 'bytes', not '{}'".format(type(data)))
# Unpack data and return
message = unpack(self, Packet(data))
self.log.debug('Unpacked message: {}', message.type)
self.log.trace('server << {}', message)
return message
async def future_read_message(ws, future):
try:
message = await ws.stomp_read_message()
future.set_result(message)
except ConnectionClosed:
print('Websocket connection closed')
# After trying a couple of time, we must check the status of the experiment
if should_check > RESOURCES_CHECK:
experiment.refresh_from_db()
if experiment.is_done:
logger.info(
'removing all socket because the experiment `%s` is done', experiment_uuid)
ws_manager.ws = set([])
handle_experiment_disconnected_ws(ws)
return
else:
should_check -= CHECK_DELAY
if resources:
try:
await ws.send(resources)
except ConnectionClosed:
handle_experiment_disconnected_ws(ws)
return
# Just to check if connection closed
if ws._connection_lost: # pylint:disable=protected-access
handle_experiment_disconnected_ws(ws)
return
await asyncio.sleep(SOCKET_SLEEP)
keep_waiting = True
try:
ws_url = self.STREAM_URL + self._prefix + self._path
async with ws.connect(ws_url) as socket:
self._reconnect_wait = self.MIN_RECONNECT_WAIT
while keep_waiting:
evt = await socket.recv()
try:
evt_obj = json.loads(evt)
except ValueError:
pass
else:
await self._coro(evt_obj)
except ws.ConnectionClosed as e:
self._log.debug('ws connection closed:{}'.format(e))
keep_waiting = False
await self._reconnect()
except Exception as e:
self._log.debug('ws exception:{}'.format(e))
keep_waiting = False
# await self._reconnect()
for sdfg in self.render_queue:
if isinstance(sdfg, str):
json = sdfg
else:
json = sdfg.to_json()
await websocket.send(json)
self.render_queue.clear()
# Lock to ensure correct operation (commands can be added asynchronously)
with self.comm_queue_lock:
for cmd in self.command_queue:
# The difference in the command queue: All data must already be in JSON format
await websocket.send(cmd)
self.command_queue.clear()
except websockets.ConnectionClosed:
# If the connection was closed, probably a refresh was
# requested. This also means that we have to re-queue
print("Restoring render queue after abort")
self.render_queue = self.restore_render_queue.copy()
self.command_queue = self.restore_command_queue.copy()
break
(self.exchange.upper(), self.sym))
if self.trades_request is not None:
LOGGER.info('Requesting Trades: {}'.format(self.trades_request))
await self.ws.send(self.trades_request)
LOGGER.info('TRADES %s: %s subscription request sent.' %
(self.exchange.upper(), self.sym))
self.last_subscribe_time = dt.now(tz=TIMEZONE)
# Add incoming messages to a queue, which is consumed and processed
# in the run() method.
while True:
self.queue.put(json.loads(await self.ws.recv()))
except websockets.ConnectionClosed as exception:
LOGGER.warn('%s: subscription exception %s' % (self.exchange, exception))
self.retry_counter += 1
elapsed = (dt.now(tz=TIMEZONE) - self.last_subscribe_time).seconds
if elapsed < 10:
sleep_time = max(10 - elapsed, 1)
time.sleep(sleep_time)
LOGGER.info('%s - %s is sleeping %i seconds...' %
(self.exchange, self.sym, sleep_time))
if self.retry_counter < self.max_retries:
LOGGER.info('%s: Retrying to connect... attempted #%i' %
(self.exchange, self.retry_counter))
await self.subscribe() # recursion
else:
LOGGER.warn('%s: %s Ran out of reconnection attempts. '
evt = await asyncio.wait_for(self._socket.recv(), timeout=self.TIMEOUT)
except asyncio.TimeoutError:
self._log.debug("no message in {} seconds".format(self.TIMEOUT))
await self._socket.ping()
except asyncio.CancelledError:
self._log.debug("cancelled error")
await self._socket.ping()
else:
try:
evt_obj = json.loads(evt)
except ValueError:
pass
else:
await self._coro(evt_obj)
except ws.ConnectionClosed as e:
keep_waiting = False
await self._reconnect()
except Exception as e:
self._log.debug('ws exception:{}'.format(e))
keep_waiting = False
# await self._reconnect()