Skip to content

Scrapy, a fast high-level web crawling & scraping framework for Python.

Add CONCURRENT_CONNECTIONS_PER_HANDLER and CONNECTION_KEEPALIVE_TIMEOUT (#7932)

Adrianee068e72ebb5
diff --git a/conftest.py b/conftest.py
index c8d300516..f7e18ee44 100644
--- a/conftest.py
+++ b/conftest.py
@@ -58,7 +58,7 @@ if not H2_ENABLED:
)
)
-if find_spec("httpx2") is None and find_spec("httpx") is None:
+if find_spec("httpx2") is None:
collect_ignore.append("scrapy/core/downloader/handlers/_httpx.py")
if find_spec("pytest_codspeed") is None:
diff --git a/docs/faq.rst b/docs/faq.rst
index 3fac4df41..7bc8e879e 100644
--- a/docs/faq.rst
+++ b/docs/faq.rst
@@ -422,6 +422,23 @@ inline within web pages, similar to external resources. The "data:" scheme with
content (",") essentially creates a request to a data URL without any specific content.
+.. _faq-too-many-open-files:
+
+I get ``too many file descriptors in select()`` or ``Too many open files``
+--------------------------------------------------------------------------
+
+The crawl is opening more sockets than the system allows. On Windows
+:func:`select.select` handles at most 512 sockets; elsewhere the ceiling is the
+maximum number of open files allowed for the process, which sockets, log files
+and feed exports all count towards.
+
+Lower :setting:`CONCURRENT_CONNECTIONS_PER_HANDLER`, keeping in mind that every
+:ref:`download handler <topics-download-handlers>` applies it on its own, so a
+crawl of both ``http://`` and ``https://`` URLs can open twice as many
+connections. Raising the limit of the operating system works as well on
+platforms other than Windows.
+
+
Running ``runspider`` I get ``error: No spider found in file: <filename>``
--------------------------------------------------------------------------
diff --git a/docs/topics/optimize.rst b/docs/topics/optimize.rst
index 4fa4db5d8..c1e88a32c 100644
--- a/docs/topics/optimize.rst
+++ b/docs/topics/optimize.rst
@@ -139,6 +139,10 @@ Raise them to crawl a single website faster, and see
:ref:`broad-crawls-concurrency` to spread requests across many websites
instead.
+Concurrency also drives how many connections stay open, which is capped
+separately by :setting:`CONCURRENT_CONNECTIONS_PER_HANDLER`. See
+:ref:`faq-too-many-open-files` if a crawl runs out of file descriptors.
+
The limit that matters, though, is the one the target website tolerates.
Exceeding it gets you throttled, served errors or banned, all of which make the
crawl slower than a lower concurrency would have been. To find that limit:
diff --git a/docs/topics/settings.rst b/docs/topics/settings.rst
index 8f9d5e313..071d3b5c3 100644
--- a/docs/topics/settings.rst
+++ b/docs/topics/settings.rst
@@ -586,6 +586,44 @@ project name). This name will be used for the logging too.
It's automatically populated with your project name when you create your
project with the :command:`startproject` command.
+.. setting:: CONCURRENT_CONNECTIONS_PER_HANDLER
+
+CONCURRENT_CONNECTIONS_PER_HANDLER
+----------------------------------
+
+Default: ``None``
+
+.. versionadded:: VERSION
+
+The maximum number of connections that a single :ref:`download handler
+<topics-download-handlers>` may keep open, whether they are being used for a
+request or kept around for reuse by a later request. Use ``0`` for no limit.
+
+``None`` lets Scrapy pick a limit that fits the system it runs on. How it is
+picked may change in any future Scrapy version, without a deprecation period,
+so set a number if you need it to stay the same.
+
+Scrapy currently picks half of the maximum number of open files allowed for the
+process, or 480 on Windows, where :func:`select.select` handles at most 512
+sockets.
+
+Each download handler applies this limit on its own, so a crawl of both
+``http://`` and ``https://`` URLs may open up to twice as many connections.
+:class:`~scrapy.core.downloader.handlers._httpx.HttpxDownloadHandler`
+additionally applies it once per proxy, since httpx `cannot use a different
+proxy per request <https://github.com/pydantic/httpx2/issues/818>`_.
+
+HTTP/2 multiplexes requests over a single connection per remote, so
+:class:`~scrapy.core.downloader.handlers.http2.H2DownloadHandler` reaches this
+limit only after as many remotes, regardless of concurrency, and it keeps a
+connection that is serving requests even if that leaves it over the limit.
+
+How the limit is reached also depends on the handler: some close the connection
+that has been idle the longest to make room for a new one, others make requests
+wait for a connection to free up. Either way, a value below
+:setting:`CONCURRENT_REQUESTS` keeps the crawl from reaching the configured
+concurrency, and logs a warning.
+
.. setting:: CONCURRENT_ITEMS
CONCURRENT_ITEMS
diff --git a/pyproject.toml b/pyproject.toml
index 2d7113e94..a29cffe3b 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -70,7 +70,7 @@ bpython = ["bpython>=0.7.1"]
clipboard = ["pyperclip>=1.8.0"]
color = ["colorlog>=6.6.0"]
gcs = ["google-cloud-storage>=1.30.0"]
-httpx = ["httpx2[http2,socks]>=2.0.0"]
+httpx = ["httpx2[http2,socks]>=2.3.0"]
images = ["Pillow>=9.2.0"]
ipython = ["ipython>=8.15.0"]
memusage = ["psutil>=5.9.0"]
diff --git a/scrapy/core/_http2/agent.py b/scrapy/core/_http2/agent.py
index 4467985d5..6a54d585f 100644
--- a/scrapy/core/_http2/agent.py
+++ b/scrapy/core/_http2/agent.py
@@ -25,8 +25,9 @@ ConnectionKey: TypeAlias = tuple[bytes, bytes, int, tuple[str, int] | None]
class H2ConnectionPool:
- def __init__(self, crawler: Crawler) -> None:
+ def __init__(self, crawler: Crawler, limit: int = 0) -> None:
self._crawler = crawler
+ self._limit = limit
# Store a dictionary which is used to get the respective
# H2ClientProtocolInstance using the key as Tuple(scheme, hostname, port)
@@ -48,9 +49,13 @@ class H2ConnectionPool:
# Received a request while connecting to remote
return self._pending_request(key)
- # Check if we already have a connection to the remote
- conn = self._connections.get(key, None)
+ # Check if we already have a usable connection to the remote, moving
+ # it to the end so that the pool stays ordered from least to most
+ # recently used
+ conn = self._connections.get(key)
if conn and not conn.closing:
+ del self._connections[key]
+ self._connections[key] = conn
# Return this connection instance wrapped inside a deferred
return defer.succeed(conn)
@@ -60,6 +65,7 @@ class H2ConnectionPool:
def _new_connection(
self, key: ConnectionKey, uri: URI, endpoint: HostnameEndpoint
) -> Deferred[H2ClientProtocol]:
+ self._enforce_limit()
self._pending_requests[key] = deque()
conn_lost_deferred: Deferred[None] = Deferred()
@@ -89,6 +95,26 @@ class H2ConnectionPool:
pending_requests.append(d)
return d
+ def _enforce_limit(self) -> None:
+ """Close the least recently used connections that are not serving any
+ stream, to make room for one more connection.
+
+ HTTP/2 multiplexes requests over a single connection per remote, so a
+ connection with active streams is kept even if that leaves the pool
+ over the limit.
+ """
+ if not self._limit:
+ return
+ surplus = len(self._connections) + len(self._pending_requests) + 1 - self._limit
+ for key, conn in list(self._connections.items()):
+ if surplus <= 0:
+ return
+ if conn.metadata["active_streams"]:
+ continue
+ del self._connections[key]
+ conn._close_idle()
+ surplus -= 1
+
def put_connection(
self,
conn: H2ClientProtocol,
diff --git a/scrapy/core/downloader/handlers/_aiohttp.py b/scrapy/core/downloader/handlers/_aiohttp.py
index 1323132f6..1237d9b07 100644
--- a/scrapy/core/downloader/handlers/_aiohttp.py
+++ b/scrapy/core/downloader/handlers/_aiohttp.py
@@ -25,10 +25,40 @@ from ._base_streaming import BaseStreamingDownloadHandler, _BaseResponseArgs
if TYPE_CHECKING:
from collections.abc import AsyncIterator
+ from aiohttp.client_proto import ResponseHandler
+ from aiohttp.client_reqrep import ClientRequest
+ from aiohttp.tracing import Trace
+
from scrapy import Request
from scrapy.crawler import Crawler
+class _TCPConnector(aiohttp.TCPConnector):
+ """Counts idle connections toward the connection limit, closing the least
+ recently used one when a new connection would otherwise exceed it."""
+
+ async def _create_connection(
+ self,
+ req: ClientRequest,
+ traces: list[Trace],
+ timeout: aiohttp.ClientTimeout, # noqa: ASYNC109
+ ) -> ResponseHandler:
+ # the connection about to be created is already counted in _acquired
+ while (
+ self._limit
+ and len(self._acquired) + sum(map(len, self._conns.values())) > self._limit
+ ):
+ self._evict()
+ return await super()._create_connection(req, traces, timeout)
+
+ def _evict(self) -> None:
+ _, key = min((conns[0][1], key) for key, conns in self._conns.items())
+ protocol, _ = self._conns[key].popleft()
+ if not self._conns[key]:
+ del self._conns[key]
+ protocol.close()
+
+
class _ClientResponse(aiohttp.ClientResponse):
"""Captures transport data that can be lost after parent ``start()``.
@@ -57,9 +87,9 @@ class AiohttpDownloadHandler(BaseStreamingDownloadHandler[_ClientResponse]):
def __init__(self, crawler: Crawler):
super().__init__(crawler)
self._ssl_context: ssl.SSLContext = _make_ssl_context(crawler.settings)
- connector = aiohttp.TCPConnector(
+ connector = _TCPConnector(
local_addr=self._bind_address,
- # hard limit on simultaneous connections
+ # hard limit on open connections, idle ones included
limit=self._pool_size_total,
# hard limit on simultaneous connections per host
limit_per_host=self._pool_size_per_host,
diff --git a/scrapy/core/downloader/handlers/_base_http.py b/scrapy/core/downloader/handlers/_base_http.py
index eee164aa1..930c22285 100644
--- a/scrapy/core/downloader/handlers/_base_http.py
+++ b/scrapy/core/downloader/handlers/_base_http.py
@@ -1,12 +1,55 @@
from __future__ import annotations
+import logging
+import sys
from abc import ABC
from typing import TYPE_CHECKING
from .base import BaseDownloadHandler
+try:
+ # stdlib's resource module is only available on unix platforms
+ import resource
+except ImportError:
+ resource = None # type: ignore[assignment]
+
if TYPE_CHECKING:
from scrapy.crawler import Crawler
+ from scrapy.settings import BaseSettings
+
+
+logger = logging.getLogger(__name__)
+
+# The number of sockets that select() accepts in CPython's Windows build; see
+# FD_SETSIZE in Modules/selectmodule.c.
+_FD_SETSIZE = 512
+
+# Room left for the sockets that a Windows crawl registers with the event loop
+# outside of download handlers, e.g. the asyncio self-pipe and the telnet
+# console.
+_WINDOWS_RESERVED_SOCKETS = 32
+
+
+def _auto_connection_limit() -> int:
+ if sys.platform == "win32":
+ return _FD_SETSIZE - _WINDOWS_RESERVED_SOCKETS
+ soft_limit: int = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
+ if soft_limit == resource.RLIM_INFINITY:
+ return 0
+ return soft_limit // 2
+
+
+def _get_connection_limit(settings: BaseSettings) -> int:
+ limit = settings.get("CONCURRENT_CONNECTIONS_PER_HANDLER")
+ limit = _auto_connection_limit() if limit is None else int(limit)
+ concurrent_requests = settings.getint("CONCURRENT_REQUESTS")
+ if 0 < limit < concurrent_requests:
+ logger.warning(
+ f"CONCURRENT_CONNECTIONS_PER_HANDLER ({limit}) is lower than"
+ f" CONCURRENT_REQUESTS ({concurrent_requests}), which keeps the"
+ f" crawl from reaching the configured concurrency."
+ )
+ return limit
class BaseHttpDownloadHandler(BaseDownloadHandler, ABC):
@@ -23,6 +66,11 @@ class BaseHttpDownloadHandler(BaseDownloadHandler, ABC):
"DOWNLOADER_CLIENT_TLS_VERBOSE_LOGGING"
)
self._fail_on_dataloss_warned: bool = False
+ # these are useful for many handlers but used in different ways by them
+ self._pool_size_total: int = _get_connection_limit(crawler.settings)
+ self._pool_size_per_host: int = crawler.settings.getint(
+ "CONCURRENT_REQUESTS_PER_DOMAIN"
+ )
self._keepalive_timeout: float = crawler.settings.getfloat(
"CONNECTION_KEEPALIVE_TIMEOUT"
)
diff --git a/scrapy/core/downloader/handlers/_base_streaming.py b/scrapy/core/downloader/handlers/_base_streaming.py
index 050bf4df8..a556530e5 100644
--- a/scrapy/core/downloader/handlers/_base_streaming.py
+++ b/scrapy/core/downloader/handlers/_base_streaming.py
@@ -95,11 +95,6 @@ class BaseStreamingDownloadHandler(BaseHttpDownloadHandler, Generic[_ResponseT])
crawler.settings.get("DOWNLOAD_BIND_ADDRESS")
)
self._proxy_auth_encoding: str = crawler.settings.get("HTTPPROXY_AUTH_ENCODING")
- # these are useful for many handlers but used in different ways by them
- self._pool_size_total: int = crawler.settings.getint("CONCURRENT_REQUESTS")
- self._pool_size_per_host: int = crawler.settings.getint(
- "CONCURRENT_REQUESTS_PER_DOMAIN"
- )
@abstractmethod
def _make_request(
diff --git a/scrapy/core/downloader/handlers/_httpx.py b/scrapy/core/downloader/handlers/_httpx.py
index f768d02f1..9c3e73a33 100644
--- a/scrapy/core/downloader/handlers/_httpx.py
+++ b/scrapy/core/downloader/handlers/_httpx.py
@@ -45,10 +45,7 @@ _ProxyKey: TypeAlias = tuple[str, tuple[tuple[str, str], ...]]
HAS_SOCKS = HAS_HTTP2 = False
try:
- try:
- import httpx2 as httpx
- except ImportError: # pragma: no cover
- import httpx # type: ignore[import-not-found,no-redef]
+ import httpx2 as httpx
except ImportError: # pragma: no cover
httpx = None # type: ignore[assignment]
else:
@@ -99,7 +96,7 @@ class HttpxDownloadHandler(_Base):
self._bind_host: str | None = self._get_bind_address_host()
self._limits: httpx.Limits = httpx.Limits(
# hard limit on simultaneous connections (None for no limit, which
- # is what a CONCURRENT_REQUESTS of 0 means)
+ # is what a CONCURRENT_CONNECTIONS_PER_HANDLER of 0 means)
max_connections=self._pool_size_total or None,
# total number of idle connections in the pool (extra ones are
# closed); keeping none of them is how keepalive gets disabled,
@@ -217,7 +214,7 @@ class HttpxDownloadHandler(_Base):
raise DownloadConnectionRefusedError(str(e)) from e
except httpx.ProxyError as e:
raise DownloadConnectionRefusedError(str(e)) from e
- except DOWNLOAD_FAILED_EXCEPTIONS as e: # pylint: disable=catching-non-exception
+ except DOWNLOAD_FAILED_EXCEPTIONS as e:
raise DownloadFailedError(str(e)) from e
@staticmethod
diff --git a/scrapy/core/downloader/handlers/http11.py b/scrapy/core/downloader/handlers/http11.py
index 43868dcc8..c5a1649b9 100644
--- a/scrapy/core/downloader/handlers/http11.py
+++ b/scrapy/core/downloader/handlers/http11.py
@@ -71,6 +71,7 @@ from ._base_http import BaseHttpDownloadHandler
if TYPE_CHECKING:
import os
+ from collections.abc import Callable
from twisted.internet.base import ReactorBase
from twisted.internet.interfaces import IAddress, IConsumer
@@ -93,6 +94,182 @@ class _ResultT(TypedDict):
stop_download: NotRequired[StopDownload | None]
+class _LenientHTTPClientParser(HTTPClientParser):
+ """Response parser that skips bad response header lines, those with no
+ colon in them, instead of failing to parse the whole response.
+
+ Some servers send such lines, and web browsers skip them and keep parsing
+ the header lines that follow. See
+ https://github.com/scrapy/scrapy/issues/210.
+ """
+
+ def lineReceived(self, line: bytes) -> None:
+ # A copy of twisted.web._newclient.HTTPParser.lineReceived() where the
+ # header name and value are only extracted from header lines that have
+ # a colon.
+
+ # Handle the normal CR LF case.
+ line = line.removesuffix(b"\r")
+
+ if self.state == STATUS:
+ self.statusReceived(line) # type: ignore[no-untyped-call]
+ self.state = HEADER
+ return
+
+ # HEADER is the only other state in which lines are received, as the
+ # parser switches to raw mode for the response body.
+ if not line or line[0] not in b" \t":
+ if self._partialHeader is not None:
+ header = b"".join(self._partialHeader)
+ if b":" in header:
+ name, value = header.split(b":", 1)
+ self.headerReceived(name, value.strip()) # type: ignore[no-untyped-call]
+ else:
+ logger.debug(
+ f"Skipping the bad response header line {header!r}, as "
+ f"it has no colon."
+ )
+ if not line:
+ # Empty line means the header section is over.
+ self.allHeadersReceived() # type: ignore[no-untyped-call]
+ else:
+ # Line not beginning with LWS is another header.
+ self._partialHeader = [line]
+ else:
+ # A line beginning with LWS is a continuation of a header begun on
+ # a previous line.
+ self._partialHeader.append(line) # type: ignore[union-attr]
+
+
+class _LenientHTTP11ClientProtocol(HTTP11ClientProtocol):
+ """Protocol that parses responses with :class:`_LenientHTTPClientParser`."""
+
+ def request(self, request: TxRequest) -> Deferred[IResponse]:
+ d: Deferred[IResponse] = super().request(request)
+ # HTTP11ClientProtocol.request() hardcodes the parser class, so the
+ # only way to use a different one is to replace the class of the parser
+ # object that it creates. This is safe because
+ # _LenientHTTPClientParser defines no additional state. The parser is
+ # always there because HTTPConnectionPool only reuses connections whose
+ # protocol is in the QUIESCENT state, for which request() always
+ # creates a parser.
+ assert self._parser is not None
+ self._parser.__class__ = _LenientHTTPClientParser
+
+ # For responses without a body, twisted.web.client.Response never
+ # hands its transport to a protocol, so the certificate and IP
+ # address cannot be read from it later (see
+ # _ResponseReader.connectionMade). self.transport, however, is the
+ # connection's real transport and outlives any single request, so
+ # read the certificate and IP address from it directly and stash
+ # them on the response.
+ assert self.transport is not None
+ transport = self.transport
+
+ def _attach_connection_info(response: IResponse) -> IResponse:
+ with suppress(AttributeError):
+ response._scrapy_certificate = ssl.Certificate(
+ transport.getPeerCertificate()
+ )
+ with suppress(AttributeError):
+ response._scrapy_ip_address = ipaddress.ip_address(
+ transport.getPeer().host
+ )
+ return response
+
+ d.addCallback(_attach_connection_info)
+ return d
+
+
+class _TrackedHTTP11ClientProtocol(_LenientHTTP11ClientProtocol):
+ """Connection that tells the pool that opened it when it closes, whether it
+ was cached at the time or in use."""
+
+ _pool: _BoundedHTTPConnectionPool
+ _pool_key: Any
+
+ def connectionLost(self, reason: Failure = connectionDone) -> None:
+ self._pool._forget(self)
+ super().connectionLost(reason) # type: ignore[no-untyped-call]
+
+
+class _BoundedHTTP11ClientFactory(_HTTP11ClientFactory):
+ noisy = False
+
+ def __init__(
+ self,
+ quiescentCallback: Callable[[HTTP11ClientProtocol], None],
+ metadata: str,
+ pool: _BoundedHTTPConnectionPool,
+ key: Any,
+ ):
+ super().__init__(quiescentCallback, metadata) # type: ignore[no-untyped-call]
+ self._pool: _BoundedHTTPConnectionPool = pool
+ self._key: Any = key
+
+ def buildProtocol(self, addr: IAddress | None) -> _TrackedHTTP11ClientProtocol:
+ protocol = _TrackedHTTP11ClientProtocol(self._quiescentCallback) # type: ignore[no-untyped-call]
+ protocol._pool = self._pool
+ protocol._pool_key = self._key
+ self._pool._open.add(protocol)
+ return protocol
+
+
+class _BoundedHTTPConnectionPool(HTTPConnectionPool):
+ """Connection pool that keeps the number of open connections, cached and in
+ use alike, under *limit*, where 0 means no limit.
+
+ Opening a connection once the limit is reached closes the least recently
+ used cached connection to make room for it. When there is no cached
+ connection left to close, the limit is exceeded rather than requests
+ delayed.
+ """
+
+ _factory = _BoundedHTTP11ClientFactory # type: ignore[assignment]
+
+ def __init__(self, reactor: ReactorBase, limit: int, keepalive_timeout: float):
+ super().__init__(reactor, persistent=bool(keepalive_timeout)) # type: ignore[no-untyped-call]
+ self.cachedConnectionTimeout = keepalive_timeout # type: ignore[assignment]
+ self._limit: int = limit
+ self._open: set[_TrackedHTTP11ClientProtocol] = set()
+
+ def _newConnection(
+ self, key: Any, endpoint: IStreamClientEndpoint
+ ) -> Deferred[HTTP11ClientProtocol]:
+ while self._limit and len(self._open) >= self._limit and self._evict():
+ pass
+
+ def quiescentCallback(protocol: HTTP11ClientProtocol) -> None:
+ self._putConnection(key, protocol) # type: ignore[no-untyped-call]
+
+ factory = self._factory(quiescentCallback, repr(endpoint), self, key)
+ return endpoint.connect(factory) # type: ignore[no-any-return]
+
+ def _forget(self, connection: _TrackedHTTP11ClientProtocol) -> None:
+ self._open.discard(connection)
+
+ def _evict(self) -> bool:
+ """Close the least recently used cached connection, and report whether
+ there was one to close.
+
+ ``_timeouts`` holds cached connections only, and ``getConnection()``
+ drops the ones it hands out, so its insertion order goes from least to
+ most recently used.
+ """
+ connection = next(iter(self._timeouts), None)
+ if connection is None:
+ return False
+ self._timeouts[connection].cancel()
+ # dropped early so that a caller looping on this method sees the room
+ # made by connections that have yet to finish closing
+ self._forget(connection)
+ key = connection._pool_key
+ self._removeConnection(key, connection) # type: ignore[no-untyped-call]
+ if not self._connections[key]:
+ del self._connections[key]
+ return True
+
+
class HTTP11DownloadHandler(BaseHttpDownloadHandler):
def __init__(self, crawler: Crawler):
if not crawler.settings.getbool("TWISTED_REACTOR_ENABLED"):
@@ -103,14 +280,10 @@ class HTTP11DownloadHandler(BaseHttpDownloadHandler):
from twisted.internet import reactor
- self._pool: HTTPConnectionPool = HTTPConnectionPool(
- reactor, persistent=bool(self._keepalive_timeout)
+ self._pool: _BoundedHTTPConnectionPool = _BoundedHTTPConnectionPool(
+ reactor, self._pool_size_total, self._keepalive_timeout
)
- self._pool.cachedConnectionTimeout = self._keepalive_timeout # type: ignore[assignment]
- self._pool.maxPersistentPerHost = crawler.settings.getint(
- "CONCURRENT_REQUESTS_PER_DOMAIN"
- )
- self._pool._factory = _LenientHTTP11ClientFactory
+ self._pool.maxPersistentPerHost = self._pool_size_per_host
self._contextFactory: IPolicyForHTTPS = _load_context_factory_from_settings(
crawler
@@ -152,7 +325,7 @@ class HTTP11DownloadHandler(BaseHttpDownloadHandler):
async def close(self) -> None:
from twisted.internet import reactor
- d: Deferred[None] = self._pool.closeCachedConnections()
+ d: Deferred[None] = self._pool.closeCachedConnections() # type: ignore[no-untyped-call]
# closeCachedConnections will hang on network or server issues, so
# we'll manually timeout the deferred.
#
@@ -883,99 +1056,3 @@ class _ResponseReader(Protocol):
exc = ResponseDataLossError()
exc.__cause__ = reason.value
self._finished.errback(exc)
-
-
-class _LenientHTTPClientParser(HTTPClientParser):
- """Response parser that skips bad response header lines, those with no
- colon in them, instead of failing to parse the whole response.
-
- Some servers send such lines, and web browsers skip them and keep parsing
- the header lines that follow. See
- https://github.com/scrapy/scrapy/issues/210.
- """
-
- def lineReceived(self, line: bytes) -> None:
- # A copy of twisted.web._newclient.HTTPParser.lineReceived() where the
- # header name and value are only extracted from header lines that have
- # a colon.
-
- # Handle the normal CR LF case.
- line = line.removesuffix(b"\r")
-
- if self.state == STATUS:
- self.statusReceived(line) # type: ignore[no-untyped-call]
- self.state = HEADER
- return
-
- # HEADER is the only other state in which lines are received, as the
- # parser switches to raw mode for the response body.
- if not line or line[0] not in b" \t":
- if self._partialHeader is not None:
- header = b"".join(self._partialHeader)
- if b":" in header:
- name, value = header.split(b":", 1)
- self.headerReceived(name, value.strip()) # type: ignore[no-untyped-call]
- else:
- logger.debug(
- f"Skipping the bad response header line {header!r}, as "
- f"it has no colon."
- )
- if not line:
- # Empty line means the header section is over.
- self.allHeadersReceived() # type: ignore[no-untyped-call]
- else:
- # Line not beginning with LWS is another header.
- self._partialHeader = [line]
- else:
- # A line beginning with LWS is a continuation of a header begun on
- # a previous line.
- self._partialHeader.append(line) # type: ignore[union-attr]
-
-
-class _LenientHTTP11ClientProtocol(HTTP11ClientProtocol):
- """Protocol that parses responses with :class:`_LenientHTTPClientParser`."""
-
- def request(self, request: TxRequest) -> Deferred[IResponse]:
- d: Deferred[IResponse] = super().request(request)
- # HTTP11ClientProtocol.request() hardcodes the parser class, so the
- # only way to use a different one is to replace the class of the parser
- # object that it creates. This is safe because
- # _LenientHTTPClientParser defines no additional state. The parser is
- # always there because HTTPConnectionPool only reuses connections whose
- # protocol is in the QUIESCENT state, for which request() always
- # creates a parser.
- assert self._parser is not None
- self._parser.__class__ = _LenientHTTPClientParser
-
- # For responses without a body, twisted.web.client.Response never
- # hands its transport to a protocol, so the certificate and IP
- # address cannot be read from it later (see
- # _ResponseReader.connectionMade). self.transport, however, is the
- # connection's real transport and outlives any single request, so
- # read the certificate and IP address from it directly and stash
- # them on the response.
- assert self.transport is not None
- transport = self.transport
-
- def _attach_connection_info(response: IResponse) -> IResponse:
- with suppress(AttributeError):
- response._scrapy_certificate = ssl.Certificate(
- transport.getPeerCertificate()
- )
- with suppress(AttributeError):
- response._scrapy_ip_address = ipaddress.ip_address(
- transport.getPeer().host
- )
- return response
-
- d.addCallback(_attach_connection_info)
- return d
-
-
-class _LenientHTTP11ClientFactory(_HTTP11ClientFactory):
- """Factory that builds :class:`_LenientHTTP11ClientProtocol` protocols."""
-
- noisy = False
-
- def buildProtocol(self, addr: IAddress | None) -> HTTP11ClientProtocol:
- return _LenientHTTP11ClientProtocol(self._quiescentCallback) # type: ignore[no-untyped-call]
diff --git a/scrapy/core/downloader/handlers/http2.py b/scrapy/core/downloader/handlers/http2.py
index 5302a7749..2dc5ea848 100644
--- a/scrapy/core/downloader/handlers/http2.py
+++ b/scrapy/core/downloader/handlers/http2.py
@@ -8,7 +8,7 @@ from urllib.parse import urldefrag
from scrapy.core._http2.agent import H2Agent, H2ConnectionPool
from scrapy.core.downloader._idna_patch import _install_twisted_idna_fallbacks
from scrapy.core.downloader.contextfactory import _load_context_factory_from_settings
-from scrapy.core.downloader.handlers.base import BaseDownloadHandler
+from scrapy.core.downloader.handlers._base_http import BaseHttpDownloadHandler
from scrapy.exceptions import (
DownloadTimeoutError,
NotConfigured,
@@ -36,7 +36,7 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
-class H2DownloadHandler(BaseDownloadHandler):
+class H2DownloadHandler(BaseHttpDownloadHandler):
lazy = True
def __init__(self, crawler: Crawler):
@@ -46,7 +46,7 @@ class H2DownloadHandler(BaseDownloadHandler):
super().__init__(crawler)
self._crawler = crawler
- self._pool = H2ConnectionPool(crawler)
+ self._pool = H2ConnectionPool(crawler, self._pool_size_total)
self._context_factory = _load_context_factory_from_settings(crawler)
self._bind_address = crawler.settings.get("DOWNLOAD_BIND_ADDRESS")
self._fail_on_dataloss_warned = False
diff --git a/scrapy/settings/default_settings.py b/scrapy/settings/default_settings.py
index 9f55b3717..fd9d45f26 100644
--- a/scrapy/settings/default_settings.py
+++ b/scrapy/settings/default_settings.py
@@ -43,6 +43,7 @@ __all__ = [
"CLOSESPIDER_TIMEOUT_NO_ITEM",
"COMMANDS_MODULE",
"COMPRESSION_ENABLED",
+ "CONCURRENT_CONNECTIONS_PER_HANDLER",
"CONCURRENT_ITEMS",
"CONCURRENT_REQUESTS",
"CONCURRENT_REQUESTS_PER_DOMAIN",
@@ -274,6 +275,8 @@ COMMANDS_MODULE = ""
COMPRESSION_ENABLED = True
+CONCURRENT_CONNECTIONS_PER_HANDLER = None
+
CONCURRENT_ITEMS = 100
CONCURRENT_REQUESTS = 16
diff --git a/tests/mockserver/http_resources.py b/tests/mockserver/http_resources.py
index b01712577..759e3765b 100644
--- a/tests/mockserver/http_resources.py
+++ b/tests/mockserver/http_resources.py
@@ -488,13 +488,26 @@ _connection_ids = itertools.count()
class ConnectionId(LeafResource):
- """Return the identifier of the connection serving the request.
+ """Return the identifier of the connection serving the request, after the
+ number of seconds given in the ``delay`` argument.
Two responses carrying the same identifier were served over the same
connection, which lets tests tell connection reuse from reconnection.
"""
- def render_GET(self, request: Request) -> bytes:
+ def render_GET(self, request: Request) -> int | bytes:
+ delay = getarg(request, b"delay", 0, type_=float)
+ if not delay:
+ return self._connection_id(request)
+ self.deferRequest(request, delay, self._delayedRender, request)
+ return NOT_DONE_YET
+
+ def _delayedRender(self, request: Request) -> None:
+ request.write(self._connection_id(request))
+ request.finish()
+
+ @staticmethod
+ def _connection_id(request: Request) -> bytes:
# under HTTP/2 the channel of a request is its stream, so the
# connection has to be reached through it
channel: Any = getattr(request.channel, "_conn", request.channel)
diff --git a/tests/test_downloader_handler_httpx.py b/tests/test_downloader_handler_httpx.py
index 4427d8d5d..a3ab5d1c1 100644
--- a/tests/test_downloader_handler_httpx.py
+++ b/tests/test_downloader_handler_httpx.py
@@ -45,8 +45,8 @@ if TYPE_CHECKING:
pytestmark = pytest.mark.only_asyncio
-if find_spec("httpx2") is None and find_spec("httpx") is None:
- pytest.skip("Neither httpx2 nor httpx are installed", allow_module_level=True)
+if find_spec("httpx2") is None:
+ pytest.skip("httpx2 is not installed", allow_module_level=True)
# httpx2 < 2.4.0 reads URL.host through idna.decode() without display=True when
# building the Host header, which raises for punycode labels that IDNA 2008
@@ -233,10 +233,10 @@ async def test_proxy_headers_ignored_for_socks(
assert "the SOCKS protocol has no headers" in caplog.text
[email protected](("concurrency", "expected"), [(16, 16), (0, None)])
[email protected](("limit", "expected"), [(16, 16), (0, None)])
@coroutine_test
-async def test_pool_limits(concurrency: int, expected: int | None) -> None:
- crawler = get_crawler(settings_dict={"CONCURRENT_REQUESTS": concurrency})
+async def test_pool_limits(limit: int, expected: int | None) -> None:
+ crawler = get_crawler(settings_dict={"CONCURRENT_CONNECTIONS_PER_HANDLER": limit})
handler = build_from_crawler(HttpxDownloadHandler, crawler)
try:
assert handler._limits.max_connections == expected
@@ -245,6 +245,16 @@ async def test_pool_limits(concurrency: int, expected: int | None) -> None:
await handler.close()
+@coroutine_test
+async def test_keepalive_timeout() -> None:
+ crawler = get_crawler(settings_dict={"CONNECTION_KEEPALIVE_TIMEOUT": 5})
+ handler = build_from_crawler(HttpxDownloadHandler, crawler)
+ try:
+ assert handler._limits.keepalive_expiry == 5
+ finally:
+ await handler.close()
+
+
class StableHandler(HttpxDownloadHandler):
experimental = False
diff --git a/tests/test_downloader_handler_twisted_http11.py b/tests/test_downloader_handler_twisted_http11.py
index b260f055d..af71f3415 100644
--- a/tests/test_downloader_handler_twisted_http11.py
+++ b/tests/test_downloader_handler_twisted_http11.py
@@ -20,8 +20,14 @@ from twisted.python.failure import Failure
from twisted.web.client import URI, BrowserLikePolicyForHTTPS
from zope.interface import implementer
+try:
+ import resource
+except ImportError:
+ resource = None # type: ignore[assignment]
+
from scrapy import Request, Spider
from scrapy.core.downloader.contextfactory import _load_context_factory_from_settings
+from scrapy.core.downloader.handlers._base_http import _auto_connection_limit
from scrapy.core.downloader.handlers.http11 import (
HTTP11DownloadHandler,
TunnelError,
@@ -96,6 +102,63 @@ def test_not_configured_without_reactor() -> None:
build_from_crawler(HTTP11DownloadHandler, crawler)
+@asynccontextmanager
+async def _get_dh(
+ settings_dict: dict[str, Any] | None = None,
+) -> AsyncGenerator[HTTP11DownloadHandler]:
+ crawler = get_crawler(DefaultSpider, settings_dict)
+ crawler.spider = crawler._create_spider()
+ dh = build_from_crawler(HTTP11DownloadHandler, crawler)
+ try:
+ yield dh
+ finally:
+ await dh.close()
+
+
+@coroutine_test
+async def test_connection_limit_auto() -> None:
+ async with _get_dh({}) as dh:
+ assert dh._pool._limit == _auto_connection_limit()
+
+
+@coroutine_test
[email protected]("limit", [0, 20])
+async def test_connection_limit_explicit(limit: int) -> None:
+ async with _get_dh({"CONCURRENT_CONNECTIONS_PER_HANDLER": limit}) as dh:
+ assert dh._pool._limit == limit
+
+
+@coroutine_test
+async def test_connection_limit_below_concurrent_requests(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ settings_dict = {
+ "CONCURRENT_CONNECTIONS_PER_HANDLER": 4,
+ "CONCURRENT_REQUESTS": 8,
+ }
+ with caplog.at_level("WARNING"):
+ async with _get_dh(settings_dict):
+ pass
+ assert "CONCURRENT_CONNECTIONS_PER_HANDLER (4)" in caplog.text
+
+
[email protected](resource is None, reason="No file descriptor limit")
+@coroutine_test
+async def test_connection_limit_auto_without_file_descriptor_limit(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ infinity = resource.RLIM_INFINITY
+ monkeypatch.setattr(resource, "getrlimit", lambda _: (infinity, infinity))
+ async with _get_dh({}) as dh:
+ assert dh._pool._limit == 0
+
+
+@coroutine_test
+async def test_keepalive_timeout() -> None:
+ async with _get_dh({"CONNECTION_KEEPALIVE_TIMEOUT": 5}) as dh:
+ assert dh._pool.cachedConnectionTimeout == 5
+
+
@pytest.mark.parametrize(
("proxy_headers", "proxy_auth", "expected"),
[
@@ -475,17 +538,6 @@ async def _canned_proxy(response: bytes, split_at: int = 0) -> AsyncGenerator[st
await maybe_deferred_to_future(port.stopListening())
-@asynccontextmanager
-async def _get_dh() -> AsyncGenerator[HTTP11DownloadHandler]:
- crawler = get_crawler(DefaultSpider)
- crawler.spider = crawler._create_spider()
- dh = build_from_crawler(HTTP11DownloadHandler, crawler)
- try:
- yield dh
- finally:
- await dh.close()
-
-
class TestTunnelingErrors:
@coroutine_test
async def test_response_in_two_packets(self) -> None:
diff --git a/tests/test_downloader_handler_twisted_http2.py b/tests/test_downloader_handler_twisted_http2.py
index a88158a8d..4b3d19349 100644
--- a/tests/test_downloader_handler_twisted_http2.py
+++ b/tests/test_downloader_handler_twisted_http2.py
@@ -7,7 +7,7 @@ from typing import TYPE_CHECKING, Any
from unittest.mock import Mock
import pytest
-from twisted.internet.defer import Deferred
+from twisted.internet.defer import Deferred, DeferredList
from twisted.web.http import H2_ENABLED
from scrapy import Spider
@@ -18,6 +18,7 @@ from scrapy.exceptions import (
UnsupportedURLSchemeError,
)
from scrapy.http import Request
+from scrapy.utils.defer import deferred_from_coro, maybe_deferred_to_future
from scrapy.utils.misc import build_from_crawler
from scrapy.utils.test import get_crawler
from tests.utils.bases.download_handlers_http import (
@@ -114,6 +115,23 @@ class TestHttp2(H2DownloadHandlerMixin, TestHttpsBase):
response2 = await download_handler.download_request(request2)
assert response2.headers["Content-Length"] == b"79"
+ @coroutine_test
+ async def test_parallel_requests_same_domain(self, mockserver: MockServer) -> None:
+ url = mockserver.url("/connection-id", is_secure=self.is_secure)
+ async with self.get_dh() as download_handler:
+ results = await maybe_deferred_to_future(
+ DeferredList(
+ [
+ deferred_from_coro(download_handler.download_request(request))
+ for request in (Request(url), Request(url))
+ ],
+ fireOnOneErrback=True,
+ )
+ )
+ # the second request waited for the connection that the first one was
+ # opening instead of opening a second one
+ assert len({response.text for _, response in results}) == 1
+
@pytest.mark.xfail(reason="https://github.com/python-hyper/h2/issues/1247")
@coroutine_test
async def test_connect_request(self, mockserver: MockServer) -> None:
diff --git a/tests/utils/bases/download_handlers_http.py b/tests/utils/bases/download_handlers_http.py
index 616f30606..76f4d83a2 100644
--- a/tests/utils/bases/download_handlers_http.py
+++ b/tests/utils/bases/download_handlers_http.py
@@ -130,24 +130,94 @@ class TestHttpBase(ABC):
await dh.close()
async def _connection_ids(
- self, url: str, settings_dict: dict[str, Any]
+ self, urls: list[str], settings_dict: dict[str, Any]
) -> set[str]:
- """Request *url* twice in a row and return the identifiers of the
+ """Request *urls* one after another and return the identifiers of the
connections that the server used to serve them."""
async with self.get_dh(settings_dict) as dh:
- responses = [await dh.download_request(Request(url)) for _ in range(2)]
+ responses = [await dh.download_request(Request(url)) for url in urls]
return {response.text for response in responses}
+ @staticmethod
+ def _other_host(url: str) -> str:
+ """Return *url* pointing at the same server through a different name,
+ so that its connection cannot be reused."""
+ return url.replace("127.0.0.1", "localhost")
+
@coroutine_test
async def test_keepalive(self, mockserver: MockServer) -> None:
url = mockserver.url("/connection-id", is_secure=self.is_secure)
- assert len(await self._connection_ids(url, {})) == 1
+ assert len(await self._connection_ids([url, url], {})) == 1
@coroutine_test
async def test_no_keepalive(self, mockserver: MockServer) -> None:
url = mockserver.url("/connection-id", is_secure=self.is_secure)
settings_dict = {"CONNECTION_KEEPALIVE_TIMEOUT": 0}
- assert len(await self._connection_ids(url, settings_dict)) == 2
+ assert len(await self._connection_ids([url, url], settings_dict)) == 2
+
+ @coroutine_test
+ async def test_connection_limit(self, mockserver: MockServer) -> None:
+ url = mockserver.url("/connection-id", is_secure=self.is_secure)
+ urls = [url, self._other_host(url)] * 2
+
+ assert len(await self._connection_ids(urls, {})) == 2
+
+ settings_dict = {"CONCURRENT_CONNECTIONS_PER_HANDLER": 1}
+ assert len(await self._connection_ids(urls, settings_dict)) == 4
+
+ settings_dict = {"CONCURRENT_CONNECTIONS_PER_HANDLER": 0}
+ assert len(await self._connection_ids(urls, settings_dict)) == 2
+
+ @coroutine_test
+ async def test_connection_limit_spares_connections_in_use(
+ self, mockserver: MockServer
+ ) -> None:
+ url = mockserver.url("/connection-id", is_secure=self.is_secure)
+ slow_url = mockserver.url("/connection-id?delay=0.5", is_secure=self.is_secure)
+ other_url = self._other_host(url)
+ async with self.get_dh({"CONCURRENT_CONNECTIONS_PER_HANDLER": 1}) as dh:
+ first = await dh.download_request(Request(url))
+ results = await maybe_deferred_to_future(
+ DeferredList(
+ [
+ deferred_from_coro(dh.download_request(Request(slow_url))),
+ deferred_from_coro(dh.download_request(Request(other_url))),
+ ],
+ fireOnOneErrback=True,
+ )
+ )
+ ids = {response.text for _, response in results}
+ # the connection serving the slow request was kept even though the
+ # request to the other host had to exceed the limit to get one
+ assert first.text in ids
+ assert len(ids) == 2
+
+ @coroutine_test
+ async def test_connection_limit_with_several_connections_per_host(
+ self, mockserver: MockServer
+ ) -> None:
+ if self.http2:
+ pytest.skip("HTTP/2 uses a single connection per host")
+ url = mockserver.url("/connection-id", is_secure=self.is_secure)
+ slow_url = mockserver.url("/connection-id?delay=0.5", is_secure=self.is_secure)
+ other_url = self._other_host(url)
+ async with self.get_dh({"CONCURRENT_CONNECTIONS_PER_HANDLER": 2}) as dh:
+ results = await maybe_deferred_to_future(
+ DeferredList(
+ [
+ deferred_from_coro(dh.download_request(Request(slow_url)))
+ for _ in range(2)
+ ],
+ fireOnOneErrback=True,
+ )
+ )
+ ids = {response.text for _, response in results}
+ assert len(ids) == 2
+ # only one of the two connections to the host makes room for the
+ # connection to the other host, so the other one stays reusable
+ await dh.download_request(Request(other_url))
+ reused = await dh.download_request(Request(url))
+ assert reused.text in ids
@coroutine_test
async def test_unsupported_scheme(self) -> None:
diff --git a/tox.ini b/tox.ini
index dfc5a853d..e8276a5b8 100644
--- a/tox.ini
+++ b/tox.ini
@@ -210,7 +210,7 @@ deps =
bpython==0.7.1
colorlog==6.6.0
google-cloud-storage==1.30.0
- httpx2[http2,socks]==2.0.0
+ httpx2[http2,socks]==2.3.0
ipython==8.15.0
psutil==5.9.0
ptpython==3.0.23