Spaces:
Paused
Paused
Peng Ding commited on
Commit ·
16780dd
1
Parent(s): 70d4363
feat: real browser page count via CDP /json endpoint
Browse files- Add _count_cdp_pages() to query actual open page targets from browser
- worker_stats() now includes browser_pages (real count from CDP)
- RemoteWorker.start() verifies connectivity by creating a test page
- Prometheus metrics: add veilrender_worker_browser_pages gauge
- /stats JSON: workers array includes browser_pages field
- worker_stats() and dependent functions are now async
src/veilrender/browser.py
CHANGED
|
@@ -13,6 +13,7 @@ import subprocess
|
|
| 13 |
import urllib.request
|
| 14 |
from collections.abc import AsyncIterator, Callable
|
| 15 |
from contextlib import asynccontextmanager
|
|
|
|
| 16 |
|
| 17 |
from cloakbrowser import ensure_binary, get_default_stealth_args
|
| 18 |
from playwright.async_api import Browser, BrowserContext, Page, async_playwright
|
|
@@ -25,12 +26,23 @@ logger = logging.getLogger(__name__)
|
|
| 25 |
CDP_PORT = 9222
|
| 26 |
|
| 27 |
|
| 28 |
-
def _fetch_json(url: str, timeout: int = 2) ->
|
| 29 |
"""Fetch and parse JSON from a URL (blocking)."""
|
| 30 |
resp = urllib.request.urlopen(url, timeout=timeout)
|
| 31 |
return json.loads(resp.read())
|
| 32 |
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
def _ws_to_http(endpoint: str) -> str:
|
| 35 |
"""Convert a ws(s):// URL to http(s):// for CDP HTTP API."""
|
| 36 |
if endpoint.startswith("wss://"):
|
|
@@ -107,6 +119,10 @@ class _BaseWorker:
|
|
| 107 |
def available(self) -> int:
|
| 108 |
return self._semaphore._value
|
| 109 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
@asynccontextmanager
|
| 111 |
async def get_page(
|
| 112 |
self,
|
|
@@ -247,6 +263,11 @@ class LocalWorker(_BaseWorker):
|
|
| 247 |
logger.debug("Failed to get CDP WebSocket URL", exc_info=True)
|
| 248 |
return f"ws://127.0.0.1:{self.cdp_port}"
|
| 249 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
@property
|
| 251 |
def is_alive(self) -> bool:
|
| 252 |
return self._browser is not None and self._browser.is_connected()
|
|
@@ -271,8 +292,12 @@ class RemoteWorker(_BaseWorker):
|
|
| 271 |
self._playwright = await async_playwright().start()
|
| 272 |
resolved = _resolve_to_ip(self.endpoint)
|
| 273 |
self._browser = await self._playwright.chromium.connect_over_cdp(resolved)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 274 |
self.healthy = True
|
| 275 |
-
logger.info("Connected to remote browser at %s", self.endpoint)
|
| 276 |
|
| 277 |
async def stop(self) -> None:
|
| 278 |
self.healthy = False
|
|
@@ -297,11 +322,15 @@ class RemoteWorker(_BaseWorker):
|
|
| 297 |
assert self._browser is not None
|
| 298 |
return self._browser
|
| 299 |
|
|
|
|
|
|
|
|
|
|
| 300 |
async def get_cdp_url(self) -> str | None:
|
| 301 |
await self.ensure_ready()
|
| 302 |
-
http_endpoint = _ws_to_http(_resolve_to_ip(self.endpoint))
|
| 303 |
try:
|
| 304 |
-
data = await asyncio.to_thread(
|
|
|
|
|
|
|
| 305 |
ws_url = data.get("webSocketDebuggerUrl")
|
| 306 |
if ws_url:
|
| 307 |
return ws_url
|
|
@@ -311,6 +340,9 @@ class RemoteWorker(_BaseWorker):
|
|
| 311 |
return self.endpoint
|
| 312 |
return None
|
| 313 |
|
|
|
|
|
|
|
|
|
|
| 314 |
@property
|
| 315 |
def is_alive(self) -> bool:
|
| 316 |
return self._browser is not None and self._browser.is_connected()
|
|
@@ -414,15 +446,17 @@ class BrowserManager:
|
|
| 414 |
def total_capacity(self) -> int:
|
| 415 |
return sum(w.max_concurrent for w in self._workers if w.healthy)
|
| 416 |
|
| 417 |
-
def worker_stats(self) -> list[dict]:
|
| 418 |
result = []
|
| 419 |
for i, w in enumerate(self._workers):
|
|
|
|
| 420 |
result.append(
|
| 421 |
{
|
| 422 |
"index": i,
|
| 423 |
"endpoint": w.endpoint,
|
| 424 |
"healthy": w.healthy,
|
| 425 |
"active": w.active,
|
|
|
|
| 426 |
"max_concurrent": w.max_concurrent,
|
| 427 |
"is_alive": w.is_alive,
|
| 428 |
}
|
|
|
|
| 13 |
import urllib.request
|
| 14 |
from collections.abc import AsyncIterator, Callable
|
| 15 |
from contextlib import asynccontextmanager
|
| 16 |
+
from typing import Any
|
| 17 |
|
| 18 |
from cloakbrowser import ensure_binary, get_default_stealth_args
|
| 19 |
from playwright.async_api import Browser, BrowserContext, Page, async_playwright
|
|
|
|
| 26 |
CDP_PORT = 9222
|
| 27 |
|
| 28 |
|
| 29 |
+
def _fetch_json(url: str, timeout: int = 2) -> Any:
|
| 30 |
"""Fetch and parse JSON from a URL (blocking)."""
|
| 31 |
resp = urllib.request.urlopen(url, timeout=timeout)
|
| 32 |
return json.loads(resp.read())
|
| 33 |
|
| 34 |
|
| 35 |
+
def _count_cdp_pages(http_base: str, timeout: int = 2) -> int:
|
| 36 |
+
"""Count open page targets via CDP /json endpoint."""
|
| 37 |
+
try:
|
| 38 |
+
targets = _fetch_json(f"{http_base}/json", timeout)
|
| 39 |
+
if isinstance(targets, list):
|
| 40 |
+
return sum(1 for t in targets if t.get("type") == "page")
|
| 41 |
+
except Exception:
|
| 42 |
+
pass
|
| 43 |
+
return -1
|
| 44 |
+
|
| 45 |
+
|
| 46 |
def _ws_to_http(endpoint: str) -> str:
|
| 47 |
"""Convert a ws(s):// URL to http(s):// for CDP HTTP API."""
|
| 48 |
if endpoint.startswith("wss://"):
|
|
|
|
| 119 |
def available(self) -> int:
|
| 120 |
return self._semaphore._value
|
| 121 |
|
| 122 |
+
async def browser_page_count(self) -> int:
|
| 123 |
+
"""Query actual open page count from the browser via CDP."""
|
| 124 |
+
return -1
|
| 125 |
+
|
| 126 |
@asynccontextmanager
|
| 127 |
async def get_page(
|
| 128 |
self,
|
|
|
|
| 263 |
logger.debug("Failed to get CDP WebSocket URL", exc_info=True)
|
| 264 |
return f"ws://127.0.0.1:{self.cdp_port}"
|
| 265 |
|
| 266 |
+
async def browser_page_count(self) -> int:
|
| 267 |
+
return await asyncio.to_thread(
|
| 268 |
+
_count_cdp_pages, f"http://127.0.0.1:{self.cdp_port}"
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
@property
|
| 272 |
def is_alive(self) -> bool:
|
| 273 |
return self._browser is not None and self._browser.is_connected()
|
|
|
|
| 292 |
self._playwright = await async_playwright().start()
|
| 293 |
resolved = _resolve_to_ip(self.endpoint)
|
| 294 |
self._browser = await self._playwright.chromium.connect_over_cdp(resolved)
|
| 295 |
+
ctx = await self._browser.new_context()
|
| 296 |
+
page = await ctx.new_page()
|
| 297 |
+
await page.close()
|
| 298 |
+
await ctx.close()
|
| 299 |
self.healthy = True
|
| 300 |
+
logger.info("Connected to remote browser at %s (verified)", self.endpoint)
|
| 301 |
|
| 302 |
async def stop(self) -> None:
|
| 303 |
self.healthy = False
|
|
|
|
| 322 |
assert self._browser is not None
|
| 323 |
return self._browser
|
| 324 |
|
| 325 |
+
def _http_base(self) -> str:
|
| 326 |
+
return _ws_to_http(_resolve_to_ip(self.endpoint))
|
| 327 |
+
|
| 328 |
async def get_cdp_url(self) -> str | None:
|
| 329 |
await self.ensure_ready()
|
|
|
|
| 330 |
try:
|
| 331 |
+
data = await asyncio.to_thread(
|
| 332 |
+
_fetch_json, f"{self._http_base()}/json/version"
|
| 333 |
+
)
|
| 334 |
ws_url = data.get("webSocketDebuggerUrl")
|
| 335 |
if ws_url:
|
| 336 |
return ws_url
|
|
|
|
| 340 |
return self.endpoint
|
| 341 |
return None
|
| 342 |
|
| 343 |
+
async def browser_page_count(self) -> int:
|
| 344 |
+
return await asyncio.to_thread(_count_cdp_pages, self._http_base())
|
| 345 |
+
|
| 346 |
@property
|
| 347 |
def is_alive(self) -> bool:
|
| 348 |
return self._browser is not None and self._browser.is_connected()
|
|
|
|
| 446 |
def total_capacity(self) -> int:
|
| 447 |
return sum(w.max_concurrent for w in self._workers if w.healthy)
|
| 448 |
|
| 449 |
+
async def worker_stats(self) -> list[dict]:
|
| 450 |
result = []
|
| 451 |
for i, w in enumerate(self._workers):
|
| 452 |
+
browser_pages = await w.browser_page_count() if w.healthy else -1
|
| 453 |
result.append(
|
| 454 |
{
|
| 455 |
"index": i,
|
| 456 |
"endpoint": w.endpoint,
|
| 457 |
"healthy": w.healthy,
|
| 458 |
"active": w.active,
|
| 459 |
+
"browser_pages": browser_pages,
|
| 460 |
"max_concurrent": w.max_concurrent,
|
| 461 |
"is_alive": w.is_alive,
|
| 462 |
}
|
src/veilrender/routes/dashboard.py
CHANGED
|
@@ -28,7 +28,7 @@ _RING_RADIUS = 40
|
|
| 28 |
_RING_CIRCUMFERENCE = 2 * math.pi * _RING_RADIUS
|
| 29 |
|
| 30 |
|
| 31 |
-
def _stats_json() -> dict:
|
| 32 |
"""Collect all dashboard data as a dict."""
|
| 33 |
active = browser_manager.active_pages
|
| 34 |
max_conc = browser_manager.total_capacity
|
|
@@ -45,7 +45,7 @@ def _stats_json() -> dict:
|
|
| 45 |
"/render": _ep_dict(stats.render),
|
| 46 |
"/screenshot": _ep_dict(stats.screenshot),
|
| 47 |
},
|
| 48 |
-
"workers": browser_manager.worker_stats(),
|
| 49 |
}
|
| 50 |
|
| 51 |
|
|
@@ -105,9 +105,9 @@ def _capacity_ring(active: int, max_conc: int, utilization: float) -> str:
|
|
| 105 |
</svg>"""
|
| 106 |
|
| 107 |
|
| 108 |
-
def _build_html() -> str:
|
| 109 |
"""Build the dashboard HTML."""
|
| 110 |
-
d = _stats_json()
|
| 111 |
browser_label = "alive" if d["browser_alive"] else "dead"
|
| 112 |
dot_cls = "dot-on" if d["browser_alive"] else "dot-off"
|
| 113 |
fail_cls = "c-err" if d["total_failures"] > 0 else "c-ok"
|
|
@@ -590,7 +590,7 @@ def register(app: App) -> None:
|
|
| 590 |
@app.get("/")
|
| 591 |
async def dashboard(request: Request) -> Response:
|
| 592 |
return Response(
|
| 593 |
-
body=_build_html(),
|
| 594 |
status_code=200,
|
| 595 |
content_type="text/html; charset=utf-8",
|
| 596 |
)
|
|
@@ -598,7 +598,7 @@ def register(app: App) -> None:
|
|
| 598 |
@app.get("/stats")
|
| 599 |
async def stats_api(request: Request) -> Response:
|
| 600 |
return Response(
|
| 601 |
-
body=json.dumps(_stats_json()),
|
| 602 |
status_code=200,
|
| 603 |
content_type="application/json",
|
| 604 |
headers={"Cache-Control": "no-store"},
|
|
|
|
| 28 |
_RING_CIRCUMFERENCE = 2 * math.pi * _RING_RADIUS
|
| 29 |
|
| 30 |
|
| 31 |
+
async def _stats_json() -> dict:
|
| 32 |
"""Collect all dashboard data as a dict."""
|
| 33 |
active = browser_manager.active_pages
|
| 34 |
max_conc = browser_manager.total_capacity
|
|
|
|
| 45 |
"/render": _ep_dict(stats.render),
|
| 46 |
"/screenshot": _ep_dict(stats.screenshot),
|
| 47 |
},
|
| 48 |
+
"workers": await browser_manager.worker_stats(),
|
| 49 |
}
|
| 50 |
|
| 51 |
|
|
|
|
| 105 |
</svg>"""
|
| 106 |
|
| 107 |
|
| 108 |
+
async def _build_html() -> str:
|
| 109 |
"""Build the dashboard HTML."""
|
| 110 |
+
d = await _stats_json()
|
| 111 |
browser_label = "alive" if d["browser_alive"] else "dead"
|
| 112 |
dot_cls = "dot-on" if d["browser_alive"] else "dot-off"
|
| 113 |
fail_cls = "c-err" if d["total_failures"] > 0 else "c-ok"
|
|
|
|
| 590 |
@app.get("/")
|
| 591 |
async def dashboard(request: Request) -> Response:
|
| 592 |
return Response(
|
| 593 |
+
body=await _build_html(),
|
| 594 |
status_code=200,
|
| 595 |
content_type="text/html; charset=utf-8",
|
| 596 |
)
|
|
|
|
| 598 |
@app.get("/stats")
|
| 599 |
async def stats_api(request: Request) -> Response:
|
| 600 |
return Response(
|
| 601 |
+
body=json.dumps(await _stats_json()),
|
| 602 |
status_code=200,
|
| 603 |
content_type="application/json",
|
| 604 |
headers={"Cache-Control": "no-store"},
|
src/veilrender/routes/metrics.py
CHANGED
|
@@ -10,7 +10,7 @@ _CONTENT_TYPE = "text/plain; version=0.0.4; charset=utf-8"
|
|
| 10 |
_ENDPOINTS = (("/render", stats.render), ("/screenshot", stats.screenshot))
|
| 11 |
|
| 12 |
|
| 13 |
-
def _build_metrics() -> str:
|
| 14 |
"""Build Prometheus exposition text."""
|
| 15 |
active = browser_manager.active_pages
|
| 16 |
alive = 1 if browser_manager.is_browser_alive else 0
|
|
@@ -39,7 +39,7 @@ def _build_metrics() -> str:
|
|
| 39 |
)
|
| 40 |
|
| 41 |
# Per-worker gauges
|
| 42 |
-
workers = browser_manager.worker_stats()
|
| 43 |
if len(workers) > 1 or (workers and workers[0]["endpoint"] != "local"):
|
| 44 |
lines = [
|
| 45 |
"# HELP veilrender_worker_healthy Whether a worker is healthy.\n",
|
|
@@ -53,7 +53,7 @@ def _build_metrics() -> str:
|
|
| 53 |
parts.append("".join(lines))
|
| 54 |
|
| 55 |
lines = [
|
| 56 |
-
"# HELP veilrender_worker_active_pages Active pages per worker.\n",
|
| 57 |
"# TYPE veilrender_worker_active_pages gauge\n",
|
| 58 |
]
|
| 59 |
for ws in workers:
|
|
@@ -63,6 +63,19 @@ def _build_metrics() -> str:
|
|
| 63 |
)
|
| 64 |
parts.append("".join(lines))
|
| 65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
# Counters — requests
|
| 67 |
lines = [
|
| 68 |
"# HELP veilrender_requests_total Total requests by endpoint and status.\n",
|
|
@@ -121,7 +134,7 @@ def register(app: App) -> None:
|
|
| 121 |
@app.get("/metrics")
|
| 122 |
async def metrics(request: Request) -> Response:
|
| 123 |
return Response(
|
| 124 |
-
body=_build_metrics(),
|
| 125 |
status_code=200,
|
| 126 |
content_type=_CONTENT_TYPE,
|
| 127 |
headers={"Cache-Control": "no-store"},
|
|
|
|
| 10 |
_ENDPOINTS = (("/render", stats.render), ("/screenshot", stats.screenshot))
|
| 11 |
|
| 12 |
|
| 13 |
+
async def _build_metrics() -> str:
|
| 14 |
"""Build Prometheus exposition text."""
|
| 15 |
active = browser_manager.active_pages
|
| 16 |
alive = 1 if browser_manager.is_browser_alive else 0
|
|
|
|
| 39 |
)
|
| 40 |
|
| 41 |
# Per-worker gauges
|
| 42 |
+
workers = await browser_manager.worker_stats()
|
| 43 |
if len(workers) > 1 or (workers and workers[0]["endpoint"] != "local"):
|
| 44 |
lines = [
|
| 45 |
"# HELP veilrender_worker_healthy Whether a worker is healthy.\n",
|
|
|
|
| 53 |
parts.append("".join(lines))
|
| 54 |
|
| 55 |
lines = [
|
| 56 |
+
"# HELP veilrender_worker_active_pages Active pages per worker (semaphore).\n",
|
| 57 |
"# TYPE veilrender_worker_active_pages gauge\n",
|
| 58 |
]
|
| 59 |
for ws in workers:
|
|
|
|
| 63 |
)
|
| 64 |
parts.append("".join(lines))
|
| 65 |
|
| 66 |
+
lines = [
|
| 67 |
+
"# HELP veilrender_worker_browser_pages Actual open pages in browser.\n",
|
| 68 |
+
"# TYPE veilrender_worker_browser_pages gauge\n",
|
| 69 |
+
]
|
| 70 |
+
for ws in workers:
|
| 71 |
+
bp = ws.get("browser_pages", -1)
|
| 72 |
+
if bp >= 0:
|
| 73 |
+
lines.append(
|
| 74 |
+
f'veilrender_worker_browser_pages{{worker="{ws["index"]}",endpoint="{ws["endpoint"]}"}} '
|
| 75 |
+
f"{bp}\n"
|
| 76 |
+
)
|
| 77 |
+
parts.append("".join(lines))
|
| 78 |
+
|
| 79 |
# Counters — requests
|
| 80 |
lines = [
|
| 81 |
"# HELP veilrender_requests_total Total requests by endpoint and status.\n",
|
|
|
|
| 134 |
@app.get("/metrics")
|
| 135 |
async def metrics(request: Request) -> Response:
|
| 136 |
return Response(
|
| 137 |
+
body=await _build_metrics(),
|
| 138 |
status_code=200,
|
| 139 |
content_type=_CONTENT_TYPE,
|
| 140 |
headers={"Cache-Control": "no-store"},
|