2022-10-09 21:04:52 +00:00
|
|
|
import asyncio
|
2022-08-29 19:41:15 +00:00
|
|
|
import logging
|
2022-11-15 03:27:45 +00:00
|
|
|
from contextlib import asynccontextmanager
|
2022-10-25 17:36:40 +00:00
|
|
|
from typing import Any, Dict, List, Optional, Type, Union
|
2022-09-02 21:05:16 +00:00
|
|
|
from uuid import uuid4
|
2022-08-29 19:41:15 +00:00
|
|
|
|
|
|
|
from freqtrade.rpc.api_server.ws.proxy import WebSocketProxy
|
2022-09-02 06:05:36 +00:00
|
|
|
from freqtrade.rpc.api_server.ws.serializer import (HybridJSONWebSocketSerializer,
|
|
|
|
WebSocketSerializer)
|
2022-08-29 19:41:15 +00:00
|
|
|
from freqtrade.rpc.api_server.ws.types import WebSocketType
|
2022-10-25 17:36:40 +00:00
|
|
|
from freqtrade.rpc.api_server.ws_schemas import WSMessageSchemaType
|
2022-08-29 19:41:15 +00:00
|
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
class WebSocketChannel:
|
|
|
|
"""
|
|
|
|
Object to help facilitate managing a websocket connection
|
|
|
|
"""
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
websocket: WebSocketType,
|
2022-09-02 21:05:16 +00:00
|
|
|
channel_id: Optional[str] = None,
|
2022-09-02 06:05:36 +00:00
|
|
|
serializer_cls: Type[WebSocketSerializer] = HybridJSONWebSocketSerializer
|
2022-08-29 19:41:15 +00:00
|
|
|
):
|
2022-09-02 21:05:16 +00:00
|
|
|
self.channel_id = channel_id if channel_id else uuid4().hex[:8]
|
2022-08-29 19:41:15 +00:00
|
|
|
self._websocket = WebSocketProxy(websocket)
|
|
|
|
|
|
|
|
# Internal event to signify a closed websocket
|
2022-11-02 19:26:27 +00:00
|
|
|
self._closed = asyncio.Event()
|
2022-11-18 20:32:27 +00:00
|
|
|
self._send_timeout_high_limit = 2
|
2022-08-29 19:41:15 +00:00
|
|
|
|
2022-11-15 05:21:40 +00:00
|
|
|
# The subscribed message types
|
|
|
|
self._subscriptions: List[str] = []
|
2022-11-15 03:27:45 +00:00
|
|
|
|
2022-08-29 19:41:15 +00:00
|
|
|
# Wrap the WebSocket in the Serializing class
|
2022-11-13 09:26:27 +00:00
|
|
|
self._wrapped_ws = serializer_cls(self._websocket)
|
2022-08-29 19:41:15 +00:00
|
|
|
|
2022-11-18 20:32:27 +00:00
|
|
|
# The async tasks created for the channel
|
|
|
|
self._channel_tasks: List[asyncio.Task] = []
|
|
|
|
|
2022-09-02 21:05:16 +00:00
|
|
|
def __repr__(self):
|
|
|
|
return f"WebSocketChannel({self.channel_id}, {self.remote_addr})"
|
|
|
|
|
2022-10-23 01:02:05 +00:00
|
|
|
@property
|
2022-10-23 17:42:59 +00:00
|
|
|
def raw_websocket(self):
|
|
|
|
return self._websocket.raw_websocket
|
2022-10-23 01:02:05 +00:00
|
|
|
|
2022-09-02 21:05:16 +00:00
|
|
|
@property
|
|
|
|
def remote_addr(self):
|
|
|
|
return self._websocket.remote_addr
|
|
|
|
|
2022-11-15 03:27:45 +00:00
|
|
|
async def send(self, message: Union[WSMessageSchemaType, Dict[str, Any]]):
|
2022-10-10 00:49:04 +00:00
|
|
|
"""
|
2022-11-15 03:27:45 +00:00
|
|
|
Send a message on the wrapped websocket
|
2022-10-10 00:49:04 +00:00
|
|
|
"""
|
2022-11-19 20:21:26 +00:00
|
|
|
await self._wrapped_ws.send(message)
|
2022-11-18 20:32:27 +00:00
|
|
|
|
|
|
|
# Without this sleep, messages would send to one channel
|
2022-11-19 20:21:26 +00:00
|
|
|
# first then another after the first one finished and prevent
|
|
|
|
# any normal Rest API calls from processing at the same time.
|
2022-11-18 20:32:27 +00:00
|
|
|
# With the sleep call, it gives control to the event
|
2022-11-19 20:21:26 +00:00
|
|
|
# loop to schedule other channel send methods, and helps
|
|
|
|
# throttle how fast we send.
|
2022-11-19 20:29:23 +00:00
|
|
|
# 0.005 = 200 messages/second max throughput
|
|
|
|
await asyncio.sleep(0.005)
|
2022-10-10 00:49:04 +00:00
|
|
|
|
2022-08-29 19:41:15 +00:00
|
|
|
async def recv(self):
|
|
|
|
"""
|
2022-11-15 03:27:45 +00:00
|
|
|
Receive a message on the wrapped websocket
|
2022-08-29 19:41:15 +00:00
|
|
|
"""
|
|
|
|
return await self._wrapped_ws.recv()
|
|
|
|
|
|
|
|
async def ping(self):
|
|
|
|
"""
|
|
|
|
Ping the websocket
|
|
|
|
"""
|
|
|
|
return await self._websocket.ping()
|
|
|
|
|
2022-11-15 03:27:45 +00:00
|
|
|
async def accept(self):
|
|
|
|
"""
|
|
|
|
Accept the underlying websocket connection
|
|
|
|
"""
|
|
|
|
return await self._websocket.accept()
|
|
|
|
|
2022-08-29 19:41:15 +00:00
|
|
|
async def close(self):
|
|
|
|
"""
|
|
|
|
Close the WebSocketChannel
|
|
|
|
"""
|
|
|
|
|
2022-11-17 19:03:11 +00:00
|
|
|
self._closed.set()
|
|
|
|
|
2022-11-02 19:26:27 +00:00
|
|
|
try:
|
2022-11-15 03:27:45 +00:00
|
|
|
await self._websocket.close()
|
2022-11-02 19:26:27 +00:00
|
|
|
except Exception:
|
|
|
|
pass
|
|
|
|
|
2022-08-29 21:48:29 +00:00
|
|
|
def is_closed(self) -> bool:
|
|
|
|
"""
|
|
|
|
Closed flag
|
|
|
|
"""
|
2022-11-02 19:26:27 +00:00
|
|
|
return self._closed.is_set()
|
2022-08-29 19:41:15 +00:00
|
|
|
|
2022-08-29 21:48:29 +00:00
|
|
|
def set_subscriptions(self, subscriptions: List[str] = []) -> None:
|
|
|
|
"""
|
|
|
|
Set which subscriptions this channel is subscribed to
|
|
|
|
|
|
|
|
:param subscriptions: List of subscriptions, List[str]
|
|
|
|
"""
|
|
|
|
self._subscriptions = subscriptions
|
|
|
|
|
|
|
|
def subscribed_to(self, message_type: str) -> bool:
|
|
|
|
"""
|
|
|
|
Check if this channel is subscribed to the message_type
|
|
|
|
|
|
|
|
:param message_type: The message type to check
|
|
|
|
"""
|
|
|
|
return message_type in self._subscriptions
|
|
|
|
|
2022-11-18 20:32:27 +00:00
|
|
|
async def run_channel_tasks(self, *tasks, **kwargs):
|
2022-10-09 21:04:52 +00:00
|
|
|
"""
|
2022-11-18 20:32:27 +00:00
|
|
|
Create and await on the channel tasks unless an exception
|
|
|
|
was raised, then cancel them all.
|
|
|
|
|
|
|
|
:params *tasks: All coros or tasks to be run concurrently
|
|
|
|
:param **kwargs: Any extra kwargs to pass to gather
|
2022-10-09 21:04:52 +00:00
|
|
|
"""
|
|
|
|
|
2022-11-18 20:32:27 +00:00
|
|
|
# Wrap the coros into tasks if they aren't already
|
|
|
|
self._channel_tasks = [
|
|
|
|
task if isinstance(task, asyncio.Task) else asyncio.create_task(task)
|
|
|
|
for task in tasks
|
|
|
|
]
|
|
|
|
|
|
|
|
try:
|
2022-11-19 20:21:26 +00:00
|
|
|
return await asyncio.gather(*self._channel_tasks, **kwargs)
|
2022-11-18 20:32:27 +00:00
|
|
|
except Exception:
|
2022-11-19 20:21:26 +00:00
|
|
|
# If an exception occurred, cancel the rest of the tasks
|
2022-11-18 20:32:27 +00:00
|
|
|
await self.cancel_channel_tasks()
|
|
|
|
|
|
|
|
async def cancel_channel_tasks(self):
|
2022-08-29 19:41:15 +00:00
|
|
|
"""
|
2022-11-18 20:32:27 +00:00
|
|
|
Cancel and wait on all channel tasks
|
2022-08-29 19:41:15 +00:00
|
|
|
"""
|
2022-11-18 20:32:27 +00:00
|
|
|
for task in self._channel_tasks:
|
|
|
|
task.cancel()
|
|
|
|
|
|
|
|
# Wait for tasks to finish cancelling
|
2022-11-15 03:27:45 +00:00
|
|
|
try:
|
2022-11-18 20:32:27 +00:00
|
|
|
await asyncio.wait(self._channel_tasks)
|
|
|
|
except asyncio.CancelledError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
self._channel_tasks = []
|
|
|
|
|
|
|
|
async def __aiter__(self):
|
|
|
|
"""
|
|
|
|
Generator for received messages
|
|
|
|
"""
|
|
|
|
# We can not catch any errors here as websocket.recv is
|
|
|
|
# the first to catch any disconnects and bubble it up
|
|
|
|
# so the connection is garbage collected right away
|
|
|
|
while not self.is_closed():
|
|
|
|
yield await self.recv()
|
|
|
|
|
|
|
|
|
|
|
|
@asynccontextmanager
|
|
|
|
async def create_channel(websocket: WebSocketType, **kwargs):
|
|
|
|
"""
|
|
|
|
Context manager for safely opening and closing a WebSocketChannel
|
|
|
|
"""
|
|
|
|
channel = WebSocketChannel(websocket, **kwargs)
|
|
|
|
try:
|
|
|
|
await channel.accept()
|
|
|
|
logger.info(f"Connected to channel - {channel}")
|
|
|
|
|
|
|
|
yield channel
|
|
|
|
finally:
|
|
|
|
await channel.close()
|
|
|
|
logger.info(f"Disconnected from channel - {channel}")
|