File size: 2,002 Bytes
ee446e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Single shared headless Chromium instance for all experimental site
scrapers (momo_scraper.py, titan_scraper.py). Each scraper previously
launched its own browser process just to hold one page open -- that's two
full Chromium processes for two WebSocket connections. One shared browser
process with a separate BrowserContext per scraper (so cookies/UA stay
isolated) cuts that in half.
"""

import asyncio

from playwright.async_api import Browser, Playwright, async_playwright

_playwright: Playwright | None = None
_browser: Browser | None = None
_lock = asyncio.Lock()


async def get_browser() -> Browser:
    global _playwright, _browser
    async with _lock:
        if _browser is None:
            _playwright = await async_playwright().start()
            _browser = await _playwright.chromium.launch(
                headless=True,
                args=[
                    "--disable-blink-features=AutomationControlled",
                    # Trims Chromium overhead we don't need for a headless
                    # tab that only exists to keep one WebSocket open --
                    # no GPU/compositor, no background services, no
                    # first-run/updater/telemetry work competing for CPU.
                    "--disable-gpu",
                    "--disable-dev-shm-usage",
                    "--disable-extensions",
                    "--disable-background-networking",
                    "--disable-sync",
                    "--disable-translate",
                    "--disable-default-apps",
                    "--metrics-recording-only",
                    "--mute-audio",
                    "--no-first-run",
                ],
            )
        return _browser


async def shutdown() -> None:
    global _playwright, _browser
    async with _lock:
        if _browser is not None:
            await _browser.close()
            _browser = None
        if _playwright is not None:
            await _playwright.stop()
            _playwright = None