Repository navigation
fix(browsers): wait for persistent profiles to be released before relaunch #2581
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
|
@@ -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. | ||
|
|
@@ -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]]] = [] | ||
|
|
@@ -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) | ||
|
|
@@ -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() | ||
| try: | ||
| return await self._open_page(page_id, plugin, proxy_info, profile) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The lock also covers the pre-page-create hooks and |
||
| 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: | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
|
|
@@ -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 | ||
|
|
@@ -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: | ||
|
|
||
There was a problem hiding this comment.
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_timeouthere, and_get_profile_browser()andnew_page()then get one each, so a singlenew_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.