2022-08-29 19:41:15 +00:00
|
|
|
import logging
|
2022-08-31 16:40:26 +00:00
|
|
|
from typing import Any, Dict
|
2022-08-29 19:41:15 +00:00
|
|
|
|
|
|
|
from fastapi import APIRouter, Depends, WebSocket, WebSocketDisconnect
|
2022-09-04 16:22:10 +00:00
|
|
|
# fastapi does not make this available through it, so import directly from starlette
|
|
|
|
from starlette.websockets import WebSocketState
|
2022-08-29 19:41:15 +00:00
|
|
|
|
2022-08-31 16:40:26 +00:00
|
|
|
from freqtrade.enums import RPCMessageType, RPCRequestType
|
2022-09-02 02:06:36 +00:00
|
|
|
from freqtrade.rpc.api_server.deps import get_channel_manager, get_rpc
|
2022-08-31 16:40:26 +00:00
|
|
|
from freqtrade.rpc.api_server.ws.channel import WebSocketChannel
|
2022-09-02 02:06:36 +00:00
|
|
|
from freqtrade.rpc.rpc import RPC
|
2022-08-29 19:41:15 +00:00
|
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
# Private router, protected by API Key authentication
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
|
|
|
2022-09-04 16:22:10 +00:00
|
|
|
async def is_websocket_alive(ws: WebSocket) -> bool:
|
|
|
|
if (
|
|
|
|
ws.application_state == WebSocketState.CONNECTED and
|
|
|
|
ws.client_state == WebSocketState.CONNECTED
|
|
|
|
):
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
2022-09-02 02:06:36 +00:00
|
|
|
async def _process_consumer_request(
|
|
|
|
request: Dict[str, Any],
|
|
|
|
channel: WebSocketChannel,
|
|
|
|
rpc: RPC
|
|
|
|
):
|
2022-08-31 16:40:26 +00:00
|
|
|
type, data = request.get('type'), request.get('data')
|
|
|
|
|
2022-09-02 21:05:16 +00:00
|
|
|
logger.debug(f"Request of type {type} from {channel}")
|
|
|
|
|
2022-08-31 16:40:26 +00:00
|
|
|
# If we have a request of type SUBSCRIBE, set the topics in this channel
|
|
|
|
if type == RPCRequestType.SUBSCRIBE:
|
2022-09-02 02:06:36 +00:00
|
|
|
# If the request is empty, do nothing
|
|
|
|
if not data:
|
|
|
|
return
|
|
|
|
|
|
|
|
if not isinstance(data, list):
|
2022-09-02 05:52:13 +00:00
|
|
|
logger.error(f"Improper subscribe request from channel: {channel} - {request}")
|
2022-08-31 16:40:26 +00:00
|
|
|
return
|
|
|
|
|
|
|
|
# If all topics passed are a valid RPCMessageType, set subscriptions on channel
|
|
|
|
if all([any(x.value == topic for x in RPCMessageType) for topic in data]):
|
|
|
|
|
|
|
|
logger.debug(f"{channel} subscribed to topics: {data}")
|
|
|
|
channel.set_subscriptions(data)
|
|
|
|
|
2022-09-02 05:52:13 +00:00
|
|
|
elif type == RPCRequestType.WHITELIST:
|
|
|
|
# They requested the whitelist
|
|
|
|
whitelist = rpc._ws_request_whitelist()
|
2022-09-02 02:06:36 +00:00
|
|
|
|
2022-09-02 05:52:13 +00:00
|
|
|
await channel.send({"type": RPCMessageType.WHITELIST, "data": whitelist})
|
2022-09-02 02:06:36 +00:00
|
|
|
|
2022-09-02 05:52:13 +00:00
|
|
|
elif type == RPCRequestType.ANALYZED_DF:
|
2022-09-02 21:05:16 +00:00
|
|
|
limit = None
|
|
|
|
|
|
|
|
if data:
|
|
|
|
# Limit the amount of candles per dataframe to 'limit' or 1500
|
|
|
|
limit = max(data.get('limit', 500), 1500)
|
|
|
|
|
2022-09-02 05:52:13 +00:00
|
|
|
# They requested the full historical analyzed dataframes
|
2022-09-02 21:05:16 +00:00
|
|
|
analyzed_df = rpc._ws_request_analyzed_df(limit)
|
|
|
|
|
2022-09-02 05:52:13 +00:00
|
|
|
# For every dataframe, send as a separate message
|
|
|
|
for _, message in analyzed_df.items():
|
|
|
|
await channel.send({"type": RPCMessageType.ANALYZED_DF, "data": message})
|
2022-09-02 02:06:36 +00:00
|
|
|
|
2022-08-31 16:40:26 +00:00
|
|
|
|
2022-08-29 19:41:15 +00:00
|
|
|
@router.websocket("/message/ws")
|
|
|
|
async def message_endpoint(
|
|
|
|
ws: WebSocket,
|
2022-09-02 02:06:36 +00:00
|
|
|
rpc: RPC = Depends(get_rpc),
|
|
|
|
channel_manager=Depends(get_channel_manager),
|
2022-08-29 19:41:15 +00:00
|
|
|
):
|
|
|
|
try:
|
|
|
|
if is_websocket_alive(ws):
|
|
|
|
# TODO:
|
|
|
|
# Return a channel ID, pass that instead of ws to the rest of the methods
|
|
|
|
channel = await channel_manager.on_connect(ws)
|
|
|
|
|
2022-09-02 21:05:16 +00:00
|
|
|
logger.info(f"Consumer connected - {channel}")
|
|
|
|
|
2022-08-31 01:21:34 +00:00
|
|
|
# Keep connection open until explicitly closed, and process requests
|
2022-08-29 19:41:15 +00:00
|
|
|
try:
|
|
|
|
while not channel.is_closed():
|
|
|
|
request = await channel.recv()
|
|
|
|
|
2022-09-02 21:05:16 +00:00
|
|
|
# Process the request here
|
2022-09-02 02:06:36 +00:00
|
|
|
await _process_consumer_request(request, channel, rpc)
|
2022-08-29 19:41:15 +00:00
|
|
|
|
|
|
|
except WebSocketDisconnect:
|
|
|
|
# Handle client disconnects
|
2022-09-02 21:05:16 +00:00
|
|
|
logger.info(f"Consumer disconnected - {channel}")
|
2022-08-29 19:41:15 +00:00
|
|
|
await channel_manager.on_disconnect(ws)
|
|
|
|
except Exception as e:
|
2022-09-02 21:05:16 +00:00
|
|
|
logger.info(f"Consumer connection failed - {channel}")
|
2022-08-29 19:41:15 +00:00
|
|
|
logger.exception(e)
|
|
|
|
# Handle cases like -
|
|
|
|
# RuntimeError('Cannot call "send" once a closed message has been sent')
|
|
|
|
await channel_manager.on_disconnect(ws)
|
|
|
|
|
2022-09-02 21:05:16 +00:00
|
|
|
except Exception as e:
|
2022-08-29 19:41:15 +00:00
|
|
|
logger.error(f"Failed to serve - {ws.client}")
|
2022-09-02 21:05:16 +00:00
|
|
|
# Log tracebacks to keep track of what errors are happening
|
|
|
|
logger.exception(e)
|
2022-08-29 19:41:15 +00:00
|
|
|
await channel_manager.on_disconnect(ws)
|