Scrapy, a fast high-level web crawling & scraping framework for Python.
Limit memory used by media pipeline and other download_async() requests (#8417)
Adriana0e3b34479d2
diff --git a/docs/news.rst b/docs/news.rstindex 9db7a6a19..07df72a52 100644--- a/docs/news.rst+++ b/docs/news.rst@@ -6,6 +6,22 @@ Release notesScrapy VERSION (unreleased)---------------------------+Security bug fixes+~~~~~~~~~~~~~~~~~~++- Scrapy now limits by default the memory that responses can take, fixing+ `CVE-2017-14158`_.++ In previous Scrapy versions, that memory had no limit. For example, when+ :ref:`media pipelines <topics-media-pipeline>` downloaded files faster than+ they could store them, e.g. to Amazon S3, the downloaded files piled up in+ memory, so a crawled website could make Scrapy run out of memory.++ To change or disable the limit, use the new+ :setting:`RESPONSE_MAX_ACTIVE_SIZE` setting.++ .. _CVE-2017-14158: https://github.com/advisories/GHSA-h7wm-ph43-c39p+Backward-incompatible changes~~~~~~~~~~~~~~~~~~~~~~~~~~~~~diff --git a/docs/topics/api.rst b/docs/topics/api.rstindex 56c4f2819..a96e7f36d 100644--- a/docs/topics/api.rst+++ b/docs/topics/api.rst@@ -208,8 +208,8 @@ Engine API==========.. autoclass:: scrapy.core.engine.ExecutionEngine()- :members: close_spider_async, needs_backout, response_active_size, running,- scheduler, state+ :members: close_spider_async, download_async, needs_backout,+ response_active_size, running, scheduler, state.. autoclass:: scrapy.core.engine.EngineState:members:diff --git a/docs/topics/settings.rst b/docs/topics/settings.rstindex 4484166bd..d099cfb8e 100644--- a/docs/topics/settings.rst+++ b/docs/topics/settings.rst@@ -2042,29 +2042,47 @@ RESPONSE_MAX_ACTIVE_SIZEDefault: ``5_000_000``-Soft limit (in bytes) on the total size of responses being kept in memory.+Soft limit (in bytes) on the total size of responses being kept in memory. A+higher value improves crawl speed at the cost of memory usage. ``0`` disables+the limit.-This counts both the size of response bodies that have passed through+It counts the body size of responses that have been downloaded or returned by:ref:`downloader middlewares <topics-downloader-middleware>` and remain inmemory, and the :setting:`rough size <RESPONSE_ROUGH_SIZE>` of requests-currently being downloaded.--While the total is above this value, Scrapy pauses sending new requests to the-downloader. A higher value improves crawl speed at the cost of memory usage.-``0`` disables the limit.+currently being downloaded. While that total is above this value, Scrapy stops+taking requests from the scheduler. While the part of it that comes from+requests sent with :meth:`~scrapy.core.engine.ExecutionEngine.download_async`,+which include :ref:`awaited requests <inline-requests>` and those of+:ref:`media pipelines <topics-media-pipeline>`, is above this value, new+requests of that kind wait before being downloaded.++Requests already being downloaded when the limit is reached still finish: up to+:setting:`CONCURRENT_REQUESTS` from the scheduler, and up to this value divided+by :setting:`RESPONSE_ROUGH_SIZE` sent with+:meth:`~scrapy.core.engine.ExecutionEngine.download_async`. So, in practice,+responses can take up to about twice this value, plus the size of the responses+to those requests.++If requests have been waiting for 5 seconds with none being downloaded and no+response released, e.g. because your code keeps responses, Scrapy runs Python's+garbage collector, and if that releases no response, lets one request through.+Each time that happens, memory use can grow by one more response, and the+:stat:`response_max_active_size/bypass_count` stat increases. Scrapy logs a+warning the first time it does.Scrapy logs an info-level message the first time the limit is reached. To see-how long request processing was paused because of it over a whole crawl, check-the :stat:`request_backout_seconds/response_max_active_size` stat.+how long Scrapy stopped taking requests from the scheduler because of it over a+whole crawl, check the :stat:`request_backout_seconds/response_max_active_size`+stat... caution::Responses that your code keeps a strong reference to, e.g. in the:attr:`.Request.meta` of a scheduled request or in a component attribute,count toward this limit until that reference is gone, so accumulating them- can pause a crawl indefinitely. So do responses in a reference cycle,- until Python's garbage collector frees them. To find out whether your- crawl keeps responses alive, see :ref:`topics-leaks`.+ slows down a crawl. So do responses in a reference cycle, until Python's+ garbage collector frees them. To find out whether your crawl keeps+ responses alive, see :ref:`topics-leaks`... setting:: RESPONSE_ROUGH_SIZEdiff --git a/docs/topics/stats.rst b/docs/topics/stats.rstindex 1dd64297b..3dfcfb18c 100644--- a/docs/topics/stats.rst+++ b/docs/topics/stats.rst@@ -619,8 +619,8 @@ one per actual value of the placeholder... stat:: request_backout_seconds/response_max_active_size``request_backout_seconds/response_max_active_size``- Seconds during which sending requests to the downloader was paused because- :setting:`RESPONSE_MAX_ACTIVE_SIZE` was reached.+ Seconds during which sending requests from the scheduler to the downloader+ was paused because :setting:`RESPONSE_MAX_ACTIVE_SIZE` was reached... stat:: request_backout_seconds/total@@ -644,6 +644,12 @@ one per actual value of the placeholder.Set by :class:`~scrapy.spidermiddlewares.depth.DepthMiddleware`.+.. stat:: response_max_active_size/bypass_count++``response_max_active_size/bypass_count``+ Number of requests that were downloaded despite+ :setting:`RESPONSE_MAX_ACTIVE_SIZE`, to keep the crawl from stalling.+.. stat:: response_received_count``response_received_count``diff --git a/scrapy/commands/shell.py b/scrapy/commands/shell.pyindex d0b02733d..c2eb206b4 100644--- a/scrapy/commands/shell.py+++ b/scrapy/commands/shell.py@@ -33,6 +33,9 @@ class Command(ScrapyCommand):"LOGSTATS_INTERVAL": 0,"TELNETCONSOLE_ENABLED": False,"REMOTE_CONTROL_ENABLED": False,+ # The shell keeps the previous response while fetch() downloads the+ # next one.+ "RESPONSE_MAX_ACTIVE_SIZE": 0,}def syntax(self) -> str:diff --git a/scrapy/core/downloader/__init__.py b/scrapy/core/downloader/__init__.pyindex babb9a010..762ed2ab5 100644--- a/scrapy/core/downloader/__init__.py+++ b/scrapy/core/downloader/__init__.py@@ -1,10 +1,12 @@from __future__ import annotationsimport asyncio+import gcimport randomimport warningsfrom collections import dequefrom dataclasses import dataclass, field+from functools import partialfrom logging import getLoggerfrom time import monotonic, perf_counter, timefrom typing import TYPE_CHECKING, Any@@ -20,8 +22,10 @@ from scrapy.settings import SETTINGS_PRIORITIESfrom scrapy.utils.asyncio import (AsyncioLoopingCall,CallLaterResult,+ _get_running_or_installed_loop,call_later,create_looping_call,+ is_asyncio_available,sleep,)from scrapy.utils.decorators import _warn_spider_arg@@ -34,7 +38,7 @@ from scrapy.utils.httpobj import urlparse_cachedfrom scrapy.utils.misc import build_from_crawlerif TYPE_CHECKING:- from collections.abc import Generator+ from collections.abc import Callable, Generator, Iterablefrom twisted.internet.task import LoopingCall@@ -70,6 +74,14 @@ def _start_delay_countdown(request: Request) -> None:request.meta["delayed"] = [*request.meta.get("delayed", []), delay]+def _examples(responses: Iterable[Response]) -> str:+ held = [str(response) for response in responses]+ examples = ", ".join(held[:3])+ if len(held) > 3:+ examples += f" (+{len(held) - 3} more)"+ return examples++@dataclass(slots=True, eq=False)class Slot:"""Downloader slot"""@@ -85,6 +97,9 @@ class Slot:transferring: set[Request] = field(default_factory=set, init=False, repr=False)lastseen: float = field(default=0, init=False, repr=False)latercall: CallLaterResult | None = field(default=None, init=False, repr=False)+ # Number of requests in queue not sent with+ # ExecutionEngine.download_async().+ _scheduled_queued: int = field(default=0, init=False, repr=False)# Hand-written to accept the deprecated randomize_delay parameter, which# means it also has to initialize the fields above.@@ -116,6 +131,7 @@ class Slot:self.transferring = set()self.lastseen = 0self.latercall = None+ self._scheduled_queued = 0@propertydef randomize_delay(self) -> bool:@@ -210,6 +226,9 @@ _STAMPED_SLOT_META_KEY = "_download_slot_stamp"class Downloader:DOWNLOAD_SLOT = "download_slot"_SLOT_GC_INTERVAL: float = 60.0 # seconds+ # Seconds that requests held back by RESPONSE_MAX_ACTIVE_SIZE wait for a+ # release before one of them is let through.+ _SIZE_BYPASS_DELAY: float = 5.0def __init__(self, crawler: Crawler):self.crawler: Crawler = crawler@@ -241,6 +260,18 @@ class Downloader:# (None, None) if not backing out.self._last_backout: tuple[str | None, float | None] = (None, None)self._max_active_size_warned = False+ # Whether _next_transfer_index() has held back a request that nothing+ # has resumed yet.+ self._size_blocked = False+ self._unscheduled_transfers = 0+ self._size_bypass_call: CallLaterResult | None = None+ self._size_bypass_due = False+ self._size_bypass_warned = False+ # (start_time, total_size): since when RESPONSE_MAX_ACTIVE_SIZE has held+ # back scheduled requests with no download in progress, and the total+ # active size then, or (None, 0) if it is not holding them back.+ self._size_stall: tuple[float | None, int] = (None, 0)+ self._size_stall_warned = False@propertydef randomize_delay(self) -> bool:@@ -257,6 +288,23 @@ class Downloader:def fetch(self, request: Request, spider: Spider | None = None) -> Generator[Deferred[Any], Any, Response | Request]:+ # Set on the first download, once there is an event loop or reactor+ # for response finalizers, which can run in any thread, to call back+ # into. close() unsets it.+ if (+ self._accepting_requests+ and self.middleware._on_unscheduled_response_release is None+ ):+ call_from_thread: Callable[[Callable[[], None]], object]+ if is_asyncio_available():+ call_from_thread = _get_running_or_installed_loop().call_soon_threadsafe+ else:+ from twisted.internet import reactor++ call_from_thread = reactor.callFromThread+ self.middleware._on_unscheduled_response_release = lambda size: (+ call_from_thread(partial(self._on_unscheduled_response_release, size))+ )self.active.add(request)self.middleware._count_rough_size(request)try:@@ -289,7 +337,7 @@ class Downloader:if 0 < self.total_concurrency <= len(self.active):self._record_backout("concurrency")return True- if self._exceeds_max_active_size():+ if self._exceeds_max_active_size() and not self._size_stall_ended():self._record_backout("response_max_active_size")if not self._max_active_size_warned:self._max_active_size_warned = True@@ -303,9 +351,72 @@ class Downloader:f"stat. This message is only logged once.")return True+ self._size_stall = (None, 0)self._record_backout(None)return False+ def _size_stall_ended(self) -> bool:+ """Return whether to let a scheduled request through+ RESPONSE_MAX_ACTIVE_SIZE because it has held scheduled requests back+ for _SIZE_BYPASS_DELAY seconds with no download or scraping in+ progress and no response released, or because garbage collection+ lifted it.++ This keeps responses that something keeps alive, e.g. in a reference+ cycle, from stalling the crawl.+ """+ start_time, size = self._size_stall+ current_time = monotonic()+ current_size = self.middleware._total_active_size+ engine = self.crawler.engine+ scheduled = bool(+ engine and engine._slot and engine._slot.scheduler.has_pending_requests()+ )+ # A response that is still being scraped is not garbage yet.+ scraping = bool(+ engine and engine.scraper.slot and not engine.scraper.slot.is_idle()+ )+ if (+ self.active+ or scraping+ or not scheduled+ or start_time is None+ or current_size < size+ ):+ self._size_stall = (current_time, current_size)+ return False+ if current_time - start_time < self._SIZE_BYPASS_DELAY:+ return False+ self._size_stall = (None, 0)+ if self._collect_responses():+ return not self._exceeds_max_active_size()+ assert self._stats is not None+ self._stats.inc_value("response_max_active_size/bypass_count")+ if not self._size_stall_warned:+ self._size_stall_warned = True+ logger.warning(+ f"Letting a request through RESPONSE_MAX_ACTIVE_SIZE: "+ f"responses, e.g. "+ f"{_examples(self.middleware._tracked_responses)}, have used "+ f"{current_size} B for at least {self._SIZE_BYPASS_DELAY:g} "+ f"seconds with no request being downloaded, and garbage "+ f"collection did not release them. If your code keeps "+ f"responses, e.g. in the meta or cb_kwargs of scheduled "+ f"requests, release them. See "+ f"https://docs.scrapy.org/en/latest/topics/settings.html#response-max-active-size "+ f"and the response_max_active_size/bypass_count stat. "+ f"This message is only logged once."+ )+ return True++ def _collect_responses(self) -> bool:+ """Run the garbage collector and return whether it released any+ response counted toward RESPONSE_MAX_ACTIVE_SIZE.+ """+ size = self.middleware._response_active_size+ gc.collect()+ return self.middleware._response_active_size < size+def _exceeds_max_active_size(self) -> bool:max_active_size = self.middleware._max_active_sizereturn (@@ -388,6 +499,8 @@ class Downloader:)d: Deferred[Response] = Deferred()slot.queue.append((request, d))+ if request not in self.middleware._unscheduled_requests:+ slot._scheduled_queued += 1self._process_queue(slot)try:return await maybe_deferred_to_future(d) # fired in _wait_for_download()@@ -410,11 +523,20 @@ class Downloader:# Process enqueued requests if there are free slots to transfer for this slotwhile slot.queue and slot.free_transfer_slots() > 0:+ index = self._next_transfer_index(slot)+ if index is None:+ break+ request, queue_dfd = slot.queue[index]+ del slot.queue[index]slot.lastseen = now- request, queue_dfd = slot.queue.popleft()# Do this immediately so that following free_transfer_slots() calls# account for this request.slot.transferring.add(request)+ if request in self.middleware._unscheduled_requests:+ self._unscheduled_transfers += 1+ self._cancel_size_bypass()+ else:+ slot._scheduled_queued -= 1download_dfd = deferred_from_coro(self._wait_for_download(slot, request, queue_dfd))@@ -454,6 +576,9 @@ class Downloader:try:# 1. Download the responseresponse: Response = await self.handlers.download_request_async(request)+ # Counted before _end_transfer() resumes queued requests, so that+ # _next_transfer_index() accounts for it.+ self.middleware._count_response_size(response, request)# 2. Notify response_downloaded listeners about the recent download# before querying queue for next requestself.signals.send_catch_log(@@ -473,9 +598,133 @@ class Downloader:# middleware itself)self._end_transfer(slot, request)+ def _add_unscheduled_request(self, request: Request) -> None:+ self.middleware._unscheduled_requests.add(request)++ def _unscheduled_size_exceeded(self) -> bool:+ """Return whether RESPONSE_MAX_ACTIVE_SIZE holds back requests sent+ with ExecutionEngine.download_async().++ Those requests skip the engine backout, so they are limited here,+ against the responses to such requests alone. Responses to scheduled+ requests are limited by the engine backout.+ """+ middleware = self.middleware+ if not middleware._max_active_size:+ return False+ size = (+ middleware._unscheduled_response_active_size+ + self._unscheduled_transfers * middleware._response_rough_size+ )+ return size >= middleware._max_active_size++ def _next_transfer_index(self, slot: Slot) -> int | None:+ """Return the index of the first request in the queue of *slot* that+ RESPONSE_MAX_ACTIVE_SIZE does not hold back, or None if there is+ none.+ """+ if not self._unscheduled_size_exceeded():+ return 0+ unscheduled = self.middleware._unscheduled_requests+ first = slot.queue[0][0]+ if first in unscheduled:+ if self._size_bypass_due:+ self._bypass_size_limit(first)+ return 0+ self._size_blocked = True+ self._schedule_size_bypass()+ if not slot._scheduled_queued:+ return None+ return next(+ (+ index+ for index, (request, _) in enumerate(slot.queue)+ if request not in unscheduled+ ),+ None,+ )++ def _resume_size_blocked(self) -> None:+ if not self._size_blocked:+ return+ # Scheduled requests queued behind held-back ones do not need this:+ # they are only waiting for their slot.+ if self._unscheduled_size_exceeded() and not self._size_bypass_due:+ self._schedule_size_bypass()+ return+ self._size_blocked = False+ # A slot with held-back requests may have no transfer of its own to+ # resume it.+ for slot in list(self.slots.values()):+ if slot.queue:+ self._process_queue(slot)++ def _on_unscheduled_response_release(self, size: int) -> None:+ self.middleware._unscheduled_response_active_size -= size+ self._cancel_size_bypass()+ self._resume_size_blocked()++ def _schedule_size_bypass(self) -> None:+ """Let a request held back by _next_transfer_index() through after+ _SIZE_BYPASS_DELAY seconds without a release, unless a transfer that+ it may be waiting for is in progress.++ This keeps code that holds a response to a download_async() request+ while it awaits another one from stalling the crawl.+ """+ if self._size_bypass_call is not None or self._unscheduled_transfers:+ return+ self._size_bypass_call = call_later(+ self._SIZE_BYPASS_DELAY, self._size_bypass_timeout+ )++ def _cancel_size_bypass(self) -> None:+ self._size_bypass_due = False+ if self._size_bypass_call is not None:+ self._size_bypass_call.cancel()+ self._size_bypass_call = None++ def _size_bypass_timeout(self) -> None:+ self._size_bypass_call = None+ if self._collect_responses():+ # Give the release a chance to resume held-back requests before+ # letting one through.+ self._schedule_size_bypass()+ return+ # Stays due until a held-back request uses it, which a slot waiting+ # for its download delay or for a free transfer slot does later.+ self._size_bypass_due = True+ self._resume_size_blocked()++ def _bypass_size_limit(self, request: Request) -> None:+ self._size_bypass_due = False+ assert self._stats is not None+ self._stats.inc_value("response_max_active_size/bypass_count")+ if self._size_bypass_warned:+ return+ self._size_bypass_warned = True+ logger.warning(+ f"Letting {request} through RESPONSE_MAX_ACTIVE_SIZE: responses "+ f"to awaited requests or requests sent with download_async(), "+ f"e.g. {_examples(self.middleware._unscheduled_responses)}, have "+ f"used {self.middleware._unscheduled_response_active_size} B for "+ f"at least {self._SIZE_BYPASS_DELAY:g} seconds with none of those "+ f"requests being downloaded, and garbage collection did not "+ f"release them. If your code keeps such a response "+ f"while it awaits another such request, release it first. See "+ f"https://docs.scrapy.org/en/latest/topics/settings.html#response-max-active-size "+ f"and the response_max_active_size/bypass_count stat. "+ f"This message is only logged once."+ )+def _end_transfer(self, slot: Slot, request: Request) -> None:slot.transferring.remove(request)+ unscheduled = request in self.middleware._unscheduled_requests+ if unscheduled:+ self._unscheduled_transfers -= 1self._process_queue(slot)+ if unscheduled:+ self._resume_size_blocked()self.signals.send_catch_log(signal=signals.request_left_downloader,request=request,@@ -538,6 +787,8 @@ class Downloader:self._stop_slot_gc()for slot in self.slots.values():slot.close()+ self._cancel_size_bypass()+ self.middleware._on_unscheduled_response_release = Noneself._record_backout(None)async def _close_async(self) -> None:diff --git a/scrapy/core/downloader/middleware.py b/scrapy/core/downloader/middleware.pyindex 8c316f6fd..d5d527c27 100644--- a/scrapy/core/downloader/middleware.py+++ b/scrapy/core/downloader/middleware.py@@ -88,6 +88,12 @@ class DownloaderMiddlewareManager(MiddlewareManager): # pylint: disable=abstracself._tracked_responses: WeakSet[Response] = WeakSet()self._rough_active_size = 0self._rough_sizes: dict[Request, int] = {}+ # Requests sent with ExecutionEngine.download_async(), and the+ # responses to them, which the downloader limits separately.+ self._unscheduled_requests: WeakSet[Request] = WeakSet()+ self._unscheduled_responses: WeakSet[Response] = WeakSet()+ self._unscheduled_response_active_size = 0+ self._on_unscheduled_response_release: Callable[[int], object] | None = Noneself._response_exceptions = settings.getbool("DOWNLOADER_MIDDLEWARE_RESPONSE_EXCEPTIONS")@@ -139,10 +145,19 @@ class DownloaderMiddlewareManager(MiddlewareManager): # pylint: disable=abstracself._tracked_responses.add(response)size = len(response.body)self._response_active_size += size- finalize(response, partial(self._discount_response_size, size))+ unscheduled = request in self._unscheduled_requests+ if unscheduled:+ self._unscheduled_responses.add(response)+ self._unscheduled_response_active_size += size+ finalize(+ response,+ partial(self._discount_response_size, size, unscheduled=unscheduled),+ )- def _discount_response_size(self, size: int) -> None:+ def _discount_response_size(self, size: int, *, unscheduled: bool) -> None:self._response_active_size -= size+ if unscheduled and self._on_unscheduled_response_release is not None:+ self._on_unscheduled_response_release(size)def download(self,diff --git a/scrapy/core/engine.py b/scrapy/core/engine.pyindex ded2ba30e..f151cbc1f 100644--- a/scrapy/core/engine.py+++ b/scrapy/core/engine.py@@ -687,7 +687,7 @@ class ExecutionEngine:self._slot.add_request(request)try:response_or_request = await maybe_deferred_to_future(- self._download(request)+ self._download(request, unscheduled=True))finally:self._slot.remove_request(request)@@ -697,11 +697,14 @@ class ExecutionEngine:@inlineCallbacksdef _download(- self, request: Request+ self, request: Request, *, unscheduled: bool = False) -> Generator[Deferred[Any], Any, Response | Request]:assert self._slot is not None # typingassert self.spider is not None+ if unscheduled and hasattr(self.downloader, "_add_unscheduled_request"):+ self.downloader._add_unscheduled_request(request)+# Lets Request.__await__() find this crawler while the downloader# middlewares run.with _active_crawler_scope(self.crawler):diff --git a/tests/test_downloader.py b/tests/test_downloader.pyindex 7bdf9e129..71e86a71f 100644--- a/tests/test_downloader.py+++ b/tests/test_downloader.py@@ -8,13 +8,17 @@ import pytestfrom twisted.internet.defer import Deferredfrom twisted.python.failure import Failure-from scrapy import Request, Spider+from scrapy import Request, Spider, signals+from scrapy.core.downloader import Downloader+from scrapy.core.downloader.handlers.datauri import DataURIDownloadHandler+from scrapy.core.engine import ExecutionEnginefrom scrapy.crawler import Crawlerfrom scrapy.exceptions import IgnoreRequest, ScrapyDeprecationWarningfrom scrapy.http import HtmlResponse, Response+from scrapy.http.request import NO_CALLBACKfrom scrapy.pipelines.files import FilesPipelinefrom scrapy.utils.asyncio import call_later, sleep-from scrapy.utils.defer import maybe_deferred_to_future+from scrapy.utils.defer import deferred_from_coro, maybe_deferred_to_futurefrom scrapy.utils.test import get_crawlerfrom tests.utils.decorators import coroutine_test@@ -492,11 +496,13 @@ class TestRequestBackout:)@coroutine_testasync def test_response_max_active_size_no_cycles(- self, status, callback, errback, settings+ self, monkeypatch, status, callback, errback, settings):"""Scrapy frees responses through reference counting alone, so a crawldoes not stall on RESPONSE_MAX_ACTIVE_SIZE without garbagecollection."""+ # Keep the bypass, which collects garbage first, from lifting a stall.+ monkeypatch.setattr(Downloader, "_SIZE_BYPASS_DELAY", 60)class ResponseMiddleware:def process_request(self, request):@@ -529,7 +535,10 @@ class TestRequestBackout:assert crawler.stats.get_value("downloader/response_count") == 3@coroutine_test- async def test_response_max_active_size_no_cycles_media(self, tmp_path):+ async def test_response_max_active_size_no_cycles_media(+ self, monkeypatch, tmp_path+ ):+ monkeypatch.setattr(Downloader, "_SIZE_BYPASS_DELAY", 60)class ResponseMiddleware:def process_request(self, request):@@ -735,3 +744,332 @@ class TestRequestBackout:"request_backout_seconds/total": gt(0),}assert _backout_stats(crawler) == expected_stats++ @pytest.mark.parametrize("shared_slot", [True, False])+ @coroutine_test+ async def test_response_max_active_size_media_downloads(self, shared_slot):+ """Responses of media pipeline requests waiting for a slow upload hold+ back the next media downloads.+ """+ max_active_size = 3000+ uploads = 0+ peak_uploads = 0++ class SlowStore(_NoStatStore):+ async def persist_file(self, path, buf, info, meta=None, headers=None):+ nonlocal uploads, peak_uploads+ uploads += 1+ peak_uploads = max(peak_uploads, uploads)+ await sleep(0.05)+ uploads -= 1++ class TestSpider(_MediaSpider):+ file_count = 20+ file_size = 1000+ custom_settings = {+ "FILES_STORE": "test://",+ "ITEM_PIPELINES": {+ _SharedSlotFilesPipeline+ if shared_slot+ else _SlotPerFileFilesPipeline: 1+ },+ "MEDIA_STORAGES": {"test": SlowStore},+ "RESPONSE_MAX_ACTIVE_SIZE": max_active_size,+ "RESPONSE_ROUGH_SIZE": file_size,+ }++ crawler = get_crawler(TestSpider)+ await maybe_deferred_to_future(crawler.crawl())++ assert crawler.stats+ assert crawler.stats.get_value("file_count") == 20+ assert peak_uploads == max_active_size // TestSpider.file_size+ assert crawler.stats.get_value("response_max_active_size/bypass_count") is None++ @coroutine_test+ async def test_response_max_active_size_scheduled_response_with_files(self):+ """A scheduled response above the limit does not hold back the media+ downloads that it waits for.+ """++ class TestSpider(_MediaSpider):+ start_urls = [f"data:,{'a' * 2000}"]+ custom_settings = {+ "FILES_STORE": "test://",+ "ITEM_PIPELINES": {_SharedSlotFilesPipeline: 1},+ "MEDIA_STORAGES": {"test": _NoStatStore},+ "RESPONSE_MAX_ACTIVE_SIZE": 1000,+ }+ file_count = 3+ file_size = 10++ crawler = get_crawler(TestSpider)+ await maybe_deferred_to_future(crawler.crawl())++ assert crawler.stats+ assert crawler.stats.get_value("file_count") == 3+ assert crawler.stats.get_value("response_max_active_size/bypass_count") is None++ @coroutine_test+ async def test_response_max_active_size_scheduled_request_behind_held_back(+ self, monkeypatch+ ):+ """Scheduled requests queued in a slot behind a held-back+ download_async() request are downloaded first, and the bypass lets it+ through even if it is due while the slot waits for its download+ delay. Once it is through, scheduled requests are not held back.+ """+ monkeypatch.setattr(Downloader, "_SIZE_BYPASS_DELAY", 0.01)+ downloads: list[int | str] = []+ scheduled_reached: Deferred[None] = Deferred()+ scheduled_downloaded: Deferred[None] = Deferred()++ class Handler(DataURIDownloadHandler):+ async def download_request(self, request: Request) -> Response:+ # Keeps the slot busy until the scheduled requests are queued+ # behind the held-back one.+ if request.meta.get("wait_for_scheduled"):+ await maybe_deferred_to_future(scheduled_reached)+ return await super().download_request(request)++ class TestSpider(Spider):+ name = "test"+ start_urls = ["data:,"]+ custom_settings = {+ "CONCURRENT_REQUESTS_PER_DOMAIN": 1,+ "DOWNLOAD_DELAY": 0.2,+ "DOWNLOAD_DELAY_JITTER": 0,+ "DOWNLOAD_HANDLERS": {"data": Handler},+ "RESPONSE_MAX_ACTIVE_SIZE": 1000,+ "RESPONSE_ROUGH_SIZE": 1,+ }+ scheduled_count = 0++ def request_reached_downloader(self, request: Request) -> None:+ if request.url[-1].isdigit():+ self.scheduled_count += 1+ if self.scheduled_count == 4:+ scheduled_reached.callback(None)++ def response_downloaded(self, response: Response) -> None:+ if response.url == "data:,a":+ downloads.append("a")+ elif response.url[-1].isdigit():+ downloads.append(int(response.text))+ if len(downloads) == 5:+ scheduled_downloaded.callback(None)++ async def parse(self, response):+ assert self.crawler.engine+ self.crawler.signals.connect(+ self.request_reached_downloader,+ signals.request_reached_downloader,+ )+ self.crawler.signals.connect(+ self.response_downloaded, signals.response_downloaded+ )+ download_async = self.crawler.engine.download_async+ kept_dfd = deferred_from_coro(+ download_async(+ Request(+ f"data:,{'a' * 2000}", meta={"wait_for_scheduled": True}+ )+ )+ )+ held_back_dfd = deferred_from_coro(download_async(Request("data:,a")))+ for n in range(4):+ yield Request(f"data:,{n}", callback=self.parse_b)+ kept = await maybe_deferred_to_future(kept_dfd)+ await maybe_deferred_to_future(held_back_dfd)+ await maybe_deferred_to_future(scheduled_downloaded)+ assert kept+ yield {}++ def parse_b(self, response):+ pass++ crawler = get_crawler(TestSpider)+ crawl_deferred = crawler.crawl()+ # Scheduled requests held back after the bypass would otherwise hang+ # the test.+ timeout = call_later(10, crawl_deferred.cancel)+ try:+ await maybe_deferred_to_future(crawl_deferred)+ finally:+ timeout.cancel()++ assert crawler.stats+ assert downloads == [3, "a", 2, 1, 0]+ assert crawler.stats.get_value("response_max_active_size/bypass_count") == 1++ @pytest.mark.parametrize(+ ("kept_count", "kept_size", "examples", "more"),+ [(1, 2000, 1, ""), (4, 300, 3, " (+1 more)")],+ )+ @coroutine_test+ async def test_response_max_active_size_bypass(+ self, monkeypatch, kept_count, kept_size, examples, more+ ):+ """Code that keeps a response to a download_async() request above the+ limit while it awaits another one slows down instead of stalling.+ """+ monkeypatch.setattr(Downloader, "_SIZE_BYPASS_DELAY", 0.01)++ class TestSpider(Spider):+ name = "test"+ start_urls = ["data:,"]+ custom_settings = {+ "RESPONSE_MAX_ACTIVE_SIZE": 1000,+ }++ async def parse(self, response):+ assert self.crawler.engine+ kept = [+ await self.crawler.engine.download_async(+ Request(f"data:,{n:0{kept_size}}")+ )+ for n in range(kept_count)+ ]+ for n in range(2):+ await self.crawler.engine.download_async(Request(f"data:,{n}"))+ assert kept+ yield {}++ crawler = get_crawler(TestSpider)+ self.caplog.clear()+ with self.caplog.at_level("INFO"):+ await maybe_deferred_to_future(crawler.crawl())++ assert crawler.stats+ assert crawler.stats.get_value("item_scraped_count") == 1+ assert crawler.stats.get_value("response_max_active_size/bypass_count") == 2+ messages = [+ record.getMessage()+ for record in self.caplog.records+ if record.getMessage().startswith("Letting")+ ]+ assert len(messages) == 1+ assert "<GET data:,0>" in messages[0]+ assert messages[0].count("<200 data:,") == examples+ assert f">{more}, have used" in messages[0]++ @coroutine_test+ async def test_response_max_active_size_scheduled_bypass(self, monkeypatch):+ """Code that keeps responses to scheduled requests above the limit+ slows down instead of stalling.+ """+ monkeypatch.setattr(Downloader, "_SIZE_BYPASS_DELAY", 0.01)+ monkeypatch.setattr(ExecutionEngine, "_SLOT_HEARTBEAT_INTERVAL", 0.01)++ class TestSpider(Spider):+ name = "test"+ start_urls = [f"data:,{n}" for n in range(3)]+ custom_settings = {+ "RESPONSE_MAX_ACTIVE_SIZE": 1,+ }+ kept: list[Response] = []++ def parse(self, response):+ self.kept.append(response)++ crawler = get_crawler(TestSpider)+ self.caplog.clear()+ with self.caplog.at_level("INFO"):+ crawl_deferred = crawler.crawl()+ # A stall would otherwise hang the test.+ timeout = call_later(10, crawl_deferred.cancel)+ try:+ await maybe_deferred_to_future(crawl_deferred)+ finally:+ timeout.cancel()++ assert crawler.stats+ assert crawler.stats.get_value("response_received_count") == 3+ assert crawler.stats.get_value("response_max_active_size/bypass_count") == 2+ records = [+ record+ for record in self.caplog.records+ if record.getMessage().startswith("Letting")+ ]+ assert len(records) == 1+ assert records[0].levelno == logging.WARNING+ assert "<200 data:," in records[0].getMessage()++ @pytest.mark.parametrize("awaited", [False, True])+ @coroutine_test+ async def test_response_max_active_size_collects_cycles(self, monkeypatch, awaited):+ """Responses in a reference cycle stop counting toward the limit once+ it holds back requests, even with automatic garbage collection+ disabled.+ """+ monkeypatch.setattr(Downloader, "_SIZE_BYPASS_DELAY", 0.01)+ monkeypatch.setattr(ExecutionEngine, "_SLOT_HEARTBEAT_INTERVAL", 0.01)++ def keep_in_cycle(response: Response) -> None:+ cycle: list[Any] = [response]+ cycle.append(cycle)++ class TestSpider(Spider):+ name = "test"+ start_urls = ["data:,"] if awaited else [f"data:,{n}" for n in range(3)]+ custom_settings = {+ "RESPONSE_MAX_ACTIVE_SIZE": 1,+ }++ async def parse(self, response):+ if not awaited:+ keep_in_cycle(response)+ yield {}+ return+ assert self.crawler.engine+ for n in range(3):+ keep_in_cycle(+ await self.crawler.engine.download_async(Request(f"data:,{n}"))+ )+ yield {}++ crawler = get_crawler(TestSpider)+ await _crawl_without_gc(crawler)++ assert crawler.stats+ assert crawler.stats.get_value("item_scraped_count") == 3+ assert crawler.stats.get_value("response_max_active_size/bypass_count") is None+++class _NoStatStore:+ checksum_algorithm = "md5"++ def __init__(self, uri: str):+ pass++ def stat_file(self, path, info):+ return {}++ def persist_file(self, path, buf, info, meta=None, headers=None):+ pass+++class _SharedSlotFilesPipeline(FilesPipeline):+ pass+++class _SlotPerFileFilesPipeline(FilesPipeline):+ def get_media_requests(self, item, info):+ return [+ Request(url, meta={"download_slot": url}, callback=NO_CALLBACK)+ for url in item["file_urls"]+ ]+++class _MediaSpider(Spider):+ name = "test"+ start_urls = ["data:,"]+ file_count: int+ file_size: int++ def parse(self, response):+ yield {+ "file_urls": [+ f"data:,{n:0{self.file_size}}" for n in range(self.file_count)+ ]+ }diff --git a/tests/test_engine.py b/tests/test_engine.pyindex cea864620..b97eb05c1 100644--- a/tests/test_engine.py+++ b/tests/test_engine.py@@ -8,6 +8,7 @@ from typing import TYPE_CHECKING, Anyfrom unittest.mock import AsyncMock, Mock, patchimport pytest+from twisted.internet.defer import succeedfrom twisted.python.failure import Failurefrom scrapy import signals@@ -48,6 +49,7 @@ if TYPE_CHECKING:from twisted.internet.defer import Deferred+ from scrapy.crawler import Crawlerfrom tests.mockserver.http import MockServer@@ -621,6 +623,39 @@ async def test_download_wrong_type(caplog: pytest.LogCaptureFixture) -> None:assert "expected Response or Request, got <class 'str'>" in caplog.text+@coroutine_test+async def test_download_async_custom_downloader() -> None:+ class CustomDownloader:+ def __init__(self, crawler: Crawler) -> None:+ self.active: set[Request] = set()++ def fetch(self, request: Request) -> Deferred[Response]:+ return succeed(Response(request.url))++ def needs_backout(self) -> bool:+ return False++ def close(self) -> None:+ pass++ responses: list[Response] = []++ class DownloadAsyncSpider(Spider):+ name = "download_async"++ async def start(self):+ assert self.crawler.engine is not None+ responses.append(+ await self.crawler.engine.download_async(Request("data:,"))+ )+ return+ yield++ crawler = get_crawler(DownloadAsyncSpider, {"DOWNLOADER": CustomDownloader})+ await crawler.crawl_async()+ assert [response.url for response in responses] == ["data:,"]++@coroutine_testasync def test_enqueue_scrape_error(caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch