fix discriminator tag issue

This commit is contained in:
Danglewood
2024-11-14 19:38:20 -08:00
parent 4f5a14b615
commit 31b05c0c15
5 changed files with 68 additions and 47 deletions

View File

@@ -3,7 +3,7 @@
import logging
import re
import sys
from typing import Optional
from typing import Any, Optional
from openbb_core.app.model.abstract.error import OpenBBError
from openbb_core.provider.utils.errors import UnauthorizedError
@@ -46,11 +46,13 @@ def handle_validation_error(logger: logging.Logger, error: ValidationError):
raise error from error
async def get_status(name: str) -> dict:
async def get_status(name: Optional[str] = None, client: Optional[Any] = None) -> dict:
"""Get the status of a client."""
if name not in connected_clients:
if name and name not in connected_clients:
raise OpenBBError(f"Client {name} not connected.")
client = connected_clients[name]
if not name and not client:
raise OpenBBError("Either name or client must be provided.")
client = client if client else connected_clients[name]
provider_pid = client._psutil_process.pid if client.is_running else None
broadcast_pid = (
client._psutil_broadcast_process.pid if client.is_broadcasting else None

View File

@@ -8,9 +8,8 @@ from openbb_core.provider.abstract.data import Data
from openbb_core.provider.abstract.query_params import QueryParams
from openbb_core.provider.utils.descriptions import (
DATA_DESCRIPTIONS,
QUERY_DESCRIPTIONS,
)
from pydantic import ConfigDict, Field, field_validator
from pydantic import ConfigDict, Field, field_validator, model_validator
from openbb_websockets.client import WebSocketClient
@@ -89,39 +88,6 @@ class WebSocketQueryParams(QueryParams):
return json.dumps(v, separators=(",", ":"))
class WebSocketData(Data):
"""WebSocket data model."""
date: datetime = Field(
description=DATA_DESCRIPTIONS.get("date", ""),
)
symbol: str = Field(
description=DATA_DESCRIPTIONS.get("symbol", ""),
)
class WebSocketConnection(Data):
"""Data model for returning WebSocketClient from the Provider Interface."""
__model_config__ = ConfigDict(
extra="forbid",
)
client: Any = Field(
description="Instance of WebSocketClient class initialized by a provider Fetcher."
+ " The client is used to communicate with the provider's data stream."
+ " It is not returned to the user, but is handled by the router for API access.",
exclude=True,
)
@field_validator("client", mode="before", check_fields=False)
def _validate_client(cls, v):
"""Validate the client."""
if not isinstance(v, WebSocketClient):
raise ValueError("Client must be an instance of WebSocketClient.")
return v
class WebSocketConnectionStatus(Data):
"""Data model for WebSocketConnection status information."""
@@ -164,3 +130,50 @@ class WebSocketConnectionStatus(Data):
save_results: bool = Field(
description="Whether to save the results after the session ends.",
)
class WebSocketData(Data):
"""WebSocket data model."""
date: datetime = Field(
description=DATA_DESCRIPTIONS.get("date", ""),
)
symbol: str = Field(
description=DATA_DESCRIPTIONS.get("symbol", ""),
)
class WebSocketConnection(Data):
"""Data model for returning WebSocketClient from the Provider Interface."""
__model_config__ = ConfigDict(
extra="forbid",
)
client: Optional[Any] = Field(
default=None,
description="Instance of WebSocketClient class initialized by a provider Fetcher."
+ " The client is used to communicate with the provider's data stream."
+ " It is not returned to the user, but is handled by the router for API access.",
exclude=True,
)
status: Optional[WebSocketConnectionStatus] = Field(
default=None,
description="Status information for the WebSocket connection.",
)
@field_validator("client", mode="before", check_fields=False)
@classmethod
def _validate_client(cls, v):
"""Validate the client."""
if v and not isinstance(v, WebSocketClient):
raise ValueError("Client must be an instance of WebSocketClient.")
return v
@model_validator(mode="before")
@classmethod
def _validate_inputs(cls, vaules):
"""Validate the status."""
if not vaules.get("status") and not vaules.get("client"):
raise ValueError("Cannot initialize empty.")
return vaules

View File

@@ -39,8 +39,9 @@ async def create_connection(
provider_choices: ProviderChoices,
standard_params: StandardParams,
extra_params: ExtraParams,
) -> OBBject[WebSocketConnectionStatus]:
) -> OBBject:
"""Create a new provider websocket connection."""
name = extra_params.name
if name in connected_clients:
broadcast_address = connected_clients[name].broadcast_address
@@ -70,10 +71,8 @@ async def create_connection(
client_name = client.name
connected_clients[client_name] = client
results = await get_status(client_name)
obbject.results = WebSocketConnectionStatus(**results)
status = await get_status(client_name)
obbject.results.status = WebSocketConnectionStatus(**status)
return obbject

View File

@@ -155,8 +155,15 @@ async def connect_and_stream(url, symbol, api_key, results_path, table_name, lim
message = task.result()
await asyncio.shield(queue.enqueue(json.loads(message)))
except websockets.ConnectionClosed:
logger.info("PROVIDER INFO: The WebSocket connection was closed.")
except websockets.ConnectionClosed as e:
msg = (
f"PROVIDER INFO: The WebSocket connection was closed -> {e.__str__()}"
)
logger.info(msg)
# Attempt to reopen the connection
logger.info("PROVIDER INFO: Attempting to reconnect after five seconds.")
await asyncio.sleep(5)
await connect_and_stream(url, symbol, api_key, results_path, table_name, limit)
except websockets.WebSocketException as e:
logger.error(e)

View File

@@ -137,7 +137,7 @@ class PolygonWebSocketQueryParams(WebSocketQueryParams):
}
symbol: str = Field(
description="Polygon symbol to get data for."
description="\n Polygon symbol to get data for."
+ " All feeds, except Options, support the wildcard symbol, '*', for all symbols."
+ "\n Options symbols are the OCC contract symbol and support up to 1000 individual contracts"
+ " per connection. Crypto and FX symbols should be entered as a pair, i.e., 'BTCUSD', 'JPYUSD'."