File size: 5,848 Bytes
6eb6c4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
"""Live browser-engine probes: can this machine actually run each engine?



Config-free (pure Playwright) so both the doctor CLI and standalone scripts

can import it without pulling in application settings. Each probe launches the

engine exactly the way ``browser.manager`` does, renders a data: URL page,

evaluates JS, and takes a screenshot — a real end-to-end engine check.

"""
from __future__ import annotations

import asyncio
import os
import time
import uuid
from pathlib import Path
from typing import Any

REPO = Path(__file__).resolve().parents[3]  # backend/ (same depth as errors.py)
RUNTIME = REPO / ".browser-runtime"
BROWSERS = RUNTIME / "playwright-browsers"
TMP = RUNTIME / "tmp"
PROFILES = RUNTIME / "probe-profiles"

# The compatibility flags manager.py already scopes to Firefox.
MOZ_ENV = {
    "MOZ_DISABLE_CONTENT_SANDBOX": "1",
    "MOZ_DISABLE_GFX_SANDBOX": "1",
    "MOZ_DISABLE_RDD_SANDBOX": "1",
    "MOZ_DISABLE_SOCKET_PROCESS_SANDBOX": "1",
}

PROBE_HTML = (
    "data:text/html,<html><title>probe</title><body><h1 id=h>engine-probe-ok</h1></body></html>"
)


def prepare_runtime_env() -> None:
    """Mirror manager._prepare_runtime: redirect caches and temp into the app

    runtime root so probes exercise the same paths the server uses."""
    for directory in (BROWSERS, TMP, PROFILES):
        directory.mkdir(parents=True, exist_ok=True)
    os.environ["PLAYWRIGHT_BROWSERS_PATH"] = str(BROWSERS)
    for key in ("TEMP", "TMP", "TMPDIR"):
        os.environ[key] = str(TMP)


async def _exercise(page: Any, label: str) -> dict[str, Any]:
    """Prove the page really renders: JS eval + title + screenshot."""
    await page.goto(PROBE_HTML, wait_until="domcontentloaded", timeout=20000)
    heading = await page.inner_text("#h")
    title = await page.title()
    shot_path = RUNTIME / "screenshots" / f"probe_{label}_{int(time.time())}.png"
    shot_path.parent.mkdir(parents=True, exist_ok=True)
    await page.screenshot(path=str(shot_path), type="png")
    if heading.strip() != "engine-probe-ok":
        raise AssertionError(f"{label}: JS eval mismatch: {heading!r}")
    if title != "probe":
        raise AssertionError(f"{label}: title mismatch: {title!r}")
    return {
        "heading": heading,
        "title": title,
        "screenshot": str(shot_path),
        "screenshot_bytes": shot_path.stat().st_size,
    }


async def probe_engine(engine: str, headless: bool = True) -> dict[str, Any]:
    """Launch one engine (chromium | chrome | msedge | firefox) and exercise it.



    The verdict requires outliving the 4-second liveness window: this

    environment has shown Firefox aborting ~2.6s after launch (denied

    child-process spawn -> 0xC0000005), so a fast data-URL-only check would

    report a false PASS.

    """
    from playwright.async_api import async_playwright

    prepare_runtime_env()
    engine = engine.lower()
    label = {
        "chromium": "chromium (Playwright bundled)",
        "chrome": "chrome (installed Google Chrome)",
        "msedge": "msedge (installed Microsoft Edge)",
        "firefox": "firefox (Playwright bundled Mozilla engine)",
    }.get(engine, engine)
    pw = await async_playwright().start()
    profile = PROFILES / f"{engine}_{uuid.uuid4().hex[:8]}"
    started = time.monotonic()
    browser = None
    try:
        try:
            if engine == "firefox":
                browser = await pw.firefox.launch(
                    headless=headless, env={**os.environ, **MOZ_ENV}
                )
                context = await browser.new_context(viewport={"width": 1280, "height": 720})
                page = await context.new_page()
            else:
                options: dict[str, Any] = {
                    "user_data_dir": str(profile),
                    "headless": headless,
                    "viewport": {"width": 1280, "height": 720},
                }
                # Mirror manager._browser_engine exactly: the bundled engine
                # also goes through channel="chromium" (plain headless would
                # want the chromium_headless_shell build instead).
                options["channel"] = "chromium" if engine == "chromium" else engine
                context = await pw.chromium.launch_persistent_context(**options)
                browser = context.browser
                page = context.pages[0] if context.pages else await context.new_page()
            facts = await _exercise(page, engine)
            # Liveness window: the Firefox abort fires ~2.6s after launch.
            await asyncio.sleep(4)
            connected = getattr(browser, "is_connected", None)
            if callable(connected) and not connected():
                raise RuntimeError(
                    "browser process exited shortly after launch (child-process "
                    "spawn denied in this environment)"
                )
            version = browser.version if browser is not None else "unknown"
            return {
                "engine": label,
                "key": engine,
                "ok": True,
                "headless": headless,
                "version": version,
                "seconds": round(time.monotonic() - started, 1),
                **facts,
            }
        finally:
            if browser is not None:
                await browser.close()
    except Exception as exc:  # noqa: BLE001 — the probe reports, never raises
        return {
            "engine": label,
            "key": engine,
            "ok": False,
            "headless": headless,
            "seconds": round(time.monotonic() - started, 1),
            "error": f"{type(exc).__name__}: {exc}"[:1500],
        }
    finally:
        await pw.stop()