diff --git a/docs/03_concepts/15_cookie_management.mdx b/docs/03_concepts/15_cookie_management.mdx index 31a1ced67e..76de840d22 100644 --- a/docs/03_concepts/15_cookie_management.mdx +++ b/docs/03_concepts/15_cookie_management.mdx @@ -17,7 +17,7 @@ import PersistCookies from '!!raw-loader!roa-loader!./code_examples/cookie_manag Cookies carry login state, consent flags, CSRF tokens, and other per-user data that a site expects to see on every request. -In Crawlee, cookies are stored on the `Session` that handles a request, in a `SessionCookies` jar. When a request runs on a session, the HTTP client sends the session's cookies with the request and writes any `Set-Cookie` from the response back onto the same jar. The next request on that session carries the updated cookies. To keep the response cookies out of the session, set `save_response_cookies` to `False` on the crawler. The session's cookies are still sent. +In Crawlee, cookies are stored on the `Session` that handles a request, in a `SessionCookies` jar. When a request runs on a session, the HTTP client sends the session's cookies with the request and writes any `Set-Cookie` from the response back onto the same jar. The next request on that session carries the updated cookies. To keep the response cookies out of the session, set `save_response_cookies` to `False` on the crawler. The session's cookies are still sent. With `respect_robots_txt_file`, the cookies of the robots.txt responses are saved either way. Cookies follow the session, not the URL. Two requests share cookies when they run on the same session. For how sessions are created and rotated, see the [Session management](./session-management) guide. diff --git a/docs/03_concepts/17_proxy_management.mdx b/docs/03_concepts/17_proxy_management.mdx index 9f68199bf5..0720d366a4 100644 --- a/docs/03_concepts/17_proxy_management.mdx +++ b/docs/03_concepts/17_proxy_management.mdx @@ -41,6 +41,8 @@ All our proxy needs are managed by the `P Instead of `proxy_urls`, you can pass a `new_url_function`. It takes no arguments and returns a proxy URL, or `None` to use no proxy. It can be sync or async. +The crawler and the `SessionPool` also take another proxy configuration implementation, such as a client of your proxy provider. It needs an async `new_proxy_info()` method, which takes the current proxy of the session or `None`, and returns a `ProxyInfo`, or `None` for no proxy. The pool calls it for every session it creates or restores. Return the saved proxy of a restored session, so that the session keeps its IP address. The persisted state doesn't store proxy passwords, so if the proxy `has_redacted_password`, put the password back into its `url` and `password`, or return another proxy. Otherwise, the pool drops the session. + ### Crawler integration `ProxyConfiguration` integrates seamlessly into `BeautifulSoupCrawler` and `PlaywrightCrawler`. 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..a319ee00df 100644 --- a/docs/06_upgrading/upgrading_to_v2.md +++ b/docs/06_upgrading/upgrading_to_v2.md @@ -718,7 +718,7 @@ async def main() -> None: The `use_session_pool` option is removed from the crawlers. Every crawler processes its requests with sessions from its `SessionPool`, the same as Crawlee JS v4. To configure the pool, pass your own `SessionPool` as `session_pool`. -`context.session` is now a `Session` instead of `Session | None`, so you can drop the `if context.session` checks. A request bound by `session_id` to a session that's no longer usable still fails with a `RequestCollisionError`, now with the message `The Session (id: ) bound to the Request is no longer usable`. Its failed request handler gets that session while the pool still holds it, or a retired session with the bound id, instead of `None`. +`context.session` is no longer optional, so you can drop the `if context.session` checks. A request bound by `session_id` to a session that's no longer usable still fails with a `RequestCollisionError`, now with the message `The Session (id: ) bound to the Request is no longer usable`. Its failed request handler gets that session while the pool still holds it, or a retired session with the bound id, instead of `None`. Without the session pool, a 401, 403 or 429 response failed the request without a retry. Now it retires the session, and the request is retried with another one, up to `max_request_retries` times. A `ThrottlingRequestManager` still defers a 429 from a domain it paces. To fail the request without a retry, as in v1, pass `retry_on_blocked=False`. This option also turns off the check of the response content for blocking. With `proxy_urls`, a session keeps its proxy, so the proxy changes when the session does, not on every request. @@ -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 @@ -856,6 +856,8 @@ async def main() -> None: A request bound by `session_id` to a session that's no longer in the pool gets a retired session without a proxy in its failed request handler. A `context.send_request` call there goes without a proxy. +The crawler fetches robots.txt with a session from its session pool, through the proxy and with the cookies of the session. So a proxy from `create_session_settings` or `create_session_function` applies to it too. The cookies of the robots.txt response are saved to the session, even with `save_response_cookies=False`. In v1, the crawler took the proxy from its own `proxy_configuration` and sent no cookies. With `respect_robots_txt_file`, enter a passed pool before `add_requests()` too. Otherwise, `add_requests()` raises a `RuntimeError` once it has to fetch a robots.txt file. + ### `create_session_function` gets the session options The `create_session_function` of `SessionPool` now gets a `SessionOptions` dict, the keyword arguments of `Session`, and can be sync or async. The options hold `create_session_settings` and the proxy that the pool's `proxy_configuration` picked, so you can pass `create_session_settings` together with `create_session_function`. The pool also calls the function for every session it restores from the persisted state, with the saved state in the options. Build the session from the options, so that a restored session keeps its state: @@ -895,6 +897,93 @@ 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. + +### A crawler takes any session pool + +The `session_pool` option of a crawler takes any session pool, not only a `SessionPool`. Such a pool is an async context manager with an `active` property and a `get_session()` method. Without an ID, `get_session()` returns a session. With an ID, it returns the usable session with this ID or `None`. To pass a type checker, declare `get_session()` with these two overloads: + +```python +from typing import overload + +from crawlee.sessions import Session + + +class MySessionPool: + @overload + async def get_session(self, session_id: None = None) -> Session: ... + + @overload + async def get_session(self, session_id: str) -> Session | None: ... + + async def get_session(self, session_id: str | None = None) -> Session | None: ... +``` + +The sessions need `id`, `cookies`, `proxy_info`, `is_usable`, `mark_good()`, `mark_bad()` and `retire()`. The crawler sends the requests of a session through its `proxy_info`. A crawler with a passed pool doesn't take a `proxy_configuration`, so such a pool picks the proxies of its sessions itself, for example with `ProxyConfiguration.new_proxy_info()`. As with a `SessionPool`, enter the pool before you run the crawler. A request bound by `session_id` to a session that such a pool doesn't return gets a retired session in its failed request handler, even while the pool still holds the session. + +`context.session` is typed by these members, so a type checker flags any other `Session` attribute read through it, such as `user_data` or `error_score`. With a `SessionPool`, `context.session` is a `Session`, so cast it: + +```python +from typing import cast + +from crawlee.crawlers import ParselCrawler, ParselCrawlingContext +from crawlee.sessions import Session + +crawler = ParselCrawler() + + +@crawler.router.default_handler +async def request_handler(context: ParselCrawlingContext) -> None: + session = cast('Session', context.session) + session.user_data['logged_in'] = True +``` + +### A crawler takes any proxy configuration + +The `proxy_configuration` option of a crawler and of a `SessionPool` takes any proxy configuration, not only a `ProxyConfiguration`. Such a configuration has an async `new_proxy_info()` method, which takes the current proxy of the session or `None`, and returns a `ProxyInfo`, or `None` for no proxy. For how it handles the proxy of a restored session, see [Proxy configuration](../concepts/proxy-management#proxy-configuration). + +`BasicCrawlerOptions.proxy_configuration` is typed by this method, so a type checker flags any other `ProxyConfiguration` method called through it, such as `new_url()`, and a `new_proxy_info()` call without an argument. + ### `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`. @@ -984,6 +1073,10 @@ In v1, `ImpitHttpClient` and `CurlImpersonateHttpClient` disabled the timeout wh The `headers` argument of a client still applies to every request. Its `Authorization`, `Proxy-Authorization` and `Cookie` headers are dropped when a redirect leaves the origin, the same as the headers passed with a request. With `HttpxHttpClient`, the headers of the client now win over the generated browser headers. In v1, the generated browser headers replaced them. +### `send_request` goes through the proxy of the session + +`send_request` with a `session` sends the request through the proxy of the session, unless you pass another one in `proxy_info`. In v1, it took the proxy only from `proxy_info`. To send the cookies of a session without its proxy, pass `cookies=session.cookies` instead of `session`. + ### A `Cookie` header is merged with the session cookies A `Cookie` header passed with a request or set on the client is merged with the session cookies while the redirect chain stays on its origin. A cookie in the header wins over a session cookie of the same name and isn't stored in the session. In v1, a `Cookie` header passed with a request replaced the session cookies with `ImpitHttpClient`, `HttpxHttpClient` and `context.send_request` of `PlaywrightCrawler`, so an empty `Cookie` header kept them out. `CurlImpersonateHttpClient` sent the session cookies in a second `Cookie` header. @@ -1606,6 +1699,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/_types.py b/src/crawlee/_types.py index bc69c1d8a7..9353bf9460 100644 --- a/src/crawlee/_types.py +++ b/src/crawlee/_types.py @@ -22,7 +22,8 @@ from crawlee.configuration import Configuration from crawlee.http_clients import HttpResponse from crawlee.proxy_configuration import ProxyInfo - from crawlee.sessions import Session, SessionCookies + from crawlee.sessions import SessionCookies + from crawlee.sessions._types import SessionInterface from crawlee.storage_backends import StorageBackend from crawlee.storages import KeyValueStore from crawlee.storages._utils import DatasetItemSnapshots @@ -720,7 +721,7 @@ class BasicCrawlingContext: request: Request """Request object for the current page being processed.""" - session: Session + session: SessionInterface """Session object for the current page being processed.""" proxy_info: ProxyInfo | None diff --git a/src/crawlee/_utils/robots.py b/src/crawlee/_utils/robots.py index 2c33ca9677..44fd85c019 100644 --- a/src/crawlee/_utils/robots.py +++ b/src/crawlee/_utils/robots.py @@ -16,6 +16,7 @@ from crawlee._types import EnqueueStrategy from crawlee.http_clients import HttpClient from crawlee.proxy_configuration import ProxyInfo + from crawlee.sessions._types import SessionInterface logger = getLogger(__name__) @@ -46,16 +47,26 @@ async def from_content(cls, url: str, content: str) -> Self: return cls(url, robots) @classmethod - async def load(cls, url: str, http_client: HttpClient, proxy_info: ProxyInfo | None = None) -> Self: + async def load( + cls, + url: str, + http_client: HttpClient, + proxy_info: ProxyInfo | None = None, + *, + session: SessionInterface | None = None, + ) -> Self: """Load the robots.txt file for a given URL. Args: url: The direct URL of the robots.txt file to be loaded. http_client: The `HttpClient` instance used to perform the network request for fetching the robots.txt file. - proxy_info: Optional `ProxyInfo` to be used when fetching the robots.txt file. If None, no proxy is used. + proxy_info: The proxy to fetch the robots.txt file and its sitemaps through, instead of the proxy of + `session`. + session: The session whose cookies the robots.txt request sends and stores, and whose proxy it goes through. + The sitemaps of the file are loaded without the cookies and proxy of the session. """ try: - response = await http_client.send_request(url, proxy_info=proxy_info) + response = await http_client.send_request(url, session=session, proxy_info=proxy_info) async with response: status_code = response.status_code @@ -81,16 +92,26 @@ async def load(cls, url: str, http_client: HttpClient, proxy_info: ProxyInfo | N return cls(url, robots, http_client=http_client, proxy_info=proxy_info) @classmethod - async def find(cls, url: str, http_client: HttpClient, proxy_info: ProxyInfo | None = None) -> Self: + async def find( + cls, + url: str, + http_client: HttpClient, + proxy_info: ProxyInfo | None = None, + *, + session: SessionInterface | None = None, + ) -> Self: """Determine the location of a robots.txt file for a URL and fetch it. Args: url: The URL whose domain will be used to find the corresponding robots.txt file. http_client: The `HttpClient` instance used to perform the network request for fetching the robots.txt file. - proxy_info: Optional `ProxyInfo` to be used when fetching the robots.txt file. If None, no proxy is used. + proxy_info: The proxy to fetch the robots.txt file and its sitemaps through, instead of the proxy of + `session`. + session: The session whose cookies the robots.txt request sends and stores, and whose proxy it goes through. + The sitemaps of the file are loaded without the cookies and proxy of the session. """ robots_url = URL(url).with_path('/robots.txt') - return await cls.load(str(robots_url), http_client, proxy_info) + return await cls.load(str(robots_url), http_client, proxy_info, session=session) def is_allowed(self, url: str, user_agent: str = '*') -> bool: """Check if the given URL is allowed for the given user agent. diff --git a/src/crawlee/crawlers/_abstract_http/_abstract_http_crawler.py b/src/crawlee/crawlers/_abstract_http/_abstract_http_crawler.py index 269bb49041..28dd5fe02f 100644 --- a/src/crawlee/crawlers/_abstract_http/_abstract_http_crawler.py +++ b/src/crawlee/crawlers/_abstract_http/_abstract_http_crawler.py @@ -48,7 +48,7 @@ class HttpCrawlerOptions( save_response_cookies: NotRequired[bool] """Whether to save the cookies set by the responses to the session. The session cookies are sent either way. The - option doesn't apply to `context.send_request`. + option doesn't apply to `context.send_request` or to fetching robots.txt files with `respect_robots_txt_file`. """ diff --git a/src/crawlee/crawlers/_basic/_basic_crawler.py b/src/crawlee/crawlers/_basic/_basic_crawler.py index 1f39aa1419..ec8b8c3a39 100644 --- a/src/crawlee/crawlers/_basic/_basic_crawler.py +++ b/src/crawlee/crawlers/_basic/_basic_crawler.py @@ -102,9 +102,10 @@ from crawlee.configuration import Configuration from crawlee.events import EventManager from crawlee.http_clients import HttpClient, HttpResponse - from crawlee.proxy_configuration import ProxyConfiguration, ProxyInfo + from crawlee.proxy_configuration import ProxyConfigurationInterface, ProxyInfo from crawlee.request_loaders import RequestManager from crawlee.sessions import SessionCookies + from crawlee.sessions._types import SessionInterface, SessionPoolInterface from crawlee.statistics import FinalStatistics from crawlee.storage_backends import StorageBackend from crawlee.storage_backends.models import DatasetItemsListPage @@ -135,13 +136,13 @@ class _BasicCrawlerOptions(TypedDict): request_manager: NotRequired[RequestManager] """Manager of requests that should be processed by the crawler.""" - session_pool: NotRequired[SessionPool] - """A custom `SessionPool` instance, allowing the use of non-default configuration. Keep it open with `async with` - until every crawler using it has finished.""" + session_pool: NotRequired[SessionPoolInterface] + """A custom `SessionPool` instance, allowing the use of non-default configuration, or another session pool + implementation. Keep it open with `async with` until every crawler using it has finished.""" - proxy_configuration: NotRequired[ProxyConfiguration | None] - """Assigns proxies to the sessions of the crawler's default session pool. With a custom `session_pool`, pass it to - the pool instead.""" + proxy_configuration: NotRequired[ProxyConfigurationInterface | None] + """A `ProxyConfiguration`, or another proxy configuration implementation, that assigns proxies to the sessions of + the crawler's default session pool. With a custom `session_pool`, pass it to the pool instead.""" http_client: NotRequired[HttpClient] """HTTP client used by `BasicCrawlingContext.send_request` method. Keep it open with `async with` until every @@ -281,7 +282,7 @@ class BasicCrawler(Generic[TCrawlingContext, TStatisticsState]): """ _CRAWLEE_STATE_KEY = 'CRAWLEE_STATE' - # Limits the whole robots.txt fetch, including the proxy lookup. The fetch holds a lock that every robots.txt + # Limits the whole robots.txt fetch, including the session lookup. The fetch holds a lock that every robots.txt # lookup waits for, so a stalled origin must not hold it for long. _ROBOTS_TXT_TIMEOUT = timedelta(seconds=30) _ROBOTS_TXT_MAX_ATTEMPTS = 3 @@ -312,8 +313,8 @@ def __init__( event_manager: EventManager | None = None, storage_backend: StorageBackend | None = None, request_manager: RequestManager | None = None, - session_pool: SessionPool | None = None, - proxy_configuration: ProxyConfiguration | None = None, + session_pool: SessionPoolInterface | None = None, + proxy_configuration: ProxyConfigurationInterface | None = None, http_client: HttpClient | None = None, request_handler: Callable[[TCrawlingContext], Awaitable[None]] | None = None, max_request_retries: int = 3, @@ -346,10 +347,11 @@ def __init__( event_manager: The event manager for managing events for the crawler and all its components. storage_backend: The storage backend for managing storages for the crawler and all its components. request_manager: Manager of requests that should be processed by the crawler. - session_pool: A custom `SessionPool` instance, allowing the use of non-default configuration. Keep it open - with `async with` until every crawler using it has finished. - proxy_configuration: Assigns proxies to the sessions of the crawler's default session pool. With a custom - `session_pool`, pass it to the pool instead, since the crawler doesn't accept both. + session_pool: A custom `SessionPool` instance, allowing the use of non-default configuration, or another + session pool implementation. Keep it open with `async with` until every crawler using it has finished. + proxy_configuration: A `ProxyConfiguration`, or another proxy configuration implementation, that assigns + proxies to the sessions of the crawler's default session pool. With a custom `session_pool`, pass it to + the pool instead, since the crawler doesn't accept both. http_client: HTTP client used by `BasicCrawlingContext.send_request` method. Keep it open with `async with` until every crawler using it has finished. request_handler: A callable responsible for handling requests. @@ -447,7 +449,7 @@ def __init__( # Core components self._request_manager = request_manager - self._session_pool = self._own_or_borrow( + self._session_pool: SessionPoolInterface = self._own_or_borrow( session_pool, lambda: SessionPool( id=id, persist_state_kvs_factory=self.get_key_value_store, proxy_configuration=proxy_configuration @@ -578,7 +580,10 @@ async def persist_state_factory() -> KeyValueStore: @cached_property def _owned_collaborators(self) -> list[Collaborator]: - """The collaborators the crawler owns, which it enters and exits on every run.""" + """The collaborators the crawler owns, which it enters and exits on every run. + + A robots.txt check before the run can enter the session pool, which the next run exits. + """ return [] @cached_property @@ -727,7 +732,7 @@ def _stop_if_max_requests_count_exceeded(self) -> None: reason=f'The crawler has reached its limit of {self._max_requests_per_crawl} requests per crawl. ' ) - async def _get_session(self) -> Session: + async def _get_session(self) -> SessionInterface: """Take a session from the session pool.""" return await wait_for( self._session_pool.get_session, @@ -738,10 +743,10 @@ async def _get_session(self) -> Session: logger=self._logger, ) - async def _get_session_by_id(self, session_id: str) -> Session | None: + async def _get_session_by_id(self, session_id: str) -> SessionInterface | 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', @@ -1061,7 +1066,11 @@ async def _run_crawler(self) -> None: async with AsyncExitStack() as exit_stack: for context in contexts_to_enter: - await exit_stack.enter_async_context(context) + # A robots.txt check before the run can enter the crawler's own session pool. + if context is self._session_pool and self._session_pool.active: + exit_stack.push_async_exit(context) + else: + await exit_stack.enter_async_context(context) event_manager = self._service_locator.get_event_manager() event_manager.on(event=Event.MIGRATING, listener=self._pause_by_event) @@ -1107,6 +1116,9 @@ async def add_requests( wait_for_all_requests_to_be_added: If True, wait for all requests to be added before returning. wait_for_all_requests_to_be_added_timeout: Timeout for waiting for all requests to be added. `None` waits without a limit, zero cancels the requests still being added right away. + + Raises: + RuntimeError: If it has to fetch a robots.txt file while a session pool passed to the crawler isn't entered. """ allowed_requests = [] skipped = list[Request]() @@ -1516,7 +1528,7 @@ def _get_only_inner_most_exception(self, error: BaseException) -> BaseException: def _prepare_send_request_function( self, - session: Session, + session: SessionInterface, proxy_info: ProxyInfo | None, register_deferred_cleanup: Callable[[DeferredCleanupCallback], None], ) -> SendRequestFunction: @@ -1737,8 +1749,9 @@ async def __run_task_function(self, task_id: str) -> None: # noqa: ARG002 session = await self._get_session_by_id(request.session_id) if session is None: bound_session_unusable = True - # The failed request handler gets the pool's unusable session, or a retired stand-in once it's dropped. - session = self._session_pool._state.current_value.sessions.get(request.session_id) # noqa: SLF001 + # The failed request handler gets the unusable session from the built-in pool, or a retired stand-in. + if isinstance(self._session_pool, SessionPool): + session = self._session_pool._state.current_value.sessions.get(request.session_id) # noqa: SLF001 if session is None: session = Session(id=request.session_id, retired=True) else: @@ -2073,6 +2086,16 @@ async def _get_robots_txt_file_for_url(self, url: str) -> RobotsTxtFile | None: if robots_txt_file: return robots_txt_file + # `add_requests()` checks robots.txt before `run()` enters the session pool. The crawler enters its own pool + # here, and a passed pool has to be entered by then, as for `run()`. + if not self._session_pool.active: + if self._session_pool not in self._owned_collaborators: + raise RuntimeError( + f'The {type(self._session_pool).__name__} passed to the crawler is not active. Enter it with ' + '`async with` before adding requests to the crawler.' + ) + await self._session_pool.__aenter__() + # If not cached, fetch the robots.txt file try: robots_txt_file = await asyncio.wait_for( @@ -2091,24 +2114,16 @@ async def _get_robots_txt_file_for_url(self, url: str) -> RobotsTxtFile | None: async def _find_txt_file_for_url(self, url: str) -> RobotsTxtFile: """Find the robots.txt file for a given URL. - A failed attempt is repeated with a new proxy. When all attempts fail, the error of the last one is raised. + Every attempt fetches the file with the cookies and through the proxy of a session from the session pool. When + all attempts fail, the error of the last one is raised. Args: url: The URL whose domain will be used to locate and fetch the corresponding robots.txt file. """ for attempt in range(1, self._ROBOTS_TXT_MAX_ATTEMPTS + 1): try: - # The proxy comes from the configuration of the session pool rather than from a session, since `run()` - # checks its requests before it enters the pool. - # TODO: Decide how to guarantee that `self._session_pool` is usable here, so that robots.txt is fetched - # with a session, as in Crawlee JS. Until then, a proxy from `create_session_settings` or from - # `create_session_function` of the pool isn't used for robots.txt. The access to the private - # `_proxy_configuration` also has to go once the session pool becomes a protocol. - # https://github.com/apify/crawlee-python/issues/2137 - proxy_configuration = self._session_pool._proxy_configuration # noqa: SLF001 - proxy_info = await proxy_configuration.new_proxy_info() if proxy_configuration else None - - return await RobotsTxtFile.find(url, self._robots_txt_http_client, proxy_info=proxy_info) + session = await self._session_pool.get_session() + return await RobotsTxtFile.find(url, self._robots_txt_http_client, session=session) except Exception: if attempt == self._ROBOTS_TXT_MAX_ATTEMPTS: raise diff --git a/src/crawlee/crawlers/_playwright/_playwright_http_client.py b/src/crawlee/crawlers/_playwright/_playwright_http_client.py index 18aa5ce79c..91c30ae6fd 100644 --- a/src/crawlee/crawlers/_playwright/_playwright_http_client.py +++ b/src/crawlee/crawlers/_playwright/_playwright_http_client.py @@ -19,7 +19,7 @@ from crawlee._types import HttpHeaders, HttpMethod, HttpPayload from crawlee.http_clients import HttpResponse from crawlee.proxy_configuration import ProxyInfo - from crawlee.sessions import Session + from crawlee.sessions._types import SessionInterface _browser_page_context_var: contextvars.ContextVar[Page | None] = contextvars.ContextVar('browser_context', default=None) @@ -57,7 +57,7 @@ async def send_request( method: HttpMethod = 'GET', headers: HttpHeaders | dict[str, str] | None = None, payload: HttpPayload | None = None, - session: Session | None = None, + session: SessionInterface | None = None, cookies: SessionCookies | None = None, proxy_info: ProxyInfo | None = None, timeout: timedelta | Literal['default'] | None = 'default', diff --git a/src/crawlee/http_clients/_base.py b/src/crawlee/http_clients/_base.py index 65498c2418..f9928d666a 100644 --- a/src/crawlee/http_clients/_base.py +++ b/src/crawlee/http_clients/_base.py @@ -20,7 +20,7 @@ from crawlee._types import HttpMethod, HttpPayload from crawlee.proxy_configuration import ProxyInfo - from crawlee.sessions import Session + from crawlee.sessions._types import SessionInterface _MAX_REDIRECTS = 10 @@ -222,7 +222,7 @@ async def send_request( method: HttpMethod = 'GET', headers: HttpHeaders | dict[str, str] | None = None, payload: HttpPayload | None = None, - session: Session | None = None, + session: SessionInterface | None = None, cookies: SessionCookies | None = None, proxy_info: ProxyInfo | None = None, timeout: timedelta | Literal['default'] | None = 'default', @@ -242,15 +242,15 @@ async def send_request( method: The HTTP method to use. headers: The headers to include in the request. payload: The data to be sent as the request body. - session: The session whose cookies are sent and stored. Without a session or `cookies`, the response - cookies are kept only for the redirect chain of this request. + session: The session whose cookies are sent and stored, and whose proxy the request goes through. Without a + session or `cookies`, the response cookies are kept only for the redirect chain of this request. cookies: The cookies to send and store instead of the cookies of `session`. - proxy_info: The information about the proxy to be used. + proxy_info: The proxy to send the request through instead of the proxy of `session`. timeout: Maximum time allowed to receive the response, including all redirects, and to read its body. With `'default'`, the default timeout of the HTTP client applies. `None` disables the timeout, so the request runs until it's cancelled. ignore_tls_errors: Whether to ignore TLS certificate errors for this request. TLS errors are also ignored - when the client or `proxy_info` sets `ignore_tls_errors`. + when the client or the proxy of the request sets `ignore_tls_errors`. Raises: ProxyError: Raised if a proxy-related error occurs. @@ -272,6 +272,9 @@ async def send_request( if cookies is None: cookies = session.cookies if session is not None else SessionCookies() + if proxy_info is None and session is not None: + proxy_info = session.proxy_info + if proxy_info is not None and proxy_info.ignore_tls_errors: ignore_tls_errors = True diff --git a/src/crawlee/http_clients/_httpx.py b/src/crawlee/http_clients/_httpx.py index ca8e2e3792..e3a5e80bb2 100644 --- a/src/crawlee/http_clients/_httpx.py +++ b/src/crawlee/http_clients/_httpx.py @@ -25,7 +25,8 @@ from crawlee._types import HttpMethod, HttpPayload from crawlee.proxy_configuration import ProxyInfo - from crawlee.sessions import Session, SessionCookies + from crawlee.sessions import SessionCookies + from crawlee.sessions._types import SessionInterface logger = getLogger(__name__) @@ -140,9 +141,9 @@ def __init__( kept in sessions, so `cookies` is ignored. The `auth` and `params` arguments would reach every request of a redirect chain, so pass credentials in the `Authorization` header and the query in the URL instead. Redirects are followed by `send_request`, so `max_redirects` is ignored. Use `ignore_tls_errors` - instead of `verify`. The `proxy` argument covers only the requests made without a `ProxyInfo`, a - `ProxyConfiguration` takes precedence over it. The `limits` argument applies per proxy and TLS setting, - because each combination gets a connection pool of its own. + instead of `verify`. The `proxy` argument covers only the requests made without a `ProxyInfo`. The + `limits` argument applies per proxy and TLS setting, because each combination gets a connection pool + of its own. """ super().__init__( follow_redirects=follow_redirects, @@ -197,7 +198,7 @@ async def send_request( method: HttpMethod = 'GET', headers: HttpHeaders | dict[str, str] | None = None, payload: HttpPayload | None = None, - session: Session | None = None, + session: SessionInterface | None = None, cookies: SessionCookies | None = None, proxy_info: ProxyInfo | None = None, timeout: timedelta | Literal['default'] | None = 'default', diff --git a/src/crawlee/proxy_configuration.py b/src/crawlee/proxy_configuration.py index 1f944ee007..9b16bb0345 100644 --- a/src/crawlee/proxy_configuration.py +++ b/src/crawlee/proxy_configuration.py @@ -22,8 +22,8 @@ class ProxyInfo: """Provides information about a proxy connection that is used for requests. The persisted session state keeps only the fields of `ProxyInfo`, with `'**********'` in place of the password. A - subclass restores its own fields in `ProxyConfiguration.new_proxy_info`. `repr` also shows `'**********'` in place - of the password. + proxy configuration that returns a subclass restores the extra fields of the subclass in `new_proxy_info`. `repr` + also shows `'**********'` in place of the password. """ # `repr=False` keeps the password out of the `repr` that a dataclass subclass generates for itself. @@ -48,7 +48,8 @@ class ProxyInfo: ignore_tls_errors: bool = False """Whether the proxy intercepts HTTPS traffic, so that `HttpClient.send_request` and the browser contexts of `PlaywrightBrowserController` ignore TLS certificate errors for the requests sent through it. `ProxyConfiguration` - never sets it, so a subclass that knows its proxy intercepts HTTPS sets it in `new_proxy_info`.""" + never sets it, so a subclass or another proxy configuration that knows its proxy intercepts HTTPS sets it in + `new_proxy_info`.""" @property def has_redacted_password(self) -> bool: @@ -61,17 +62,40 @@ def __repr__(self) -> str: return f'{type(self).__name__}(url={redact_proxy_url(self.url)!r}, {", ".join(values)})' +@docs_group('Configuration') +class ProxyConfigurationInterface(Protocol): + """The contract between a session pool and the source of the proxies of its sessions. + + `ProxyConfiguration` is the built-in implementation. Anything matching this contract can take its place, such as a + client of a proxy provider. + """ + + async def new_proxy_info(self, proxy_info: ProxyInfo | None, /) -> ProxyInfo | None: + """Get the proxy of a session that the pool creates or restores. + + Args: + proxy_info: The proxy that the session already has, such as the saved proxy of a restored session, or `None` + for a session without one. The persisted state doesn't store proxy passwords, so a restored proxy that + had a password `has_redacted_password`. + + Returns: + The proxy of the session, or `None` for no proxy. For a passed proxy, return it or an equivalent one that + works in the current environment, so that the session keeps its IP address. If it `has_redacted_password`, + put its password back into both `url` and `password`, or return another proxy, since the pool drops a + restored session whose proxy still `has_redacted_password`. + """ + + @docs_group('Configuration') class ProxyConfiguration: """Configures connection to a proxy server with the provided options. Proxy servers are used to prevent target websites from blocking your crawlers based on IP address rate limits or blacklists. Setting proxy configuration in your crawlers automatically configures them to use the selected proxies - for all connections. You can get information about the currently used proxy by inspecting the {@apilink ProxyInfo} - property in your crawler's page function. There, you can inspect the proxy's URL and other attributes. + for all connections. The request handler gets the proxy of the current request in `context.proxy_info`, with its URL + and other attributes. - If you want to use your own proxies, use the {@apilink ProxyConfigurationOptions.proxyUrls} option. Your list of - proxy URLs will be rotated by the configuration if this option is provided. + To use your own proxies, pass their URLs in `proxy_urls`, and the configuration rotates them. """ def __init__( diff --git a/src/crawlee/sessions/_session_pool.py b/src/crawlee/sessions/_session_pool.py index 2ebfc0a21b..6a4cff2edc 100644 --- a/src/crawlee/sessions/_session_pool.py +++ b/src/crawlee/sessions/_session_pool.py @@ -22,7 +22,7 @@ from types import TracebackType from crawlee.events import EventManager - from crawlee.proxy_configuration import ProxyConfiguration + from crawlee.proxy_configuration import ProxyConfigurationInterface from crawlee.storages import KeyValueStore logger = getLogger(__name__) @@ -48,7 +48,7 @@ def __init__( max_pool_size: int = 1000, create_session_settings: SessionOptions | None = None, create_session_function: CreateSessionFunctionType | None = None, - proxy_configuration: ProxyConfiguration | None = None, + proxy_configuration: ProxyConfigurationInterface | None = None, event_manager: EventManager | None = None, persistence_enabled: bool = True, persist_state_kvs_name: str | None = None, @@ -72,13 +72,14 @@ def __init__( options, so that a restored session keeps its state. The persisted state doesn't store proxy passwords, so put the password back into both `url` and `password` of a restored `proxy_info` that still `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: A `ProxyConfiguration`, or another proxy configuration implementation, that 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 or of the options passed to `add_session`. A `Session` passed to + `add_session` keeps its own `proxy_info`. With a `ProxyConfiguration`, 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 +89,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 +99,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 +137,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,19 +200,22 @@ 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: logger.warning( 'Dropped %s restored session(s) whose proxy passwords could not be recovered, since ' - 'the persisted state does not store them. Pass a `proxy_configuration` with their ' - 'proxy URLs to the session pool to keep them.', + 'the persisted state does not store them. To keep them, pass the session pool a ' + '`proxy_configuration` that restores the passwords, such as a `ProxyConfiguration` ' + 'with their proxy URLs.', dropped_session_count, ) self._restored_sessions_recreated = True @@ -237,6 +249,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 +274,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 +358,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) @@ -351,7 +407,7 @@ async def _build_session(self, options: SessionOptions) -> Session: merged_options = self._session_settings.copy() merged_options.update(options) - if self._proxy_configuration: + if self._proxy_configuration is not None: merged_options['proxy_info'] = await self._proxy_configuration.new_proxy_info( merged_options.get('proxy_info') ) @@ -362,12 +418,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 +461,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/src/crawlee/sessions/_types.py b/src/crawlee/sessions/_types.py new file mode 100644 index 0000000000..c400cb795e --- /dev/null +++ b/src/crawlee/sessions/_types.py @@ -0,0 +1,70 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Protocol, overload + +from crawlee._utils.context import Collaborator +from crawlee._utils.docs import docs_group + +if TYPE_CHECKING: + from crawlee.proxy_configuration import ProxyInfo + from crawlee.sessions._cookies import SessionCookies + + +@docs_group('Session management') +class SessionInterface(Protocol): + """The contract between a crawler and the session it handles a request with. + + A session stands for one identity of the crawler: the cookies it sends and the proxy it uses. `Session` is the + default implementation. + """ + + @property + def id(self) -> str: + """The identifier of the session, unique within its pool.""" + + @property + def cookies(self) -> SessionCookies: + """The cookies that the requests of the session send and store.""" + + @property + def proxy_info(self) -> ProxyInfo | None: + """The proxy that the requests of the session go through, or `None` for no proxy.""" + + @property + def is_usable(self) -> bool: + """Whether the session can handle another request.""" + + def mark_good(self) -> None: + """Record that a request handled with the session succeeded.""" + + def mark_bad(self) -> None: + """Record that a request handled with the session failed for a reason that doesn't prove a block.""" + + def retire(self) -> None: + """Mark the session as blocked, so that it's no longer used.""" + + +@docs_group('Session management') +class SessionPoolInterface(Collaborator, Protocol): + """The contract between a crawler and the pool it takes its sessions from. + + `SessionPool` is the default implementation. Anything matching this contract can take its place, such as a pool + shared between processes. An implementation is an async context manager, and a crawler refuses to run with a passed + one that isn't entered. + """ + + @overload + async def get_session(self, session_id: None = None) -> SessionInterface: ... + + @overload + async def get_session(self, session_id: str) -> SessionInterface | None: ... + + async def get_session(self, session_id: str | None = None) -> SessionInterface | None: + """Get a session for a request. + + Args: + session_id: The ID of the session that the request is bound to. Without it, the pool picks the session. + + Returns: + The session. With `session_id`, `None` if the pool has no usable session with this ID. + """ 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..4353f41e4a 100644 --- a/tests/integration/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py +++ b/tests/integration/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py @@ -32,7 +32,7 @@ from crawlee.crawlers._adaptive_playwright._rendering_type_predictor import DefaultRenderingTypePredictor from crawlee.errors import RequestThrottledError from crawlee.http_clients import HttpClient, HttpResponse, ImpitHttpClient -from crawlee.sessions import SessionPool +from crawlee.sessions import Session, SessionPool from crawlee.statistics import Statistics from crawlee.storage_backends import SqlStorageBackend from crawlee.storages import KeyValueStore, RequestQueue @@ -1083,7 +1083,7 @@ async def request_handler(context: AdaptivePlaywrightCrawlingContext) -> None: nonlocal used_session_id used_session_id = context.session.id - context.session.user_data['session_state'] = True + cast('Session', context.session).user_data['session_state'] = True try: # `page` is only available in the browser sub crawler, static crawling raises here. @@ -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/integration/crawlers/_playwright/test_playwright_crawler.py b/tests/integration/crawlers/_playwright/test_playwright_crawler.py index bd545fe800..96d9737d1f 100644 --- a/tests/integration/crawlers/_playwright/test_playwright_crawler.py +++ b/tests/integration/crawlers/_playwright/test_playwright_crawler.py @@ -451,7 +451,7 @@ async def test_isolation_cookies(*, use_incognito_pages: bool, server_url: URL) @crawler.router.default_handler async def handler(context: PlaywrightCrawlingContext) -> None: sessions_ids.append(context.session.id) - sessions[context.session.id] = context.session + sessions[context.session.id] = cast('Session', context.session) response_data = json.loads(await context.response.text()) response_cookies[context.session.id] = response_data.get('cookies') @@ -1052,7 +1052,7 @@ async def test_send_request_cookie_update_survives_handler(server_url: URL) -> N @crawler.router.default_handler async def request_handler(context: PlaywrightCrawlingContext) -> None: assert context.session is not None - sessions.append(context.session) + sessions.append(cast('Session', context.session)) await context.send_request(str(server_url.with_path('set_cookies').extend_query(token='B'))) async with http_client: @@ -1658,5 +1658,5 @@ async def handler(context: PlaywrightCrawlingContext) -> None: failed_request_handler.assert_not_called() record_pacing_signal.assert_called_once() assert handled[0].request.retry_count == 0 - session = handled[0].session + session = cast('Session', handled[0].session) assert session.error_score == 0 diff --git a/tests/unit/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py b/tests/unit/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py index 6f0ae32cf6..b26158b2c4 100644 --- a/tests/unit/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py +++ b/tests/unit/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py @@ -16,6 +16,7 @@ from crawlee.crawlers._adaptive_playwright._rendering_type_predictor import DefaultRenderingTypePredictor from crawlee.events import Event, EventManager, EventPersistStateData from crawlee.proxy_configuration import ProxyConfiguration +from crawlee.sessions import SessionPool from crawlee.statistics import Statistics from crawlee.storage_backends import MemoryStorageBackend from crawlee.storages import KeyValueStore @@ -122,6 +123,7 @@ def test_proxy_configuration_reaches_session_pool() -> None: proxy_configuration = ProxyConfiguration(proxy_urls=['http://proxy.placeholder.com:8000']) crawler = AdaptivePlaywrightCrawler.with_parsel_static_parser(proxy_configuration=proxy_configuration) + assert isinstance(crawler._session_pool, SessionPool) assert crawler._session_pool._proxy_configuration is proxy_configuration diff --git a/tests/unit/crawlers/_basic/test_basic_crawler.py b/tests/unit/crawlers/_basic/test_basic_crawler.py index b03771aad5..a4d0926244 100644 --- a/tests/unit/crawlers/_basic/test_basic_crawler.py +++ b/tests/unit/crawlers/_basic/test_basic_crawler.py @@ -12,7 +12,7 @@ from asyncio import Future from collections import Counter from concurrent.futures import ProcessPoolExecutor -from contextlib import suppress +from contextlib import nullcontext, suppress from dataclasses import dataclass from datetime import UTC, datetime, timedelta from itertools import chain, product, repeat @@ -48,7 +48,7 @@ LocalEventManager, ) from crawlee.http_clients import HttpClient, HttpResponse, ImpitHttpClient -from crawlee.proxy_configuration import ProxyConfiguration +from crawlee.proxy_configuration import ProxyConfiguration, ProxyInfo from crawlee.request_loaders import ( FinishedStatus, MinIntervalSignal, @@ -63,6 +63,7 @@ ) from crawlee.router import Router from crawlee.sessions import Session, SessionCookies, SessionPool +from crawlee.sessions._types import SessionInterface, SessionPoolInterface from crawlee.statistics import FinalStatistics, Statistics, StatisticsState from crawlee.storage_backends import FileSystemStorageBackend, MemoryStorageBackend from crawlee.storages import Dataset, KeyValueStore, RequestQueue @@ -70,7 +71,7 @@ from tests._utils import open_throttler_held_until_reclaim, poll_until_condition if TYPE_CHECKING: - from collections.abc import Sequence + from collections.abc import Callable, Sequence from pathlib import Path from crawlee._types import JsonSerializable @@ -531,7 +532,7 @@ async def test_session_retired_every_attempt() -> None: sessions = list[Session]() async def request_handler(context: BasicCrawlingContext) -> None: - sessions.append(context.session) + sessions.append(cast('Session', context.session)) raise SessionError('blocked') session_pool = SessionPool(max_pool_size=1) @@ -554,14 +555,14 @@ async def test_session_retire_order() -> None: observe = Mock() async def request_handler(context: BasicCrawlingContext) -> None: - sessions.append(context.session) + sessions.append(cast('Session', context.session)) raise SessionError('blocked') async def error_handler(context: BasicCrawlingContext, error: Exception) -> None: - observe('error_handler', retired=context.session.retired) + observe('error_handler', retired=cast('Session', context.session).retired) async def failed_request_handler(context: BasicCrawlingContext, error: Exception) -> None: - observe('failed_request_handler', retired=context.session.retired) + observe('failed_request_handler', retired=cast('Session', context.session).retired) reclaim_request = queue.reclaim_request @@ -1521,12 +1522,14 @@ def test_default_session_pool_uses_crawler_id(crawler_id: str | None, expected_i SessionPool() crawler = BasicCrawler(id=crawler_id) + assert isinstance(crawler._session_pool, SessionPool) assert crawler._session_pool._id == expected_id async def test_default_session_pool_persists_to_crawler_store() -> None: """The session pool a crawler creates persists to the crawler's key-value store.""" crawler = BasicCrawler(request_handler=AsyncMock(), storage_backend=MemoryStorageBackend()) + assert isinstance(crawler._session_pool, SessionPool) key = f'CRAWLEE_SESSION_POOL_STATE_{crawler._session_pool._id}' await crawler.run(['https://a.placeholder.com']) @@ -1959,7 +1962,8 @@ async def test_repeated_run_keeps_own_pool() -> None: @crawler.router.default_handler async def handler(_context: BasicCrawlingContext) -> None: - pool_session_ids.append(set(crawler._session_pool.get_state(as_dict=False).sessions)) + session_pool = cast('SessionPool', crawler._session_pool) + pool_session_ids.append(set(session_pool.get_state(as_dict=False).sessions)) await crawler.run(['https://a.placeholder.com']) await crawler.run(['https://b.placeholder.com']) @@ -3552,7 +3556,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 @@ -3587,13 +3591,27 @@ async def error_req_hook(context: BasicCrawlingContext, error: Exception) -> Non assert error_handler_mock.call_count == 1 -async def test_missing_bound_session_gives_retired_stand_in() -> None: +@pytest.mark.parametrize( + 'create_crawler_kwargs', + [ + pytest.param( + lambda: {'proxy_configuration': ProxyConfiguration(proxy_urls=['http://proxy.placeholder.com:8000'])}, + id='default pool', + ), + pytest.param( + lambda: { + 'session_pool': Mock(spec=SessionPoolInterface, active=True, get_session=AsyncMock(return_value=None)) + }, + id='custom pool', + ), + ], +) +async def test_missing_bound_session_gives_retired_stand_in( + create_crawler_kwargs: Callable[[], dict[str, Any]], +) -> None: """Test that the failed request handler gets a retired session without a proxy for a missing bound session.""" failed_request_handler = AsyncMock() - crawler = BasicCrawler( - request_handler=AsyncMock(), - proxy_configuration=ProxyConfiguration(proxy_urls=['http://proxy.placeholder.com:8000']), - ) + crawler = BasicCrawler(request_handler=AsyncMock(), **create_crawler_kwargs()) crawler.failed_request_handler(failed_request_handler) await crawler.run([Request.from_url('https://a.placeholder.com', session_id='missing')]) @@ -3650,6 +3668,20 @@ async def test_unusable_bound_session_reaches_failed_request_handler() -> None: assert context.session is session +async def test_custom_session_pool_serves_sessions() -> None: + """Test that the crawler handles a request with a session from a passed session pool implementation.""" + session = Mock(spec=SessionInterface, id='custom', cookies=SessionCookies(), proxy_info=None, is_usable=True) + session_pool = Mock(spec=SessionPoolInterface, active=True, get_session=AsyncMock(return_value=session)) + request_handler = AsyncMock() + crawler = BasicCrawler(session_pool=session_pool, request_handler=request_handler) + + await crawler.run(['https://a.placeholder.com']) + + request_handler.assert_awaited_once() + assert request_handler.call_args.args[0].session is session + session.mark_good.assert_called_once() + + async def test_handles_session_error_in_failed_request_handler() -> None: crawler = BasicCrawler(max_request_retries=0) handler_requests = set() @@ -4133,16 +4165,18 @@ async def error_handler(context: BasicCrawlingContext, error: Exception) -> None if isinstance(context.request.user_data['request_state'], list): context.request.user_data['request_state'].append('error') - if isinstance(context.session.user_data['session_state'], list): - context.session.user_data['session_state'].append('error') + session = cast('Session', context.session) + if isinstance(session.user_data['session_state'], list): + session.user_data['session_state'].append('error') context.session.cookies['error'] = 'yes' @crawler.router.default_handler async def handler(context: BasicCrawlingContext) -> None: if isinstance(context.request.user_data['request_state'], list): context.request.user_data['request_state'].append(f'modified_{context.request.retry_count}') - if isinstance(context.session.user_data['session_state'], list): - context.session.user_data['session_state'].append(f'modified_{context.request.retry_count}') + session = cast('Session', context.session) + if isinstance(session.user_data['session_state'], list): + session.user_data['session_state'].append(f'modified_{context.request.retry_count}') context.session.cookies[f'modified_{context.request.retry_count}'] = 'yes' if context.request.retry_count == 0: @@ -4153,7 +4187,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' @@ -4904,35 +4938,49 @@ def _create_robots_txt_http_client() -> Mock: @pytest.mark.parametrize( - 'via_session_pool', - [pytest.param(False, id='crawler option'), pytest.param(True, id='passed session pool')], + 'create_proxy_kwargs', + [ + pytest.param( + lambda: {'proxy_configuration': ProxyConfiguration(proxy_urls=['http://proxy.placeholder.com:8000'])}, + id='crawler option', + ), + pytest.param( + lambda: { + 'session_pool': SessionPool( + proxy_configuration=ProxyConfiguration(proxy_urls=['http://proxy.placeholder.com:8000']) + ) + }, + id='passed session pool', + ), + pytest.param( + lambda: { + 'session_pool': SessionPool( + create_session_settings={ + 'proxy_info': ProxyInfo( + url='http://proxy.placeholder.com:8000', + scheme='http', + hostname='proxy.placeholder.com', + port=8000, + ) + } + ) + }, + id='session settings', + ), + ], ) -async def test_robots_txt_fetched_through_proxy(*, via_session_pool: bool) -> None: - """The robots.txt file is fetched through the proxy configured on the crawler or on its passed session pool.""" +async def test_robots_txt_fetched_through_proxy(create_proxy_kwargs: Callable[[], dict[str, Any]]) -> None: + """The robots.txt file is fetched through the proxy of a session from the crawler's own or a passed session pool.""" http_client = _create_robots_txt_http_client() - proxy_configuration = ProxyConfiguration(proxy_urls=['http://proxy.placeholder.com:8000']) - proxy_kwargs: dict[str, Any] = ( - {'session_pool': SessionPool(proxy_configuration=proxy_configuration)} - if via_session_pool - else {'proxy_configuration': proxy_configuration} - ) + proxy_kwargs = create_proxy_kwargs() crawler = BasicCrawler(http_client=http_client, respect_robots_txt_file=True, **proxy_kwargs) - assert await crawler._is_allowed_based_on_robots_txt_file('https://site.placeholder.com/private') is False + async with proxy_kwargs.get('session_pool') or nullcontext(): + assert await crawler._is_allowed_based_on_robots_txt_file('https://site.placeholder.com/private') is False http_client.send_request.assert_awaited_once() assert http_client.send_request.call_args.args == ('https://site.placeholder.com/robots.txt',) - assert http_client.send_request.call_args.kwargs['proxy_info'].url == 'http://proxy.placeholder.com:8000' - - -async def test_robots_txt_fetched_without_proxy_when_not_configured() -> None: - """Without a proxy configuration, the robots.txt file is fetched directly.""" - http_client = _create_robots_txt_http_client() - crawler = BasicCrawler(http_client=http_client, respect_robots_txt_file=True) - - assert await crawler._is_allowed_based_on_robots_txt_file('https://site.placeholder.com/private') is False - - http_client.send_request.assert_awaited_once() + assert http_client.send_request.call_args.kwargs['session'].proxy_info.url == 'http://proxy.placeholder.com:8000' assert http_client.send_request.call_args.kwargs['proxy_info'] is None @@ -4954,7 +5002,7 @@ async def never_respond(*_: Any, **__: Any) -> None: async def test_robots_txt_fetch_retried_with_new_proxy() -> None: - """A failed robots.txt fetch is repeated with the next proxy.""" + """A failed robots.txt fetch is repeated with a new session, which the pool creates while it has room.""" proxy_urls: list[str | None] = ['http://proxy-1.placeholder.com:8000', 'http://proxy-2.placeholder.com:8000'] http_client = _create_robots_txt_http_client() http_client.send_request.side_effect = [RuntimeError('The proxy failed.'), http_client.send_request.return_value] @@ -4966,7 +5014,7 @@ async def test_robots_txt_fetch_retried_with_new_proxy() -> None: assert await crawler._is_allowed_based_on_robots_txt_file('https://site.placeholder.com/private') is False - assert [call.kwargs['proxy_info'].url for call in http_client.send_request.call_args_list] == proxy_urls + assert [call.kwargs['session'].proxy_info.url for call in http_client.send_request.call_args_list] == proxy_urls async def test_robots_txt_failed_fetch_allows_all_urls() -> None: @@ -4981,6 +5029,28 @@ async def test_robots_txt_failed_fetch_allows_all_urls() -> None: assert http_client.send_request.await_count == BasicCrawler._ROBOTS_TXT_MAX_ATTEMPTS +async def test_robots_txt_check_enters_own_pool() -> None: + """`run()` checks its requests against robots.txt with its own session pool, and exits the pool.""" + http_client = _create_robots_txt_http_client() + request_handler = AsyncMock() + crawler = BasicCrawler(http_client=http_client, request_handler=request_handler, respect_robots_txt_file=True) + + await crawler.run(['https://site.placeholder.com/private', 'https://site.placeholder.com/public']) + + handled_urls = [handler_call.args[0].request.url for handler_call in request_handler.call_args_list] + assert handled_urls == ['https://site.placeholder.com/public'] + assert not crawler._session_pool.active + + +async def test_robots_txt_needs_entered_session_pool() -> None: + """`add_requests()` raises when it fetches robots.txt with a passed session pool that isn't entered.""" + http_client = _create_robots_txt_http_client() + crawler = BasicCrawler(http_client=http_client, session_pool=SessionPool(), respect_robots_txt_file=True) + + with pytest.raises(RuntimeError, match='SessionPool passed to the crawler is not active'): + await crawler.add_requests(['https://site.placeholder.com/private']) + + async def test_robots_txt_proxy_lookup_error_allows_all_urls() -> None: """An error from `new_url_function` stays inside the robots.txt check, and nothing is fetched without a proxy.""" http_client = _create_robots_txt_http_client() diff --git a/tests/unit/crawlers/_http/test_http_crawler.py b/tests/unit/crawlers/_http/test_http_crawler.py index d2ccfb793b..adb1399579 100644 --- a/tests/unit/crawlers/_http/test_http_crawler.py +++ b/tests/unit/crawlers/_http/test_http_crawler.py @@ -2,7 +2,7 @@ import asyncio from datetime import timedelta -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, cast from unittest.mock import AsyncMock, Mock, call import pytest @@ -181,7 +181,7 @@ async def handler(context: HttpCrawlingContext) -> None: failed_request_handler.assert_not_called() request = handled[0].request assert request.retry_count == 0 - session = handled[0].session + session = cast('Session', handled[0].session) assert session.error_score == 0 assert session.is_usable diff --git a/tests/unit/crawlers/_playwright/test_playwright_crawler.py b/tests/unit/crawlers/_playwright/test_playwright_crawler.py index a941901c03..fd772445f6 100644 --- a/tests/unit/crawlers/_playwright/test_playwright_crawler.py +++ b/tests/unit/crawlers/_playwright/test_playwright_crawler.py @@ -17,8 +17,9 @@ BasicCrawler, PlaywrightCrawler, ) -from crawlee.http_clients import ImpitHttpClient +from crawlee.http_clients import HttpResponse, ImpitHttpClient from crawlee.proxy_configuration import ProxyConfiguration +from crawlee.sessions import SessionPool if TYPE_CHECKING: from crawlee.crawlers import PlaywrightCrawlingContext @@ -100,7 +101,29 @@ async def test_robots_txt_fetched_through_proxy(monkeypatch: pytest.MonkeyPatch) send_request.assert_awaited_once() assert send_request.call_args.args == ('https://site.placeholder.com/robots.txt',) - assert send_request.call_args.kwargs['proxy_info'].url == proxy_url + assert send_request.call_args.kwargs['session'].proxy_info.url == proxy_url + + +async def test_robots_txt_cookies_reach_session(monkeypatch: pytest.MonkeyPatch) -> None: + """The cookies of the robots.txt response are stored in the session, even with `save_response_cookies=False`.""" + robots_url = 'https://site.placeholder.com/robots.txt' + response = mock.MagicMock( + spec=HttpResponse, + status_code=200, + headers={}, + url=robots_url, + headers_set_cookie=['sid=1'], + read=mock.AsyncMock(return_value=b'User-agent: *\nDisallow: /private'), + ) + monkeypatch.setattr(ImpitHttpClient, '_fetch', mock.AsyncMock(return_value=response)) + session_pool = SessionPool(max_pool_size=1) + crawler = PlaywrightCrawler(session_pool=session_pool, save_response_cookies=False, respect_robots_txt_file=True) + + async with session_pool: + await crawler._is_allowed_based_on_robots_txt_file('https://site.placeholder.com/private') + session = await session_pool.get_session() + + assert session.cookies['sid'] == '1' def test_robots_txt_http_client_is_cleaned_up_with_crawler() -> None: diff --git a/tests/unit/http_clients/test_http_clients.py b/tests/unit/http_clients/test_http_clients.py index cb365ba98f..621b52ac6e 100644 --- a/tests/unit/http_clients/test_http_clients.py +++ b/tests/unit/http_clients/test_http_clients.py @@ -314,6 +314,46 @@ async def test_ignore_tls_errors_reaches_fetch( assert fetch.call_args.kwargs['ignore_tls_errors'] is expected_flag +@pytest.mark.parametrize( + 'client_class', + [ + pytest.param(ImpitHttpClient, id='impit'), + pytest.param(HttpxHttpClient, id='httpx'), + pytest.param(CurlImpersonateHttpClient, id='curl'), + ], +) +@pytest.mark.parametrize( + 'passed_proxy_info', + [ + pytest.param(None, id='proxy of the session'), + pytest.param( + ProxyInfo(url='http://passed.com:8000', scheme='http', hostname='passed.com', port=8000), + id='passed proxy wins', + ), + ], +) +async def test_session_proxy_reaches_fetch( + monkeypatch: pytest.MonkeyPatch, + client_class: type[HttpClient], + passed_proxy_info: ProxyInfo | None, +) -> None: + """Test that `send_request` goes through the proxy of the session, with its TLS flag, unless a proxy is passed.""" + url = 'https://example.com/' + response = Mock(spec=HttpResponse, status_code=200, headers={}, url=url, headers_set_cookie=[]) + fetch = AsyncMock(return_value=response) + client = client_class() + monkeypatch.setattr(client, '_fetch', fetch) + session_proxy_info = ProxyInfo( + url='http://session.com:8000', scheme='http', hostname='session.com', port=8000, ignore_tls_errors=True + ) + expected_proxy_info = passed_proxy_info or session_proxy_info + + await client.send_request(url, session=Session(proxy_info=session_proxy_info), proxy_info=passed_proxy_info) + + assert fetch.call_args.kwargs['proxy_info'] is expected_proxy_info + assert fetch.call_args.kwargs['ignore_tls_errors'] is expected_proxy_info.ignore_tls_errors + + async def test_enter_during_exit_raises(monkeypatch: pytest.MonkeyPatch) -> None: """A client can't be entered again until its exit has cleaned it up.""" http_client = ImpitHttpClient() diff --git a/tests/unit/sessions/test_session_pool.py b/tests/unit/sessions/test_session_pool.py index db55bd5901..e32fc28aea 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 @@ -12,13 +14,13 @@ from crawlee import service_locator from crawlee.events import EventManager from crawlee.events._types import Event, EventPersistStateData -from crawlee.proxy_configuration import ProxyConfiguration, ProxyInfo +from crawlee.proxy_configuration import ProxyConfiguration, ProxyConfigurationInterface, ProxyInfo from crawlee.sessions import Session, SessionOptions, SessionPool from crawlee.sessions._models import SessionPoolModel 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=ProxyConfigurationInterface) + 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=ProxyConfigurationInterface) + 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 @@ -171,6 +389,17 @@ async def test_proxy_configuration_sets_session_proxy() -> None: assert [proxy_info.url for proxy_info in factory_proxy_infos] == proxy_urls +async def test_falsy_proxy_configuration_sets_proxy() -> None: + """Test that the pool takes proxies from a proxy configuration that is falsy, such as an empty sized one.""" + proxy_info = ProxyInfo(url='http://proxy.com:8000', scheme='http', hostname='proxy.com', port=8000) + proxy_configuration = Mock(new_proxy_info=AsyncMock(return_value=proxy_info), __bool__=Mock(return_value=False)) + + async with SessionPool(proxy_configuration=proxy_configuration, persistence_enabled=False) as sp: + session = await sp.get_session() + + assert session.proxy_info == proxy_info + + async def test_restored_session_is_recreated_by_factory() -> None: """Test that a restored session goes through the factory with its state and the refreshed persisted proxy.""" persisted_proxy_info = ProxyInfo( @@ -191,7 +420,7 @@ async def test_restored_session_is_recreated_by_factory() -> None: ) as sp: await sp.get_session() - proxy_configuration = Mock(spec=ProxyConfiguration) + proxy_configuration = Mock(spec=ProxyConfigurationInterface) proxy_configuration.new_proxy_info = AsyncMock(return_value=refreshed_proxy_info) create_session_function = Mock(side_effect=lambda options: Session(**options)) @@ -203,7 +432,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 +459,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 +524,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 +556,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 +622,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 +634,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 +682,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 +715,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 +730,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 +806,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 +865,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 +986,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 +1002,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 +1081,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()