|
| 1 | +"""Base classes for data provider adapters.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import json |
| 6 | +from abc import ABC, abstractmethod |
| 7 | +from dataclasses import dataclass, field |
| 8 | +from typing import Any, AsyncIterator, Dict, List, Optional |
| 9 | + |
| 10 | +import websockets |
| 11 | + |
| 12 | +from ..auth_manager import AuthManager |
| 13 | +from ..rate_limiter import AdaptiveRateLimiter |
| 14 | + |
| 15 | + |
| 16 | +@dataclass |
| 17 | +class DataProviderAdapter(ABC): |
| 18 | + """Abstract adapter defining basic WebSocket operations.""" |
| 19 | + |
| 20 | + websocket_url: str |
| 21 | + name: str |
| 22 | + connection: Optional[websockets.WebSocketClientProtocol] = field( |
| 23 | + default=None, init=False |
| 24 | + ) |
| 25 | + circuit_breaker: Any = field(default=None, init=False) |
| 26 | + rate_limiter: Optional[AdaptiveRateLimiter] = field(default=None, init=False) |
| 27 | + auth_manager: Optional[AuthManager] = field(default=None, init=False) |
| 28 | + |
| 29 | + async def connect(self) -> None: |
| 30 | + """Establish a WebSocket connection to the provider.""" |
| 31 | + |
| 32 | + headers = None |
| 33 | + if self.auth_manager: |
| 34 | + headers = await self.auth_manager.get_auth_headers() |
| 35 | + self.connection = await websockets.connect( |
| 36 | + self.websocket_url, extra_headers=headers |
| 37 | + ) |
| 38 | + |
| 39 | + async def subscribe(self, channel: str, symbols: List[str]) -> None: |
| 40 | + """Send a subscription message for ``symbols`` on ``channel``.""" |
| 41 | + |
| 42 | + if self.connection is None: |
| 43 | + await self.connect() |
| 44 | + message = self._build_subscribe_message(channel, symbols) |
| 45 | + if self.rate_limiter: |
| 46 | + await self.rate_limiter.acquire() |
| 47 | + await self.connection.send(json.dumps(message)) |
| 48 | + |
| 49 | + async def listen(self) -> AsyncIterator[Dict[str, Any]]: |
| 50 | + """Yield parsed JSON messages from the connection.""" |
| 51 | + |
| 52 | + if self.connection is None: |
| 53 | + raise RuntimeError("Connection not established") |
| 54 | + async for message in self.connection: |
| 55 | + yield json.loads(message) |
| 56 | + |
| 57 | + @abstractmethod |
| 58 | + def _build_subscribe_message( |
| 59 | + self, channel: str, symbols: List[str] |
| 60 | + ) -> Dict[str, Any]: |
| 61 | + """Return provider specific subscription payload.""" |
0 commit comments