Skip to content

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

Small cleanups after bumping Twisted. (#8385)

Andrey Rakhmatullin4001c07fea04
diff --git a/scrapy/http/request/__init__.py b/scrapy/http/request/__init__.py
index 8173e4872..c696f8f41 100644
--- a/scrapy/http/request/__init__.py
+++ b/scrapy/http/request/__init__.py
@@ -67,12 +67,11 @@ _in_download_handler: ContextVar[bool] = ContextVar(
def _active_crawler_scope(crawler: Crawler) -> Generator[None, None, None]:
"""Set _active_crawler to *crawler* for the duration of the block.
- Restores the previous value with set() instead of reset(): on some
- supported Twisted versions, the code after an ``await`` may resume in
- a copied contextvars.Context, where the token from the original set()
- is invalid. The block may also be exited from an unrelated context, e.g.
- when an abandoned coroutine is garbage-collected, so the previous value
- is only restored where the value set here is still in place.
+ Restores the previous value with set() instead of reset(), and only where
+ the value set here is still in place: the block may be exited from an
+ unrelated context, e.g. when an abandoned coroutine is garbage-collected,
+ where the token from the original set() is invalid and the current value
+ belongs to that context.
"""
previous = _active_crawler.get()
_active_crawler.set(crawler)
diff --git a/scrapy/pipelines/media.py b/scrapy/pipelines/media.py
index e18dc5c2d..983c150ca 100644
--- a/scrapy/pipelines/media.py
+++ b/scrapy/pipelines/media.py
@@ -257,28 +257,6 @@ class MediaPipeline(ABC):
result.frames.clear()
if TWISTED_FAILURE_HAS_STACK:
result.stack.clear()
- # This code fixes a memory leak by avoiding to keep references to
- # the Request and Response objects on the Media Pipeline cache.
- #
- # What happens when the media_downloaded callback raises an
- # exception, for example a FileException('download-error') when
- # the Response status code is not 200 OK, is that the original
- # StopIteration exception (which in turn contains the failed
- # Response and by extension, the original Request) gets encapsulated
- # within the FileException context.
- #
- # Originally, Scrapy was using twisted.internet.defer.returnValue
- # inside functions decorated with twisted.internet.defer.inlineCallbacks,
- # encapsulating the returned Response in a _DefGen_Return exception
- # instead of a StopIteration.
- #
- # To avoid keeping references to the Response and therefore Request
- # objects on the Media Pipeline cache, we should wipe the context of
- # the encapsulated exception when it is a StopIteration instance
- context = getattr(result.value, "__context__", None)
- if isinstance(context, StopIteration):
- assert result.value is not None
- result.value.__context__ = None
info.downloading.remove(fp)
info.downloaded[fp] = result # cache result
diff --git a/scrapy/utils/_ssl.py b/scrapy/utils/_ssl.py
index d15f80493..4a67d3450 100644
--- a/scrapy/utils/_ssl.py
+++ b/scrapy/utils/_ssl.py
@@ -194,8 +194,7 @@ def _get_cert_options_version_kwargs(
if min_version:
# We cannot pass both insecurelyLowerMinimumTo and raiseMinimumTo,
# so we need to know the direction.
-
- # 1.0 in Twisted 22.8.0 and older, 1.2 in Twisted 22.10.0 and newer
+ # 1.2 in all currently supported Twisted versions
default_min = CertificateOptions._defaultMinimumTLSVersion
if min_version < default_min:
result["insecurelyLowerMinimumTo"] = min_version
diff --git a/tests/test_pipeline_media.py b/tests/test_pipeline_media.py
index fcf23928e..b325f981d 100644
--- a/tests/test_pipeline_media.py
+++ b/tests/test_pipeline_media.py
@@ -11,7 +11,6 @@ from scrapy import signals
from scrapy.exceptions import ScrapyDeprecationWarning
from scrapy.http import Request, Response
from scrapy.pipelines.media import (
- FileException,
FileInfo,
FileInfoOrError,
MediaPipeline,
@@ -99,76 +98,6 @@ class TestBaseMediaPipeline:
self.pipe._modify_media_request(request)
assert request.meta == {"handle_httpstatus_all": True}
- def test_should_remove_req_res_references_before_caching_the_results(self):
- """Regression test case to prevent a memory leak in the Media Pipeline.
-
- The memory leak is triggered when an exception is raised when a Response
- scheduled by the Media Pipeline is being returned. For example, when a
- FileException('download-error') is raised because the Response status
- code is not 200 OK.
-
- It happens because we are keeping a reference to the Response object
- inside the FileException context. This is caused by the way Twisted
- return values from inline callbacks. It raises a custom exception
- encapsulating the original return value.
-
- The solution is to remove the exception context when this context is a
- _DefGen_Return instance, the BaseException used by Twisted to pass the
- returned value from those inline callbacks.
-
- Maybe there's a better and more reliable way to test the case described
- here, but it would be more complicated and involve running - or at least
- mocking - some async steps from the Media Pipeline. The current test
- case is simple and detects the problem very fast. On the other hand, it
- would not detect another kind of leak happening due to old object
- references being kept inside the Media Pipeline cache.
-
- This problem does not occur in Python 2.7 since we don't have Exception
- Chaining (https://www.python.org/dev/peps/pep-3134/).
- """
- # Create sample pair of Request and Response objects
- request = Request("http://url")
- response = Response("http://url", body=b"", request=request)
-
- # Simulate the Media Pipeline behavior to produce a Twisted Failure
- try:
- # Simulate a Twisted inline callback returning a Response
- raise StopIteration(response)
- except StopIteration as exc:
- def_gen_return_exc = exc
- try:
- # Simulate the media_downloaded callback raising a FileException
- # This usually happens when the status code is not 200 OK
- raise FileException("download-error")
- except Exception as exc:
- file_exc = exc
- # Simulate Twisted capturing the FileException
- # It encapsulates the exception inside a Twisted Failure
- failure = Failure(file_exc)
-
- # The Failure should encapsulate a FileException ...
- assert failure.value == file_exc
- # ... and it should have the StopIteration exception set as its context
- assert failure.value.__context__ == def_gen_return_exc
-
- # Let's calculate the request fingerprint and fake some runtime data...
- fp = self.fingerprint(request)
- info = self.pipe.spiderinfo
- info.downloading.add(fp)
- info.waiting[fp] = []
-
- # When calling the method that caches the Request's result ...
- self.pipe._cache_result_and_execute_waiters(failure, fp, info)
- # ... it should store the Twisted Failure ...
- downloaded = info.downloaded[fp]
- assert downloaded == failure
- # ... encapsulating the original FileException ...
- assert isinstance(downloaded, Failure)
- assert downloaded.value == file_exc
- # ... but it should not store the StopIteration exception on its context
- context = getattr(downloaded.value, "__context__", None)
- assert context is None
-
def test_default_item_completed(self, caplog: pytest.LogCaptureFixture) -> None:
item = {"name": "name"}
assert self.pipe.item_completed([], item, self.info) is item
diff --git a/tox.ini b/tox.ini
index 6a0dc4888..e030f07ce 100644
--- a/tox.ini
+++ b/tox.ini
@@ -208,6 +208,7 @@ deps =
{[min]deps}
Pillow==9.2.0
Twisted[http2]==23.8.0
+ h2==3.2.0
python-socks[asyncio]==2.6.0
siosocks==0.2.0 # SOCKS server for tests
boto3==1.35.2