"""EXPERIMENTAL: generic raw-WebSocket-passthrough scraper. Shared implementation behind modules/monitor/momo_scraper.py and the StockTitan feed instances in modules/monitor/titan_scraper.py -- same Playwright headless-tab + page.on("websocket") approach, parameterized by target URL and a frame parser, since StockTitan runs several independent socket servers (news, filings, halts, momentum scanner) that all use the exact same plain-JSON frame shape. """ import asyncio import contextlib import logging from collections.abc import Callable from typing import cast from playwright.async_api import BrowserContext, Page, Request, ViewportSize, WebSocket from modules.monitor import shared_browser logger = logging.getLogger(__name__) # ``start()`` waits for the site's own socket to attach before reporting the # scraper up, so a subscriber never joins a stream that is still empty. The # wait is bounded: a site that never opens a socket is a site we keep # retrying, not one that should block the caller forever. READY_TIMEOUT_S = 30.0 # A stopped scraper keeps its warm context (validated cookies, established # connection) instead of paying a fresh session on the next start. The context # is only dropped after this long with nobody subscribed -- closing a tab does # not give the memory back, so the recycle has to be deliberate. CONTEXT_IDLE_S = 300.0 # We only need the page's WebSocket to connect, not its rendering -- blocking # these cuts CPU drastically since there's nothing left for the page's own # JS to draw/animate on every incoming frame. _BLOCKED_RESOURCE_TYPES = {"image", "stylesheet", "font", "media"} # Ad/analytics/tracking scripts run their own JS (impression pixels, session # replay, heatmaps, ad auctions) that has nothing to do with the site's own # data socket -- blocked by hostname regardless of resource_type, since some # of these load as "script"/"xhr" which we otherwise let through. _BLOCKED_HOST_SUBSTRINGS = ( "google-analytics.com", "googletagmanager.com", "doubleclick.net", "googlesyndication.com", "adsystem.com", "facebook.net", "connect.facebook.com", "hotjar.com", "clarity.ms", "segment.io", "segment.com", "amplitude.com", "fullstory.com", "sentry.io", "criteo.com", "taboola.com", "outbrain.com", ) def _should_block(request: Request) -> bool: if request.resource_type in _BLOCKED_RESOURCE_TYPES: return True return any(host in request.url for host in _BLOCKED_HOST_SUBSTRINGS) FrameParser = Callable[[object], dict[str, object] | None] class RateGate: """Enforces a minimum spacing between navigations across N scraper instances hitting the same site -- a one-time startup stagger isn't enough because retries after a crash (e.g. a 429) can still line back up and re-trigger the same rate limit. Share one instance across every scraper targeting that site. """ def __init__(self, min_interval: float) -> None: self._min_interval = min_interval self._lock = asyncio.Lock() self._last = 0.0 async def wait(self) -> None: async with self._lock: loop = asyncio.get_running_loop() now = loop.time() elapsed = now - self._last if elapsed < self._min_interval: await asyncio.sleep(self._min_interval - elapsed) self._last = loop.time() class SiteScraper: def __init__( self, url: str, parse_frame: FrameParser, *, user_agent: str | None = None, viewport: dict[str, int] | None = None, rate_gate: RateGate | None = None, context_idle_s: float = CONTEXT_IDLE_S, ) -> None: self._url = url self._parse_frame = parse_frame self._user_agent = user_agent self._viewport = viewport self._rate_gate = rate_gate self._context_idle_s = context_idle_s self._task: asyncio.Task[None] | None = None self._subscribers: set[asyncio.Queue[object]] = set() self._context: BrowserContext | None = None self._page: Page | None = None self._ready = asyncio.Event() self._idle_handle: asyncio.TimerHandle | None = None self._idle_task: asyncio.Task[None] | None = None self._idle_generation = 0 self.running = False def subscribe(self) -> asyncio.Queue[object]: queue: asyncio.Queue[object] = asyncio.Queue(maxsize=200) self._subscribers.add(queue) return queue def unsubscribe(self, queue: asyncio.Queue[object]) -> None: self._subscribers.discard(queue) async def start(self) -> None: if self.running: return self.running = True self._cancel_idle_recycle() self._ready.clear() self._task = asyncio.create_task(self._run()) try: await asyncio.wait_for(self._ready.wait(), READY_TIMEOUT_S) except TimeoutError: # The navigation is still in flight (or the site accepted the # page and never opened a socket). Keep running and let the retry # loop deal with it -- the caller gets a live scraper either way. logger.warning( "SiteScraper(%s) no socket after %.0fs, still running", self._url, READY_TIMEOUT_S, ) async def stop(self) -> None: task = self._task self.running = False self._ready.clear() if task is not None: task.cancel() with contextlib.suppress(asyncio.CancelledError): await task if self._task is task: self._task = None self._arm_idle_recycle() def _arm_idle_recycle(self) -> None: """Drop the warm context after the idle window, unless a new subscriber restarts the scraper first.""" self._cancel_idle_recycle() self._idle_generation += 1 generation = self._idle_generation def fire() -> None: if self.running or generation != self._idle_generation: return self._idle_task = asyncio.ensure_future(self._drop_context()) self._idle_handle = asyncio.get_running_loop().call_later(self._context_idle_s, fire) def _cancel_idle_recycle(self) -> None: if self._idle_handle is not None: self._idle_handle.cancel() self._idle_handle = None if self._idle_task is not None: self._idle_task.cancel() self._idle_task = None async def _drop_context(self) -> None: context, self._context = self._context, None self._page = None if context is None: return with contextlib.suppress(Exception): await context.close() async def _run(self) -> None: while self.running: try: page = await self._warm_page() if self._rate_gate is not None: await self._rate_gate.wait() response = await page.goto(self._url, wait_until="domcontentloaded", timeout=30000) if response is not None and not response.ok: # e.g. StockTitan 429s when several scrapers hit it at # once -- the DOM still "loads" (an error page), so # without this check we'd sit here forever with no # socket ever connecting instead of retrying. raise RuntimeError(f"{self._url} returned HTTP {response.status}") while self.running: await asyncio.sleep(1) except asyncio.CancelledError: raise except Exception: logger.exception("SiteScraper(%s) crashed, retrying in 10s", self._url) # A crash means the session degraded, so the retry must not # reuse it: a fresh context is the recycle. Retrying on the # same dead page would also keep the dead socket delivering. await self._drop_context() await asyncio.sleep(10) async def _warm_page(self) -> Page: """The cached page, or a new one built in its own context.""" if self._page is None: browser = await shared_browser.get_browser() self._context = await browser.new_context( user_agent=self._user_agent, viewport=cast(ViewportSize | None, self._viewport), ) page = await self._context.new_page() await page.route( "**/*", lambda route: route.abort() if _should_block(route.request) else route.continue_(), ) page.on("websocket", self._watch_socket) self._page = page return self._page def _watch_socket(self, ws: WebSocket) -> None: ws.on("framereceived", self._on_frame) self._ready.set() def _on_frame(self, payload: object) -> None: message = self._parse_frame(payload) if message is None: return for queue in list(self._subscribers): with contextlib.suppress(asyncio.QueueFull): queue.put_nowait(message)