diff --git a/docs/03_concepts/code_examples/session_management/multi_sessions_http.py b/docs/03_concepts/code_examples/session_management/multi_sessions_http.py index 73f5734ff4..c4076feb21 100644 --- a/docs/03_concepts/code_examples/session_management/multi_sessions_http.py +++ b/docs/03_concepts/code_examples/session_management/multi_sessions_http.py @@ -1,4 +1,5 @@ import asyncio +from contextlib import suppress from datetime import timedelta from crawlee import ConcurrencySettings, Request @@ -50,9 +51,13 @@ async def error_processing(context: BasicCrawlingContext, error: Exception) -> N ) async with session_pool: - # The pool creates sessions on demand, so create them before binding - # the first requests to them, for example for authentication - sessions = [await session_pool.get_session() for _ in range(10)] + # Add the sessions before binding the first requests to them, + # for example one session per authenticated profile + profile_ids = [f'profile-{i}' for i in range(10)] + for profile_id in profile_ids: + # A resumed run restores the usable sessions from the persisted state + with suppress(ValueError): + await session_pool.add_session({'id': profile_id}) # Create a pool of requests bound to their respective sessions # Use `always_enqueue=True` if session initialization happens on a non-unique @@ -61,10 +66,10 @@ async def error_processing(context: BasicCrawlingContext, error: Exception) -> N Request.from_url( 'https://example.org/', label='session_init', - session_id=session.id, + session_id=profile_id, use_extended_unique_key=True, ) - for session in sessions + for profile_id in profile_ids ] await crawler.run(init_requests) diff --git a/docs/06_upgrading/upgrading_to_v2.md b/docs/06_upgrading/upgrading_to_v2.md index e0b980b763..8213d49924 100644 --- a/docs/06_upgrading/upgrading_to_v2.md +++ b/docs/06_upgrading/upgrading_to_v2.md @@ -803,7 +803,7 @@ Session state, including the persisted session pool state, has a new `retired` f ### The session pool creates sessions on demand -`SessionPool` no longer fills itself up to `max_pool_size` when you enter it. `get_session()` creates a new session while the pool has fewer than `max_pool_size` sessions, and picks a random one after that. `get_session_by_id()` no longer creates sessions, so a request bound by `session_id` to a session that the pool hasn't created yet fails with a `RequestCollisionError`. To bind requests to sessions up front, create the sessions with `get_session()` before you run the crawler. +`SessionPool` no longer fills itself up to `max_pool_size` when you enter it. `get_session()` creates a new session while the pool has fewer than `max_pool_size` sessions, and picks a random one after that. `get_session()` with a session ID doesn't create sessions, so a request bound by `session_id` to a session that the pool hasn't created yet fails with a `RequestCollisionError`. To bind requests to sessions up front, add the sessions with `add_session()` before you run the crawler. ### Sessions carry their proxy @@ -895,6 +895,48 @@ def create_session(options: SessionOptions) -> Session: session_pool = SessionPool(create_session_function=create_session) ``` +### `get_session()` takes the session ID + +`SessionPool.get_session_by_id()` is removed. Pass the ID to `get_session()` instead. With an ID, `get_session()` returns the usable session with this ID or `None`, and doesn't create a session. + +### `add_session()` is async and takes session options + +`SessionPool.add_session()` is a coroutine and returns the added session. Besides a `Session`, it takes the options of a new session and builds the session from them the same way as the sessions the pool creates: merged over `create_session_settings`, with a proxy from `proxy_configuration`, by `create_session_function`. A passed `Session` is added as it is. + +When the pool already holds a usable session with the same ID, `add_session()` raises a `ValueError`. A session with the same ID that's no longer usable is replaced. In v1, `add_session()` logged a warning and kept the old session in both cases. + +**Before (v1):** + +```python +session_pool.add_session(Session(id='login')) +session = await session_pool.get_session_by_id('login') +``` + +**Now (v2):** + +```python +# highlight-next-line +await session_pool.add_session({'id': 'login'}) +# highlight-next-line +session = await session_pool.get_session('login') +``` + +When `add_session()` has grown the pool beyond `max_pool_size`, `get_session()` creates a new session only if removing the retired sessions leaves room for it. Otherwise, it returns one of the remaining sessions. In v1, it created a new session every time it removed retired sessions. + +### A session ID is unique in the pool + +The pool holds one usable session per ID. It raises a `ValueError` when: + +- `get_session()` gets a session from `create_session_function` with the ID of a usable session already in the pool. Such a function includes one that returns the same `Session` object on every call, so with a `max_pool_size` over 1 the second `get_session()` raises. +- The pool is entered, and the function gives two restored sessions the same ID. +- `create_session_settings` holds an `id`, and `max_pool_size` is over 1. + +In v1, a new session silently replaced the session with its ID, so a pool with a fixed session ID and a `max_pool_size` over 1 created new sessions, without the cookies of the old one, on every `get_session()` call. To share one session, pass `max_pool_size=1`. To use several sessions with fixed IDs, add them with `add_session()`. + +`get_session()` and `add_session()` also raise a `ValueError` when the session they build is no longer usable, such as a shared session that `create_session_function` returns after it was retired. In v1, the pool returned such a session. When the pool is entered, it drops a restored session that the function recreates unusable. + +In a crawler, a `ValueError` from `get_session()` ends the crawl: `run()` raises it after the crawler has tried to get a session three times. + ### `max_session_rotations` is removed Session errors no longer have their own retry budget, the same as in Crawlee JS v4. The `max_session_rotations` crawler option and the `Request.session_rotation_count` property are removed. A `SessionError`, which includes a `ProxyError` and a blocked response, retires the session and counts towards `max_request_retries` like any other error. With the defaults, a request that keeps failing with session errors gets 4 attempts instead of 10. To allow more attempts on blocked requests, raise `max_request_retries`. @@ -1606,6 +1648,8 @@ The `ThrottlingRequestManager` warning about capping a delay now calls it a "req The WARNING `Encountered "", rotating session and retrying...` is removed. Session errors log the same `Retrying request to due to: . ` WARNING as other errors. For the other session error changes, see [`max_session_rotations` is removed](#max_session_rotations-is-removed). +`SessionPool.add_session()` no longer logs the `Session with ID ... already exists in the pool.` warning. It raises a `ValueError` for a usable session with the same ID and replaces one that's no longer usable. For details, see [`add_session()` is async and takes session options](#add_session-is-async-and-takes-session-options). + The `Retrying request to ...` WARNING is now logged after the `error_handler` runs, and only when the request is retried. In v1, it was logged before the error handler, so it also appeared when the handler then raised. The error of an `AdaptivePlaywrightCrawler` sub crawler that timed out now reads `rendering_type=static timed out after 60.0 seconds`, with a space before `seconds`. diff --git a/src/crawlee/crawlers/_basic/_basic_crawler.py b/src/crawlee/crawlers/_basic/_basic_crawler.py index 1f39aa1419..95f4a7c153 100644 --- a/src/crawlee/crawlers/_basic/_basic_crawler.py +++ b/src/crawlee/crawlers/_basic/_basic_crawler.py @@ -741,7 +741,7 @@ async def _get_session(self) -> Session: async def _get_session_by_id(self, session_id: str) -> Session | None: """Take the session with the given id from the session pool.""" return await wait_for( - partial(self._session_pool.get_session_by_id, session_id), + partial(self._session_pool.get_session, session_id), timeout=self._internal_timeout, timeout_message='Fetching a session from the pool timed out after ' f'{self._internal_timeout.total_seconds()} seconds', diff --git a/src/crawlee/sessions/_session_pool.py b/src/crawlee/sessions/_session_pool.py index 2ebfc0a21b..381822b204 100644 --- a/src/crawlee/sessions/_session_pool.py +++ b/src/crawlee/sessions/_session_pool.py @@ -74,11 +74,11 @@ def __init__( `has_redacted_password`, or the pool drops the restored session. Defaults to `Session(**options)`. proxy_configuration: Assigns proxies to the sessions that the pool creates or restores. Before calling `create_session_function`, the pool sets `proxy_info` in the options to the result of - `proxy_configuration.new_proxy_info()`, called with the proxy of a restored session. A session added - with `add_session` keeps its own `proxy_info`. A restored session without a proxy, for example because - `new_url_function` returned `None` for it, gets a new one, and so does one whose password - `new_proxy_info()` can't recover, since the persisted state doesn't store it. The cookies of such a - session then go out through a new IP. + `proxy_configuration.new_proxy_info()`, called with the proxy of a restored session or of the options + passed to `add_session`. A `Session` passed to `add_session` keeps its own `proxy_info`. A restored + session without a proxy, for example because `new_url_function` returned `None` for it, gets a new one, + and so does one whose password `new_proxy_info()` can't recover, since the persisted state doesn't store + it. The cookies of such a session then go out through a new IP. event_manager: The event manager to handle events like persist state. persistence_enabled: Flag to enable or disable state persistence of the pool. persist_state_kvs_name: The name of the `KeyValueStore` used for state persistence. @@ -88,7 +88,8 @@ def __init__( combined with `persist_state_kvs_name`. Raises: - ValueError: If both `proxy_configuration` and a `proxy_info` in `create_session_settings` are passed. + ValueError: If both `proxy_configuration` and a `proxy_info` in `create_session_settings` are passed, or if + `create_session_settings` has an `id` and `max_pool_size` is over 1. """ if proxy_configuration is not None and create_session_settings and 'proxy_info' in create_session_settings: raise ValueError( @@ -97,6 +98,13 @@ def __init__( 'only one of them.' ) + if max_pool_size > 1 and create_session_settings and create_session_settings.get('id') is not None: + raise ValueError( + 'An `id` in `create_session_settings` gives every session of the pool the same ID, but the pool holds ' + 'only one usable session per ID. Pass `max_pool_size=1`, or add the sessions with their own IDs with ' + '`add_session`.' + ) + if id is not None: validate_id(id, type(self).__name__) @@ -128,11 +136,11 @@ def __init__( self._persistence_enabled = persistence_enabled # Keeps concurrent `get_session` calls from overfilling the pool while a session is being created, and holds - # them until the pool is entered and its restored sessions are recreated. + # them and `add_session` calls until the pool is entered and its restored sessions are recreated. self._lock = asyncio.Lock() - # Set once an entry of the pool finishes or fails. `get_session_by_id` waits only for it, so a lookup doesn't - # wait for `_lock` while `get_session` creates a session. + # Set once an entry of the pool finishes or fails. A lookup by ID waits only for it, so it doesn't wait for + # `_lock` while a session is being created. self._entry_finished = asyncio.Event() # Set once the sessions of the persisted record are recreated, so an entry that fails before that retries it. @@ -191,12 +199,14 @@ async def __aenter__(self) -> SessionPool: dropped_session_count = 0 for session in state.sessions.values(): restored_session = await self._build_session(_get_session_options(session)) + if not restored_session.is_usable: + continue # A proxy whose password neither `proxy_configuration` nor the factory restored fails auth. restored_proxy_info = restored_session.proxy_info if restored_proxy_info is not None and restored_proxy_info.has_redacted_password: dropped_session_count += 1 continue - restored_sessions[restored_session.id] = restored_session + _add_restored_session(restored_sessions, restored_session) state.sessions = restored_sessions if dropped_session_count: @@ -237,6 +247,11 @@ async def __aexit__( if not self._active: raise RuntimeError(f'The {self.__class__.__name__} is not active.') + # An exit during an entry waits for it, so that it doesn't tear the state down while the sessions are restored. + await self._entry_finished.wait() + if not self._active: + raise RuntimeError(f'The {self.__class__.__name__} is not active.') + try: await self._state.teardown() finally: @@ -257,33 +272,79 @@ def get_state(self, *, as_dict: bool = False) -> SessionPoolModel | dict: return model @ensure_context - def add_session(self, session: Session) -> None: - """Add an externally created session to the pool. + async def add_session(self, session: Session | SessionOptions | None = None) -> Session: + """Add a session to the pool, even beyond `max_pool_size`. - This is intended only for the cases when you want to add a session that was created outside of the pool. - Otherwise, the pool will create new sessions automatically. + The pool creates sessions as needed, so add only a session that needs specific options, such as a fixed `id`. + The pool builds a session from options the same way as the sessions it creates, and adds a `Session` instance as + it is. A session with the same `id` that's no longer usable is replaced. A full pool first removes its retired + sessions. Args: - session: The session to add to the pool. + session: The `Session` to add, or the options of the session to create. + + Returns: + The added session. + + Raises: + ValueError: If the pool already holds a usable session with the same `id`, or if the session built from the + options is no longer usable. """ - state = self._state.current_value + async with self._lock: + self._raise_if_deactivated() + + if isinstance(session, Session): + new_session = session + else: + options = session or SessionOptions() + # A duplicate `id` in the options or the settings is rejected before the factory and the proxy + # configuration run. + options_id = options.get('id', self._session_settings.get('id')) + if self._holds_usable_session(options_id): + raise ValueError(f'The session pool already holds a usable session with ID {options_id}.') + new_session = await self._build_usable_session(options) + + # Covers a passed `Session` and an ID set by the factory. + if self._holds_usable_session(new_session.id): + raise ValueError(f'The session pool already holds a usable session with ID {new_session.id}.') + + # A replaced session doesn't count toward a full pool. + self._state.current_value.sessions.pop(new_session.id, None) + if self.session_count >= self._max_pool_size: + self._remove_retired_sessions() + + self._state.current_value.sessions[new_session.id] = new_session + return new_session + + @overload + async def get_session(self, session_id: None = None) -> Session: ... - if session.id in state.sessions: - logger.warning('Session with ID %s already exists in the pool.', session.id) - return - state.sessions[session.id] = session + @overload + async def get_session(self, session_id: str) -> Session | None: ... @ensure_context - async def get_session(self) -> Session: + async def get_session(self, session_id: str | None = None) -> Session | None: """Retrieve a session from the pool. - While the pool has fewer than `max_pool_size` sessions, this method creates a new one. Once the pool is full, - it picks a random session. If the random session is not usable, retired sessions are removed and a new session - is created and returned. + Without `session_id`, the pool creates a new session while it has fewer than `max_pool_size` sessions. Once + it's full, it picks a random session. If the random session is not usable, retired sessions are removed, and + the pool creates a new session if it has room, or picks a random one of the remaining sessions otherwise. + + With `session_id`, the pool returns the usable session with this ID and doesn't create one. + + Args: + session_id: The ID of the session to retrieve. Returns: - The session object. + The session. With `session_id`, `None` if the pool has no usable session with this ID. + + Raises: + ValueError: If the new session is no longer usable, or if `create_session_function` gives it the ID of a + usable session already in the pool. """ + if session_id is not None: + return await self._get_session_by_id(session_id) + async with self._lock: self._raise_if_deactivated() @@ -295,22 +356,15 @@ async def get_session(self) -> Session: if session.is_usable: return session - # If the random session is not usable, clean up and create a new session + # If the random session is not usable, clean up and create a new session. A pool that `add_session` grew + # beyond `max_pool_size` can still be full after the cleanup, so it picks one of the remaining sessions. self._remove_retired_sessions() - return await self._create_new_session() - - @ensure_context - async def get_session_by_id(self, session_id: str) -> Session | None: - """Retrieve a session by ID from the pool. - - It doesn't create sessions. If the session is not found or not usable, `None` is returned. - - Args: - session_id: The ID of the session to retrieve. + if self.session_count < self._max_pool_size: + return await self._create_new_session() + return self._get_random_session() - Returns: - The session object if found and usable, otherwise `None`. - """ + async def _get_session_by_id(self, session_id: str) -> Session | None: + """Get the usable session with the given ID, without waiting for a session that's being created.""" await self._entry_finished.wait() self._raise_if_deactivated() session = self._state.current_value.sessions.get(session_id) @@ -362,12 +416,36 @@ async def _build_session(self, options: SessionOptions) -> Session: return session + async def _build_usable_session(self, options: SessionOptions) -> Session: + """Build a session like `_build_session`, and raise if it's no longer usable.""" + session = await self._build_session(options) + if not session.is_usable: + raise ValueError( + f'The session pool built the session {session.id}, which is no longer usable. Check that ' + '`create_session_settings`, the options passed to `add_session` and `create_session_function` give a ' + 'usable session, for example a new session instead of a retired one returned on every call.' + ) + return session + async def _create_new_session(self) -> Session: """Create a new session, add it to the pool and return it.""" - new_session = await self._build_session(SessionOptions()) + new_session = await self._build_usable_session(SessionOptions()) + if self._holds_usable_session(new_session.id): + raise ValueError( + f'`create_session_function` returned a session with the ID {new_session.id} of a usable session ' + 'already in the pool. Give every new session its own ID, pass `max_pool_size=1` to use a single ' + 'session, or add the sessions with fixed IDs with `add_session`.' + ) self._state.current_value.sessions[new_session.id] = new_session return new_session + def _holds_usable_session(self, session_id: str | None) -> bool: + """Check whether the pool holds a usable session with the given ID.""" + if session_id is None: + return False + existing_session = self._state.current_value.sessions.get(session_id) + return existing_session is not None and existing_session.is_usable + def _get_random_session(self) -> Session: """Get a random session from the pool.""" state = self._state.current_value @@ -381,6 +459,16 @@ def _remove_retired_sessions(self) -> None: state.sessions = {session.id: session for session in state.sessions.values() if session.is_usable} +def _add_restored_session(restored_sessions: dict[str, Session], session: Session) -> None: + """Add a recreated session to `restored_sessions`, unless the factory gave another restored session its ID.""" + if session.id in restored_sessions: + raise ValueError( + f'`create_session_function` gave two restored sessions the ID {session.id}. Build the session from the ' + 'options it gets, so that a restored session keeps its ID.' + ) + restored_sessions[session.id] = session + + def _get_session_options(session: Session) -> SessionOptions: """Get the options that recreate the given session.""" state = session.get_state(as_dict=False) diff --git a/tests/integration/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py b/tests/integration/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py index 36a875bc5f..c95f79647e 100644 --- a/tests/integration/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py +++ b/tests/integration/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py @@ -1101,7 +1101,7 @@ async def request_handler(context: AdaptivePlaywrightCrawlingContext) -> None: assert used_session_id is not None - session = await session_pool.get_session_by_id(used_session_id) + session = await session_pool.get_session(used_session_id) check_request = await request_queue.get_request(request.unique_key) assert session is not None diff --git a/tests/integration/crawlers/_http/test_http_crawler.py b/tests/integration/crawlers/_http/test_http_crawler.py index 56fd214925..d5e1fe99e6 100644 --- a/tests/integration/crawlers/_http/test_http_crawler.py +++ b/tests/integration/crawlers/_http/test_http_crawler.py @@ -193,7 +193,7 @@ async def handler(context: HttpCrawlingContext) -> None: session_ids = {call[0][0] for call in track_session_usage.call_args_list} assert len(session_ids) == 1 - session = await session_pool.get_session_by_id(session_ids.pop()) + session = await session_pool.get_session(session_ids.pop()) assert session is not None assert {cookie['name']: cookie['value'] for cookie in session.cookies.get_cookies_as_dicts()} == { 'a': '1', @@ -571,7 +571,7 @@ async def handler(context: HttpCrawlingContext) -> None: session_ids = {call[0][0] for call in track_session_usage.call_args_list} assert len(session_ids) == 1 - session = await session_pool.get_session_by_id(session_ids.pop()) + session = await session_pool.get_session(session_ids.pop()) assert session is not None session_cookies_dict = {cookie['name']: cookie for cookie in session.cookies.get_cookies_as_dicts()} diff --git a/tests/unit/crawlers/_basic/test_basic_crawler.py b/tests/unit/crawlers/_basic/test_basic_crawler.py index b03771aad5..a77ba5483a 100644 --- a/tests/unit/crawlers/_basic/test_basic_crawler.py +++ b/tests/unit/crawlers/_basic/test_basic_crawler.py @@ -3552,7 +3552,7 @@ async def handler(context: BasicCrawlingContext) -> None: async with session_pool: # The pool creates sessions on demand, so the bound ones are added up front. for session_id in check_sessions: - session_pool.add_session(Session(id=session_id)) + await session_pool.add_session(Session(id=session_id)) await crawler.run(requests) assert len(used_sessions) == 10 @@ -4153,7 +4153,7 @@ async def handler(context: BasicCrawlingContext) -> None: check_request = await request_queue.get_request(request.unique_key) assert check_request is not None assert check_request.user_data['request_state'] == ['initial', 'modified_0', 'error', 'modified_1'] - session = await session_pool.get_session_by_id(session.id) + session = await session_pool.get_session(session.id) assert session is not None assert session.user_data['session_state'] == ['initial', 'modified_0', 'error', 'modified_1'] assert session.cookies['initial'] == 'yes' diff --git a/tests/unit/sessions/test_session_pool.py b/tests/unit/sessions/test_session_pool.py index db55bd5901..3b5e243bed 100644 --- a/tests/unit/sessions/test_session_pool.py +++ b/tests/unit/sessions/test_session_pool.py @@ -3,7 +3,9 @@ import asyncio import json import logging +from contextlib import nullcontext from datetime import UTC, datetime +from functools import partial from typing import TYPE_CHECKING, Any from unittest.mock import AsyncMock, Mock @@ -18,7 +20,7 @@ from crawlee.storages import KeyValueStore if TYPE_CHECKING: - from collections.abc import AsyncGenerator + from collections.abc import AsyncGenerator, Callable MAX_POOL_SIZE = 3 KVS_NAME = 'test-session-pool' @@ -69,26 +71,242 @@ async def test_add_session(session_pool: SessionPool) -> None: """Test adding sessions to the session pool increases session counts appropriately.""" session_01 = Session(id='test_session_01') session_02 = Session(id='test_session_02') - session_pool.add_session(session=session_01) - session_pool.add_session(session=session_02) + await session_pool.add_session(session=session_01) + await session_pool.add_session(session=session_02) assert session_pool.session_count == 2 assert session_pool.usable_session_count == 2 assert session_pool.retired_session_count == 0 -async def test_add_session_duplicate(caplog: pytest.LogCaptureFixture, session_pool: SessionPool) -> None: - """Verify that adding a duplicate session logs a warning and does not increase count.""" - session_01 = Session(id='test_session_01') - session_02 = Session(id='test_session_01') +async def test_add_session_options_build_session() -> None: + """Test that `add_session` builds a session from options with the settings, factory and proxy configuration.""" + create_session_function = Mock(side_effect=lambda options: Session(**options)) + passed_proxy_info = ProxyInfo(url='http://passed.com:8000', scheme='http', hostname='passed.com', port=8000) + proxy_info = ProxyInfo(url='http://proxy.com:8000', scheme='http', hostname='proxy.com', port=8000) + proxy_configuration = Mock(spec=ProxyConfiguration) + proxy_configuration.new_proxy_info = AsyncMock(return_value=proxy_info) - session_pool.add_session(session=session_01) - assert session_pool.session_count == 1 + async with SessionPool( + create_session_settings={'max_usage_count': 5}, + create_session_function=create_session_function, + proxy_configuration=proxy_configuration, + persistence_enabled=False, + ) as sp: + session = await sp.add_session({'id': 'named', 'proxy_info': passed_proxy_info}) + assert await sp.get_session('named') is session - with caplog.at_level(logging.WARNING): - session_pool.add_session(session=session_02) + proxy_configuration.new_proxy_info.assert_awaited_once_with(passed_proxy_info) + create_session_function.assert_called_once_with({'max_usage_count': 5, 'id': 'named', 'proxy_info': proxy_info}) - assert session_pool.session_count == 1 - assert 'Session with ID test_session_01 already exists in the pool.' in caplog.text + +async def test_add_session_keeps_passed_session() -> None: + """Test that `add_session` adds a passed `Session` as it is, without the factory or a proxy.""" + create_session_function = Mock(side_effect=lambda options: Session(**options)) + proxy_configuration = Mock(spec=ProxyConfiguration) + passed_session = Session(id='named') + + async with SessionPool( + create_session_function=create_session_function, + proxy_configuration=proxy_configuration, + persistence_enabled=False, + ) as sp: + session = await sp.add_session(passed_session) + assert await sp.get_session('named') is passed_session + + assert session is passed_session + proxy_configuration.new_proxy_info.assert_not_called() + create_session_function.assert_not_called() + + +@pytest.mark.parametrize( + ('create_session', 'make_duplicate', 'factory_calls'), + [ + pytest.param(lambda options: Session(**options), lambda _: Session(id='named'), 0, id='session'), + pytest.param(lambda options: Session(**options), lambda _: SessionOptions(id='named'), 0, id='options'), + pytest.param(lambda _: Session(id='named'), lambda _: None, 1, id='factory_id'), + pytest.param(lambda options: Session(**options), lambda session: session, 0, id='same_session'), + ], +) +async def test_add_session_with_usable_id_raises( + create_session: Callable[[SessionOptions], Session], + make_duplicate: Callable[[Session], Session | SessionOptions | None], + factory_calls: int, +) -> None: + """Test that `add_session` with the ID of a usable session raises, keeps it, and calls no factory for a known ID.""" + create_session_function = Mock(side_effect=create_session) + + async with SessionPool(create_session_function=create_session_function, persistence_enabled=False) as sp: + session = await sp.add_session(Session(id='named')) + + with pytest.raises(ValueError, match='already holds a usable session with ID named'): + await sp.add_session(make_duplicate(session)) + + assert await sp.get_session('named') is session + + assert create_session_function.call_count == factory_calls + + +async def test_add_session_replaces_unusable(session_pool: SessionPool) -> None: + """Test that `add_session` replaces an unusable session with the same ID without counting it toward a full pool.""" + other_retired_session = await session_pool.add_session({'id': 'other'}) + other_retired_session.retire() + await session_pool.add_session({'id': 'kept'}) + retired_session = await session_pool.add_session({'id': 'named'}) + retired_session.retire() + + session = await session_pool.add_session({'id': 'named'}) + + assert await session_pool.get_session('named') is session + assert session_pool.retired_session_count == 1 + + +async def test_add_session_beyond_max_pool_size() -> None: + """Test that `add_session` removes retired sessions only from a full pool and adds beyond `max_pool_size`.""" + async with SessionPool(max_pool_size=2, persistence_enabled=False) as sp: + retired_session = await sp.get_session() + retired_session.retire() + + await sp.add_session() + assert sp.retired_session_count == 1 + + await sp.add_session() + assert sp.retired_session_count == 0 + + await sp.add_session() + assert sp.session_count == 3 + + +async def test_add_session_survives_reset() -> None: + """Test that a session added by `add_session` stays in the pool when `reset` is called during its creation.""" + creation_started = asyncio.Event() + release_creation = asyncio.Event() + + async def create_session(options: SessionOptions) -> Session: + creation_started.set() + await release_creation.wait() + return Session(**options) + + async with SessionPool(create_session_function=create_session, persistence_enabled=False) as sp: + add_task = asyncio.create_task(sp.add_session({'id': 'named'})) + await creation_started.wait() + sp.reset() + release_creation.set() + session = await add_task + + assert await sp.get_session('named') is session + + +async def test_settings_id_needs_pool_size_one() -> None: + """Test that an `id` in `create_session_settings` raises unless `max_pool_size` is 1, and is checked up front.""" + with pytest.raises(ValueError, match='An `id` in `create_session_settings`'): + SessionPool(max_pool_size=2, create_session_settings={'id': 'login'}) + + create_session_function = Mock(side_effect=lambda options: Session(**options)) + async with SessionPool( + max_pool_size=1, + create_session_settings={'id': 'login'}, + create_session_function=create_session_function, + persistence_enabled=False, + ) as sp: + assert (await sp.get_session()).id == 'login' + + with pytest.raises(ValueError, match='already holds a usable session with ID login'): + await sp.add_session() + + create_session_function.assert_called_once() + + +async def test_get_session_reuses_after_sweep(monkeypatch: pytest.MonkeyPatch) -> None: + """Test that a pool still full after removing its retired sessions returns a usable one instead of creating one.""" + retired_first = Mock(side_effect=lambda sessions: min(sessions, key=lambda session: session.is_usable)) + monkeypatch.setattr('crawlee.sessions._session_pool.random', Mock(choice=retired_first)) + + async with SessionPool(max_pool_size=1, create_session_settings={'id': 'login'}) as session_pool: + login_session = await session_pool.get_session() + await session_pool.add_session(Session(retired=True)) + + assert await session_pool.get_session() is login_session + assert session_pool.session_count == 1 + + +@pytest.mark.parametrize( + 'shared', + [pytest.param(False, id='new_session'), pytest.param(True, id='shared_session')], +) +async def test_get_session_factory_id_raises(*, shared: bool) -> None: + """Test that `get_session` raises when the factory returns a session with the ID of a usable one, and keeps it.""" + shared_session = Session(id='login') + + def create_session(_: SessionOptions) -> Session: + return shared_session if shared else Session(id='login') + + async with SessionPool(max_pool_size=2, create_session_function=create_session, persistence_enabled=False) as sp: + session = await sp.get_session() + + with pytest.raises(ValueError, match='returned a session with the ID login'): + await sp.get_session() + + assert await sp.get_session('login') is session + + +@pytest.mark.parametrize( + 'method', [pytest.param('get_session', id='get_session'), pytest.param('add_session', id='add_session')] +) +async def test_factory_retired_session_raises(method: str) -> None: + """Test that a session lookup raises when the factory returns a retired session, and doesn't add it.""" + async with SessionPool(create_session_function=lambda _: Session(retired=True), persistence_enabled=False) as sp: + with pytest.raises(ValueError, match='which is no longer usable'): + await getattr(sp, method)() + + assert sp.session_count == 0 + + +async def test_restore_factory_id_raises() -> None: + """Test that the entry of the pool raises when the factory gives two restored sessions one ID.""" + async with SessionPool( + max_pool_size=2, + persistence_enabled=True, + persist_state_kvs_name=KVS_NAME, + persist_state_key=PERSIST_STATE_KEY, + ) as sp: + await sp.get_session() + await sp.get_session() + + session_pool = SessionPool( + max_pool_size=2, + create_session_function=lambda _: Session(id='same'), + persistence_enabled=True, + persist_state_kvs_name=KVS_NAME, + persist_state_key=PERSIST_STATE_KEY, + ) + with pytest.raises(ValueError, match='gave two restored sessions the ID same'): + async with session_pool: + pass + + +async def test_restore_drops_retired_factory_session() -> None: + """Test that the entry of the pool drops a restored session that the factory recreates retired.""" + async with SessionPool( + max_pool_size=1, + persistence_enabled=True, + persist_state_kvs_name=KVS_NAME, + persist_state_key=PERSIST_STATE_KEY, + ) as sp: + persisted_session = await sp.get_session() + + def create_retired_session(options: SessionOptions) -> Session: + options['retired'] = True + return Session(**options) + + async with SessionPool( + max_pool_size=1, + create_session_function=create_retired_session, + persistence_enabled=True, + persist_state_kvs_name=KVS_NAME, + persist_state_key=PERSIST_STATE_KEY, + ) as sp: + assert sp.session_count == 0 + assert await sp.get_session(persisted_session.id) is None async def test_get_session(session_pool: SessionPool) -> None: @@ -109,7 +327,7 @@ async def test_pool_does_not_reuse_retired_session_after_success() -> None: session.retire() session.mark_good() - assert await pool.get_session_by_id(session.id) is None + assert await pool.get_session(session.id) is None replacement = await pool.get_session() assert replacement.id != session.id assert replacement.is_usable @@ -117,17 +335,17 @@ async def test_pool_does_not_reuse_retired_session_after_success() -> None: async def test_get_session_no_usable(caplog: pytest.LogCaptureFixture, session_pool: SessionPool) -> None: """Ensure that retrieval of a non-existent or retired session returns None and logs warning.""" - session = await session_pool.get_session_by_id('non_existent') + session = await session_pool.get_session('non_existent') assert session is None session = Session(id='test_session_not_usable') session.retire() assert not session.is_usable - session_pool.add_session(session=session) + await session_pool.add_session(session=session) assert session_pool.session_count == 1 with caplog.at_level(logging.WARNING): - session = await session_pool.get_session_by_id('test_session_not_usable') + session = await session_pool.get_session('test_session_not_usable') assert session is None assert 'Session with ID non_existent not found.' in caplog.text @@ -203,7 +421,7 @@ async def test_restored_session_is_recreated_by_factory() -> None: persist_state_kvs_name=KVS_NAME, persist_state_key=PERSIST_STATE_KEY, ) as sp: - session = await sp.get_session_by_id('restored') + session = await sp.get_session('restored') proxy_configuration.new_proxy_info.assert_awaited_once_with(persisted_proxy_info) create_session_function.assert_called_once() @@ -230,7 +448,7 @@ async def test_restored_state_overrides_settings() -> None: persist_state_kvs_name=KVS_NAME, persist_state_key=PERSIST_STATE_KEY, ) as sp: - restored_session = await sp.get_session_by_id(session.id) + restored_session = await sp.get_session(session.id) assert restored_session is not None assert restored_session.cookies.get_cookies_as_dicts()[0]['value'] == 'restored' @@ -295,7 +513,7 @@ async def test_restored_session_proxy( with caplog.at_level(logging.WARNING): async with SessionPool(**pool_kwargs, **restore_kwargs) as sp: - restored_session = await sp.get_session_by_id(session.id) + restored_session = await sp.get_session(session.id) is_dropped = restored_proxy_info is None assert (restored_session is None) is is_dropped @@ -327,7 +545,7 @@ async def test_proxy_password_restored_from_proxy_urls(kvs: KeyValueStore) -> No persist_state_kvs_name=KVS_NAME, persist_state_key=PERSIST_STATE_KEY, ) as sp: - restored_sessions = [await sp.get_session_by_id(session.id) for session in sessions] + restored_sessions = [await sp.get_session(session.id) for session in sessions] assert [session.proxy_info for session in restored_sessions if session] == [ session.proxy_info for session in sessions @@ -393,8 +611,8 @@ async def create_session(options: SessionOptions) -> Session: assert sessions[0] is sessions[1] -async def test_get_session_by_id_does_not_wait_for_session_creation() -> None: - """Test that `get_session_by_id` returns a session while `get_session` waits for a slow factory.""" +async def test_lookup_by_id_skips_creation_wait() -> None: + """Test that `get_session` with an ID returns a session while another call waits for a slow factory.""" creation_started = asyncio.Event() release_creation = asyncio.Event() @@ -405,14 +623,14 @@ async def create_session(options: SessionOptions) -> Session: async with SessionPool(max_pool_size=2, create_session_function=create_session) as sp: existing_session = Session(id='existing') - sp.add_session(existing_session) + await sp.add_session(existing_session) create_task = asyncio.create_task(sp.get_session()) await creation_started.wait() try: async with asyncio.timeout(5): - found_session = await sp.get_session_by_id(existing_session.id) + found_session = await sp.get_session(existing_session.id) finally: release_creation.set() await create_task @@ -453,7 +671,7 @@ async def create_session(options: SessionOptions) -> Session: @pytest.mark.parametrize( 'by_id', - [pytest.param(False, id='get_session'), pytest.param(True, id='get_session_by_id')], + [pytest.param(False, id='get_session'), pytest.param(True, id='by_id')], ) async def test_get_session_waits_for_restore(*, by_id: bool) -> None: """Test that a session lookup during the entry of the pool gets the session recreated by the factory.""" @@ -486,7 +704,7 @@ def create_session(options: SessionOptions) -> Session: ) enter_task = asyncio.create_task(session_pool.__aenter__()) await kvs_requested.wait() - lookup = session_pool.get_session_by_id(persisted_session.id) if by_id else session_pool.get_session() + lookup = session_pool.get_session(persisted_session.id) if by_id else session_pool.get_session() lookup_task = asyncio.create_task(lookup) await asyncio.sleep(0) release_kvs.set() @@ -501,12 +719,54 @@ def create_session(options: SessionOptions) -> Session: assert session.user_data == {'recreated': True} +async def test_add_session_waits_for_restore() -> None: + """Test that `add_session` during the entry of the pool sees the restored session with the same ID.""" + async with SessionPool( + max_pool_size=1, + persistence_enabled=True, + persist_state_kvs_name=KVS_NAME, + persist_state_key=PERSIST_STATE_KEY, + ) as sp: + persisted_session = await sp.get_session() + + kvs_requested = asyncio.Event() + release_kvs = asyncio.Event() + + async def open_kvs() -> KeyValueStore: + kvs_requested.set() + await release_kvs.wait() + return await KeyValueStore.open(name=KVS_NAME) + + session_pool = SessionPool( + max_pool_size=1, + persistence_enabled=True, + persist_state_key=PERSIST_STATE_KEY, + persist_state_kvs_factory=open_kvs, + ) + enter_task = asyncio.create_task(session_pool.__aenter__()) + await kvs_requested.wait() + add_task = asyncio.create_task(session_pool.add_session({'id': persisted_session.id})) + await asyncio.sleep(0) + release_kvs.set() + await enter_task + + try: + with pytest.raises(ValueError, match='already holds a usable session'): + await add_task + finally: + await session_pool.__aexit__(None, None, None) + + @pytest.mark.parametrize( - 'by_id', - [pytest.param(False, id='get_session'), pytest.param(True, id='get_session_by_id')], + 'lookup', + [ + pytest.param('get_session', id='get_session'), + pytest.param('by_id', id='by_id'), + pytest.param('add_session', id='add_session'), + ], ) -async def test_lookup_during_failed_entry_raises(*, by_id: bool) -> None: - """Test that a session lookup that waits for an entry of the pool that fails raises that the pool isn't active.""" +async def test_lookup_during_failed_entry_raises(lookup: str) -> None: + """Test that a lookup or `add_session` waiting for an entry of the pool that fails raises that it isn't active.""" async with SessionPool( max_pool_size=2, persistence_enabled=True, @@ -535,10 +795,14 @@ def create_session(options: SessionOptions) -> Session: persist_state_key=PERSIST_STATE_KEY, persist_state_kvs_factory=open_kvs, ) + lookups = { + 'get_session': session_pool.get_session, + 'by_id': partial(session_pool.get_session, persisted_session.id), + 'add_session': session_pool.add_session, + } enter_task = asyncio.create_task(session_pool.__aenter__()) await kvs_requested.wait() - lookup = session_pool.get_session_by_id(persisted_session.id) if by_id else session_pool.get_session() - lookup_task = asyncio.create_task(lookup) + lookup_task = asyncio.create_task(lookups[lookup]()) await asyncio.sleep(0) release_kvs.set() @@ -590,7 +854,7 @@ async def test_session_pool_persist(event_manager: EventManager, kvs_name: str | # Check if all the sessions are correctly persisted for kvs_session in sp_model.sessions.values(): - session = await sp.get_session_by_id(kvs_session.id) + session = await sp.get_session(kvs_session.id) assert kvs_session == session @@ -711,7 +975,7 @@ async def test_retired_session_is_not_restored(event_manager: EventManager, kvs: persist_state_kvs_name=KVS_NAME, persist_state_key=PERSIST_STATE_KEY, ) as restored_pool: - assert await restored_pool.get_session_by_id(session.id) is None + assert await restored_pool.get_session(session.id) is None replacement = await restored_pool.get_session() assert replacement.id != session.id assert replacement.is_usable @@ -727,13 +991,13 @@ async def test_methods_raise_error_when_not_active() -> None: session_pool.get_state(as_dict=True) with pytest.raises(RuntimeError, match=r'SessionPool is not active.'): - session_pool.add_session(session) + await session_pool.add_session(session) with pytest.raises(RuntimeError, match=r'SessionPool is not active.'): await session_pool.get_session() with pytest.raises(RuntimeError, match=r'SessionPool is not active.'): - await session_pool.get_session_by_id(session.id) + await session_pool.get_session(session.id) await session_pool.reset_store() @@ -806,3 +1070,54 @@ async def wait_for_release() -> None: release_teardown.set() await exit_task + + +@pytest.mark.parametrize( + 'entry_fails', + [pytest.param(False, id='entry_succeeds'), pytest.param(True, id='entry_fails')], +) +async def test_exit_waits_for_entry(monkeypatch: pytest.MonkeyPatch, *, entry_fails: bool) -> None: + """Test that an exit during the entry of the pool tears it down only after the entry, and raises if it failed.""" + async with SessionPool( + max_pool_size=1, + persistence_enabled=True, + persist_state_kvs_name=KVS_NAME, + persist_state_key=PERSIST_STATE_KEY, + ) as sp: + await sp.get_session() + + creation_started = asyncio.Event() + release_creation = asyncio.Event() + + async def create_session(options: SessionOptions) -> Session: + creation_started.set() + await release_creation.wait() + if entry_fails: + raise RuntimeError('restore failed') + return Session(**options) + + session_pool = SessionPool( + max_pool_size=1, + create_session_function=create_session, + persistence_enabled=True, + persist_state_kvs_name=KVS_NAME, + persist_state_key=PERSIST_STATE_KEY, + ) + teardown = AsyncMock(wraps=session_pool._state.teardown) + monkeypatch.setattr(session_pool._state, 'teardown', teardown) + + enter_task = asyncio.create_task(session_pool.__aenter__()) + await creation_started.wait() + exit_task = asyncio.create_task(session_pool.__aexit__(None, None, None)) + await asyncio.sleep(0) + assert teardown.await_count == 0 + + release_creation.set() + enter_raises = pytest.raises(RuntimeError, match='restore failed') if entry_fails else nullcontext() + exit_raises = pytest.raises(RuntimeError, match='SessionPool is not active') if entry_fails else nullcontext() + with enter_raises: + await enter_task + with exit_raises: + await exit_task + + teardown.assert_awaited_once()