-
Notifications
You must be signed in to change notification settings - Fork 790
fix(httpx): honor session cookies across HTTP client request paths #2104
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Ayush7614
wants to merge
7
commits into
apify:master
Choose a base branch
from
Ayush7614:fix/http-client-session-cookie-correctness
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
91e9be4
fix: honor session cookies across HTTP client request paths
Ayush7614 dccf1e7
fix: address Impit cookie review feedback
Ayush7614 086b115
fix: address remaining Impit review nits
Ayush7614 d4f5fae
fix: address httpx redirect cookies and Impit cache review
Ayush7614 6aaadc4
test: assert httpx headers come from a single generate() call
Ayush7614 6b2c8c8
fix(httpx): keep clients shared per proxy for session cookies
Ayush7614 bf9a8d0
test: keep HttpxHttpClient type for client-cache assertion
Ayush7614 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,6 +4,7 @@ | |
| from contextlib import asynccontextmanager | ||
| from logging import DEBUG, WARNING, getLogger | ||
| from typing import TYPE_CHECKING, Any, cast | ||
| from urllib.request import Request as UrllibRequest | ||
|
|
||
| import httpx | ||
| from typing_extensions import override | ||
|
|
@@ -20,6 +21,7 @@ | |
| if TYPE_CHECKING: | ||
| from collections.abc import AsyncGenerator, AsyncIterator | ||
| from datetime import timedelta | ||
| from http.cookiejar import CookieJar | ||
| from ssl import SSLContext | ||
|
|
||
| from crawlee import Request | ||
|
|
@@ -63,26 +65,41 @@ async def read_stream(self) -> AsyncIterator[bytes]: | |
|
|
||
|
|
||
| class _HttpxTransport(httpx.AsyncHTTPTransport): | ||
| """HTTP transport adapter that stores response cookies in a `Session`. | ||
| """HTTP transport adapter that keeps session cookies off the shared `httpx` client. | ||
|
|
||
| This transport adapter modifies the handling of HTTP requests to update the session cookies | ||
| based on the response cookies, ensuring that the cookies are stored in the session object | ||
| rather than the `HTTPX` client itself. | ||
| Outbound cookies are applied per hop (including redirects) from the jar in request extensions, | ||
| because httpx strips the `Cookie` header on redirect and rebuilds it from the client jar. Response | ||
| `Set-Cookie` values are stored on the session and removed from the response so the shared client | ||
| jar stays empty and reusable across sessions. | ||
| """ | ||
|
|
||
| @override | ||
| async def handle_async_request(self, request: httpx.Request) -> httpx.Response: | ||
| if cookie_jar := cast('CookieJar | None', request.extensions.get('crawlee_cookie_jar')): | ||
| self._apply_cookie_header(request, cookie_jar) | ||
|
|
||
| response = await super().handle_async_request(request) | ||
| response.request = request | ||
|
|
||
| if session := cast('Session', request.extensions.get('crawlee_session')): | ||
| if session := cast('Session | None', request.extensions.get('crawlee_session')): | ||
| session.cookies.store_cookies(list(response.cookies.jar)) | ||
|
|
||
| if 'Set-Cookie' in response.headers: | ||
| del response.headers['Set-Cookie'] | ||
|
|
||
| return response | ||
|
|
||
| @staticmethod | ||
| def _apply_cookie_header(request: httpx.Request, jar: CookieJar) -> None: | ||
| """Set the Cookie header from a jar for the current request URL.""" | ||
| urllib_request = UrllibRequest(str(request.url), headers=dict(request.headers)) # noqa: S310 | ||
| jar.add_cookie_header(urllib_request) | ||
| cookie_header = urllib_request.get_header('Cookie') | ||
| if cookie_header: | ||
| request.headers['cookie'] = cookie_header | ||
| else: | ||
| request.headers.pop('cookie', None) | ||
|
|
||
|
|
||
| @docs_group('HTTP clients') | ||
| class HttpxHttpClient(HttpClient): | ||
|
|
@@ -158,16 +175,15 @@ async def crawl( | |
| timeout: timedelta | None = None, | ||
| ) -> HttpCrawlingResult: | ||
| client = self._get_client(proxy_info.url if proxy_info else None) | ||
| headers = self._combine_headers(request.headers) | ||
|
|
||
| http_request = client.build_request( | ||
| http_request = self._build_request( | ||
| client=client, | ||
| url=request.url, | ||
| method=request.method, | ||
| headers=headers, | ||
| content=request.payload, | ||
| cookies=session.cookies.jar if session else None, | ||
| extensions={'crawlee_session': session if self._persist_cookies_per_session else None}, | ||
| timeout=timeout.total_seconds() if timeout is not None else httpx.USE_CLIENT_DEFAULT, | ||
| headers=request.headers, | ||
| payload=request.payload, | ||
| session=session, | ||
| timeout=httpx.Timeout(timeout.total_seconds()) if timeout is not None else None, | ||
| ) | ||
|
|
||
| try: | ||
|
|
@@ -284,17 +300,22 @@ def _build_request( | |
| method=method, | ||
| headers=dict(headers) if headers else None, | ||
| content=payload, | ||
| extensions={'crawlee_session': session if self._persist_cookies_per_session else None}, | ||
| cookies=session.cookies.jar if session else None, | ||
|
vdusek marked this conversation as resolved.
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. With this new approach that uses transport, Also, the session is already being passed to the transport. Use the session's |
||
| extensions={ | ||
| # Used by the transport to re-apply cookies on every hop (httpx strips Cookie on redirect). | ||
| 'crawlee_cookie_jar': session.cookies.jar if session else None, | ||
| 'crawlee_session': session if self._persist_cookies_per_session else None, | ||
| }, | ||
| timeout=timeout or httpx.USE_CLIENT_DEFAULT, | ||
| ) | ||
|
|
||
| def _get_client(self, proxy_url: str | None) -> httpx.AsyncClient: | ||
| """Retrieve or create an HTTP client for the given proxy URL. | ||
|
|
||
| If a client for the specified proxy URL does not exist, create and store a new one. | ||
| Clients are shared per proxy (not per session). Session cookies stay on the request / | ||
| transport path so concurrent sessions can reuse one client and its connection pool. | ||
| """ | ||
| if not self._transport: | ||
| # Configure connection pool limits and keep-alive connections for transport | ||
| limits = self._async_client_kwargs.get( | ||
| 'limits', httpx.Limits(max_connections=1000, max_keepalive_connections=200) | ||
| ) | ||
|
|
@@ -307,15 +328,13 @@ def _get_client(self, proxy_url: str | None) -> httpx.AsyncClient: | |
| ) | ||
|
|
||
| if proxy_url not in self._client_by_proxy_url: | ||
| # Prepare a default kwargs for the new client. | ||
| kwargs: dict[str, Any] = { | ||
| 'proxy': proxy_url, | ||
| 'http1': self._http1, | ||
| 'http2': self._http2, | ||
| 'follow_redirects': True, | ||
| } | ||
|
|
||
| # Update the default kwargs with any additional user-provided kwargs. | ||
| kwargs.update(self._async_client_kwargs) | ||
|
|
||
| kwargs.update( | ||
|
|
@@ -333,15 +352,19 @@ def _get_client(self, proxy_url: str | None) -> httpx.AsyncClient: | |
| def _combine_headers(self, explicit_headers: HttpHeaders | None) -> HttpHeaders | None: | ||
| """Merge default headers with explicit headers for an HTTP request. | ||
|
|
||
| Generate a final set of request headers by combining default headers, a random User-Agent header, | ||
| and any explicitly provided headers. | ||
| Generate a final set of request headers by combining default headers from a single fingerprint | ||
| (Accept, Accept-Language, User-Agent) and any explicitly provided headers. Using one fingerprint | ||
| avoids mixing Accept headers from one browser profile with a User-Agent from another. | ||
| """ | ||
| common_headers = self._header_generator.get_common_headers() if self._header_generator else HttpHeaders() | ||
| user_agent_header = ( | ||
| self._header_generator.get_random_user_agent_header() if self._header_generator else HttpHeaders() | ||
| ) | ||
| if self._header_generator: | ||
| generated_headers = self._header_generator.get_specific_headers( | ||
|
vdusek marked this conversation as resolved.
|
||
| header_names={'Accept', 'Accept-Language', 'User-Agent'}, | ||
| ) | ||
| else: | ||
| generated_headers = HttpHeaders() | ||
|
|
||
| explicit_headers = explicit_headers or HttpHeaders() | ||
| headers = common_headers | user_agent_header | explicit_headers | ||
| headers = generated_headers | explicit_headers | ||
| return headers or None | ||
|
|
||
| @staticmethod | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.