Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
155 changes: 130 additions & 25 deletions src/crawlee/browsers/_browser_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@
import asyncio
import itertools
from collections import defaultdict
from dataclasses import dataclass, field
from datetime import timedelta
from logging import getLogger
from typing import TYPE_CHECKING, Any
from weakref import WeakValueDictionary

from async_timeout import timeout as async_timeout

from crawlee._utils.context import ensure_context
from crawlee._utils.crypto import crypto_random_object_id
from crawlee._utils.docs import docs_group
Expand All @@ -30,6 +33,16 @@
logger = getLogger(__name__)


@dataclass
class _PersistentProfile:
"""Serialize browser ownership changes for one user data directory."""

lock: asyncio.Lock = field(default_factory=asyncio.Lock)
page_closed: asyncio.Event = field(default_factory=asyncio.Event)
plugin: BrowserPlugin | None = None
browser: BrowserController | None = None


@docs_group('Browser management')
class BrowserPool:
"""Manage a pool of browsers and pages, handling their lifecycle and resource allocation.
Expand Down Expand Up @@ -101,6 +114,7 @@ def __init__(
self._retire_browser_after_page_count = retire_browser_after_page_count
self._pages = WeakValueDictionary[str, CrawleePage]() # Track the pages in the pool
self._plugins_cycle = itertools.cycle(self._plugins) # Cycle through the plugins
self._persistent_profiles: dict[Path, _PersistentProfile] = {}

# Hooks for custom behavior at different stages of the browser and page lifecycles.
self._pre_launch_hooks: list[Callable[[str, BrowserPlugin], Awaitable[None]]] = []
Expand Down Expand Up @@ -247,6 +261,7 @@ async def __aexit__(
await browser.close(force=True)
self._active_browsers.clear()
self._inactive_browsers.clear()
self._persistent_profiles.clear()

for plugin in self._plugins:
await plugin.__aexit__(exc_type, exc_value, exc_traceback)
Expand Down Expand Up @@ -308,50 +323,121 @@ async def _get_new_page(
Select a browser with available capacity or launch a new one if needed. Create a new page in the selected
browser with the provided proxy settings.
"""
timeout = self._operation_timeout.total_seconds()
browser_controller = self._pick_browser_with_free_capacity(plugin)
profile_path = plugin._persistent_profile if isinstance(plugin, PlaywrightBrowserPlugin) else None # noqa: SLF001
profile = None
if profile_path is not None:
profile = self._persistent_profiles.get(profile_path)
if profile is None:
profile = self._persistent_profiles[profile_path] = _PersistentProfile()

try:
if not browser_controller:
browser_controller = await asyncio.wait_for(self._launch_new_browser(page_id, plugin), timeout)
browser_new_context_options = dict(plugin.browser_new_context_options)

await self._execute_hooks(
self._pre_page_create_hooks, page_id, browser_controller, browser_new_context_options, proxy_info
)

page = await asyncio.wait_for(
browser_controller.new_page(
browser_new_context_options=browser_new_context_options,
proxy_info=proxy_info,
),
timeout,
)
if profile is None:
crawlee_page, browser_controller = await self._open_page(page_id, plugin, proxy_info, None)
else:
crawlee_page, browser_controller = await self._open_profile_page(page_id, plugin, proxy_info, profile)
except asyncio.TimeoutError as exc:
raise TimeoutError(f'Creating a new page with plugin {plugin} timed out.') from exc
except RuntimeError as exc:
raise RuntimeError('Browser pool is not initialized.') from exc

await self._execute_hooks(self._post_page_create_hooks, crawlee_page, browser_controller)
self._override_page_close(crawlee_page, browser_controller, profile)
return crawlee_page

async def _open_profile_page(
self,
page_id: str,
plugin: BrowserPlugin,
proxy_info: ProxyInfo | None,
profile: _PersistentProfile,
) -> tuple[CrawleePage, BrowserController]:
"""Reserve the profile while selecting its owner and opening the page."""
async with async_timeout(self._operation_timeout.total_seconds()):
await profile.lock.acquire()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The lock wait gets its own operation_timeout here, and _get_profile_browser() and new_page() then get one each, so a single new_page() call can take up to three times the timeout. I think the lock and the wait for the previous browser could share one timeout, as the description says.

try:
return await self._open_page(page_id, plugin, proxy_info, profile)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The lock also covers the pre-page-create hooks and new_page(), so all pages on the profile open one by one, not just browser launches. Maybe it's enough to hold it while waiting for the previous browser and launching the next one, since the controller already creates the context under its own lock.

finally:
profile.lock.release()

async def _open_page(
self,
page_id: str,
plugin: BrowserPlugin,
proxy_info: ProxyInfo | None,
profile: _PersistentProfile | None,
) -> tuple[CrawleePage, BrowserController]:
"""Open a page and reserve its profile until the browser is retired and closed."""
timeout = self._operation_timeout.total_seconds()
if profile is None:
browser_controller = self._pick_browser_with_free_capacity(plugin)
if browser_controller is None:
browser_controller = await asyncio.wait_for(self._launch_new_browser(page_id, plugin), timeout)
else:
browser_controller = await asyncio.wait_for(self._get_profile_browser(page_id, plugin, profile), timeout)

browser_new_context_options = dict(plugin.browser_new_context_options)
await self._execute_hooks(
self._pre_page_create_hooks, page_id, browser_controller, browser_new_context_options, proxy_info
)
page = await asyncio.wait_for(
browser_controller.new_page(browser_new_context_options=browser_new_context_options, proxy_info=proxy_info),
timeout,
)
if profile is not None:
page.on('close', lambda _: profile.page_closed.set())

if browser_controller.total_opened_pages >= self._retire_browser_after_page_count:
self._retire_browser(browser_controller)

crawlee_page = CrawleePage(id=page_id, page=page, browser_type=plugin.browser_type)
self._pages[page_id] = crawlee_page
self._total_pages_count += 1
return crawlee_page, browser_controller

async def _get_profile_browser(
self, page_id: str, plugin: BrowserPlugin, profile: _PersistentProfile
) -> BrowserController:
"""Reuse an available profile owner or wait until the previous owner releases its directory."""
browser = profile.browser
if browser is not None:
while True:
if browser in self._active_browsers and profile.plugin is plugin:
if browser.has_free_capacity:
return browser
elif not browser.pages and not browser.is_opening_pages:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A browser also gets into the inactive list after 'browser_inactive_threshold' without new pages, even with a page still open. Then the next page waits for that page to close and restarts the browser, though it was never retired.

self._retire_browser(browser)
await self._close_profile_browser(browser, profile)
break

profile.page_closed.clear()
await profile.page_closed.wait()

browser = await self._launch_new_browser(page_id, plugin)
profile.browser = browser
profile.plugin = plugin
return browser

await self._execute_hooks(self._post_page_create_hooks, crawlee_page, browser_controller)
async def _close_profile_browser(self, browser: BrowserController, profile: _PersistentProfile) -> None:
"""Release profile ownership after the previous browser finishes closing."""
await browser.close()
self._inactive_browsers.remove(browser)
profile.browser = None
profile.plugin = None

self._override_page_close(crawlee_page, browser_controller)

return crawlee_page
def _profile_for_browser(self, browser: BrowserController) -> _PersistentProfile | None:
return next((profile for profile in self._persistent_profiles.values() if profile.browser is browser), None)

def _pick_browser_with_free_capacity(
self,
browser_plugin: BrowserPlugin,
) -> BrowserController | None:
"""Pick a browser with free capacity that matches the specified plugin."""
for browser in self._active_browsers:
if browser.has_free_capacity and browser.AUTOMATION_LIBRARY == browser_plugin.AUTOMATION_LIBRARY:
if (
browser.has_free_capacity
and browser.AUTOMATION_LIBRARY == browser_plugin.AUTOMATION_LIBRARY
and self._profile_for_browser(browser) is None
):
return browser

return None
Expand Down Expand Up @@ -384,23 +470,40 @@ async def _launch_new_browser(self, page_id: str, plugin: BrowserPlugin) -> Brow
def _identify_inactive_browsers(self) -> None:
"""Identify inactive browsers and move them to the inactive list if their idle time exceeds the threshold."""
for browser in list(self._active_browsers):
if browser.idle_time >= self._browser_inactive_threshold and not browser.is_opening_pages:
profile = self._profile_for_browser(browser)
if (
browser.idle_time >= self._browser_inactive_threshold
and not browser.is_opening_pages
and (profile is None or not profile.lock.locked())
):
self._active_browsers.remove(browser)
self._inactive_browsers.append(browser)

async def _close_inactive_browsers(self) -> None:
"""Close the browsers that have no active pages and have been idle for a certain period."""
for browser in list(self._inactive_browsers):
if not browser.pages and not browser.is_opening_pages:
if browser not in self._inactive_browsers or browser.pages or browser.is_opening_pages:
continue
profile = self._profile_for_browser(browser)
if profile is None:
await browser.close()
self._inactive_browsers.remove(browser)
elif not profile.lock.locked():
async with profile.lock:
if profile.browser is browser and not browser.pages and not browser.is_opening_pages:
await self._close_profile_browser(browser, profile)

async def _execute_hooks(self, hooks: list[Callable[..., Awaitable[None]]], *args: Any) -> None:
"""Execute the provided hooks with the given arguments."""
for hook in hooks:
await hook(*args)

def _override_page_close(self, crawlee_page: CrawleePage, browser_controller: BrowserController) -> None:
def _override_page_close(
self,
crawlee_page: CrawleePage,
browser_controller: BrowserController,
profile: _PersistentProfile | None = None,
) -> None:
"""Override the page's close method to execute pre and post close hooks and bound the close itself.

A browser can acknowledge the close and then never destroy the page, so neither the close call nor the page's
Expand All @@ -421,6 +524,8 @@ async def close_page(*args: Any, **kwargs: Any) -> None:
)
browser_controller.register_page_closed(crawlee_page.page)
self._retire_browser(browser_controller)
if profile is not None:
profile.page_closed.set()

async def close_with_hooks(*args: Any, **kwargs: Any) -> None:
try:
Expand Down
9 changes: 8 additions & 1 deletion src/crawlee/browsers/_playwright_browser_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

from logging import getLogger
from pathlib import Path
from typing import TYPE_CHECKING, Any

from playwright.async_api import Playwright, async_playwright
Expand All @@ -17,7 +18,6 @@

if TYPE_CHECKING:
from collections.abc import Mapping
from pathlib import Path
from types import TracebackType

from playwright.async_api._generated import Browser
Expand Down Expand Up @@ -112,6 +112,13 @@ def __init__(

self._fingerprint_generator = fingerprint_generator

@property
def _persistent_profile(self) -> Path | None:
"""Return the explicit directory shared by this plugin's persistent browsers."""
if not self._use_incognito_pages and self._user_data_dir:
return Path(self._user_data_dir).resolve()
return None

@property
@override
def active(self) -> bool:
Expand Down
48 changes: 48 additions & 0 deletions tests/integration/browsers/test_browser_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

if TYPE_CHECKING:
from collections.abc import Mapping
from pathlib import Path
from typing import Any

from playwright.async_api import BrowserContext
Expand Down Expand Up @@ -263,6 +264,53 @@ async def test_browser_pool_retire_browser_after_page_count(
assert first_browser is not second_browser


async def test_browser_pool_retires_and_reuses_persistent_profile(tmp_path: Path, server_url: URL) -> None:
"""Pages keep loading when their persistent browser is retired and replaced."""
async with BrowserPool.with_default_plugin(
user_data_dir=tmp_path / 'profile',
headless=True,
browser_launch_options={'channel': 'chromium'},
retire_browser_after_page_count=2,
close_inactive_browsers_interval=timedelta(minutes=1),
) as browser_pool:
contexts: list[BrowserContext] = []
for _ in range(6):
page = (await browser_pool.new_page()).page
contexts.append(page.context)
await page.goto(str(server_url))
await page.close()

assert contexts[0] is contexts[1]
assert contexts[2] is contexts[3]
assert contexts[4] is contexts[5]
assert len(set(contexts)) == 3


async def test_browser_pool_waits_for_open_page_in_retired_persistent_profile(
tmp_path: Path, server_url: URL, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Allocation can time out without destroying a page or leaving the profile stuck."""
async with BrowserPool.with_default_plugin(
user_data_dir=tmp_path / 'profile',
headless=True,
browser_launch_options={'channel': 'chromium'},
retire_browser_after_page_count=1,
) as browser_pool:
first = (await browser_pool.new_page()).page
await first.goto(str(server_url))
with monkeypatch.context() as patch:
patch.setattr(browser_pool, '_operation_timeout', timedelta(milliseconds=100))
with pytest.raises(TimeoutError, match='Creating a new page'):
await browser_pool.new_page()

assert not first.is_closed()
await first.close()
second = (await browser_pool.new_page()).page
await second.goto(str(server_url))
assert second.context is not first.context
await second.close()


async def test_pre_page_create_hook_is_called() -> None:
call_mock = AsyncMock()

Expand Down