-
Notifications
You must be signed in to change notification settings - Fork 28
Implement a request fingerprinter that accounts for dependencies #172
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
Merged
Merged
Changes from 12 commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
a39ef5c
Implement a request fingerprinter that accounts for dependencies
Gallaecio 1e8af9a
Fix circular dependency caused by isort
Gallaecio c3bb97d
Fix test naming
Gallaecio a1d9d04
fallback → base
Gallaecio d740418
Do not let dependency order affect fingerprints
Gallaecio 6bb32a2
test file: fingerprinting → fingerprinter
Gallaecio 99ba579
Test caching
Gallaecio cc2bb24
tests/__init__.py → scrapy_poet/utils/testing.py
Gallaecio 5bb01ec
Merge 2 test cases with a lot of shared code
Gallaecio 2af611d
Test different URLs
Gallaecio dc40040
Add tests for DummyResponse, responseless inputs and (lack of) depend…
Gallaecio 3af6693
Use fully-qualified names for dependency serialization
Gallaecio a611fd2
Ignore some (unannotated) page input dependencies
Gallaecio 23b7c33
Count page params towards request fingerprinting
Gallaecio e8f0322
Test that meta (empty page params and arbitrary keys) does not impact…
Gallaecio e2c5b17
Address feedback
Gallaecio a72f7c2
Fix typing
Gallaecio bf93c2b
Merge remote-tracking branch 'scrapinghub/master' into request-finger…
Gallaecio 596431b
Document the use of repr() for annotation fingerprinting
Gallaecio 55326a4
Implement dependency resolution
Gallaecio 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
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
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 |
---|---|---|
@@ -0,0 +1,102 @@ | ||
try: | ||
from scrapy.utils.request import RequestFingerprinter # NOQA | ||
except ImportError: | ||
from typing import TYPE_CHECKING | ||
|
||
if not TYPE_CHECKING: | ||
ScrapyPoetRequestFingerprinter = None | ||
else: | ||
import hashlib | ||
import json | ||
from functools import cached_property | ||
from typing import Callable, Dict, List, Optional, get_args, get_origin | ||
from weakref import WeakKeyDictionary | ||
|
||
from scrapy import Request | ||
from scrapy.crawler import Crawler | ||
from scrapy.settings.default_settings import REQUEST_FINGERPRINTER_CLASS | ||
from scrapy.utils.misc import create_instance, load_object | ||
|
||
from scrapy_poet import InjectionMiddleware | ||
from scrapy_poet.injection import get_callback | ||
|
||
def _serialize_dep(cls): | ||
try: | ||
from typing import Annotated | ||
except ImportError: | ||
pass | ||
else: | ||
if get_origin(cls) is Annotated: | ||
annotated, *annotations = get_args(cls) | ||
return f"{_serialize_dep(annotated)}{repr(annotations)}" | ||
return f"{cls.__module__}.{cls.__qualname__}" | ||
Gallaecio marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
class ScrapyPoetRequestFingerprinter: | ||
@classmethod | ||
def from_crawler(cls, crawler): | ||
return cls(crawler) | ||
|
||
def __init__(self, crawler: Crawler) -> None: | ||
settings = crawler.settings | ||
self._base_request_fingerprinter = create_instance( | ||
load_object( | ||
settings.get( | ||
"SCRAPY_POET_REQUEST_FINGERPRINTER_BASE_CLASS", | ||
REQUEST_FINGERPRINTER_CLASS, | ||
) | ||
), | ||
settings=crawler.settings, | ||
crawler=crawler, | ||
) | ||
self._callback_cache: Dict[Callable, bytes] = {} | ||
self._request_cache: "WeakKeyDictionary[Request, bytes]" = ( | ||
WeakKeyDictionary() | ||
) | ||
self._crawler: Crawler = crawler | ||
|
||
@cached_property | ||
def _injector(self): | ||
middlewares = self._crawler.engine.downloader.middleware.middlewares | ||
for middleware in middlewares: | ||
if isinstance(middleware, InjectionMiddleware): | ||
return middleware.injector | ||
Gallaecio marked this conversation as resolved.
Show resolved
Hide resolved
|
||
raise RuntimeError( | ||
"scrapy_poet.InjectionMiddleware not found at run time, has it " | ||
"been configured in the DOWNLOADER_MIDDLEWARES setting?" | ||
) | ||
|
||
def _get_deps(self, request: Request) -> Optional[List[str]]: | ||
"""Return a JSON-serializable structure that uniquely identifies the | ||
dependencies requested by the request, or None if dependency injection | ||
is not required.""" | ||
plan = self._injector.build_plan(request) | ||
root_deps = plan[-1][1] | ||
if not root_deps: | ||
return None | ||
return sorted([_serialize_dep(cls) for cls in root_deps.values()]) | ||
|
||
def fingerprint_deps(self, request: Request) -> Optional[bytes]: | ||
"""Return a fingerprint based on dependencies requested through | ||
scrapy-poet injection, or None if no injection was requested.""" | ||
callback = get_callback(request, self._crawler.spider) | ||
if callback in self._callback_cache: | ||
return self._callback_cache[callback] | ||
|
||
deps = self._get_deps(request) | ||
if deps is None: | ||
return None | ||
Gallaecio marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
deps_key = json.dumps(deps, sort_keys=True).encode() | ||
self._callback_cache[callback] = hashlib.sha1(deps_key).digest() | ||
Gallaecio marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return self._callback_cache[callback] | ||
|
||
def fingerprint(self, request: Request) -> bytes: | ||
if request in self._request_cache: | ||
return self._request_cache[request] | ||
fingerprint = self._base_request_fingerprinter.fingerprint(request) | ||
deps_fingerprint = self.fingerprint_deps(request) | ||
if deps_fingerprint is None: | ||
return fingerprint | ||
fingerprints = fingerprint + deps_fingerprint | ||
self._request_cache[request] = hashlib.sha1(fingerprints).digest() | ||
return self._request_cache[request] |
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.
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.