Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/06_upgrading/upgrading_to_v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,8 @@ async def main() -> None:

The `id` argument of `BasicCrawler` and its subclasses is now a `str`, so pass a string wherever you passed an integer. `StatisticsState.stats_id` and `EventCrawlerStatusData.crawler_id` are strings too, and `crawler_id` holds the crawler's `id`. In v1, it held the Python object ID of the crawler.

The crawler `id` is part of key-value store keys, such as `CRAWLEE_STATE_{id}`, so the constructor now raises `ValueError` for an `id` that can't be part of a valid key. The `id` must be at most 217 characters long and contain only the characters `a-zA-Z0-9!-_.'()`. The limit leaves room for the longest key prefix, `CRAWLEE_RENDERING_TYPE_PREDICTOR_STATE_`, within the 256-character key limit. Crawlee JS checks the same characters but allows 256 characters. A non-string `id`, such as an `int` from v1, raises `TypeError`. `SessionPool`, `Statistics` and `DefaultRenderingTypePredictor` check an explicit `id` the same way.

The statistics a crawler creates by default now use the `id` you pass to the crawler, except those of `AdaptivePlaywrightCrawler`, which aren't persisted. Crawlers that share an `id` therefore share both the state returned by `use_state` and the persisted statistics. In v1, they shared only the state. A later crawler with the same `id` continues the statistics of the earlier one, so its `max_requests_per_crawl` counts their requests too.

A crawler without an `id` gets its creation index, such as `'0'`, and crawlers with an explicit `id` now count towards that index too. If you resume a v1 run with `purge_on_start=False` and mix both kinds of crawlers, a generated `id` can differ from the one v1 assigned, and the crawler won't find the state that `use_state` stored under the old one. The default statistics of a crawler without an `id` get their `id` from a per-process counter of the `Statistics` instances created without one. v2 doesn't read the statistics that v1 persisted, as described in [Internal key-value store records are renamed](#internal-key-value-store-records-are-renamed).
Expand Down
30 changes: 30 additions & 0 deletions src/crawlee/_utils/ids.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from __future__ import annotations

import re

MAX_ID_LENGTH = 217
"""The longest ID that keeps every key built from it within the 256-character key-value store key limit. The longest
key prefix is `CRAWLEE_RENDERING_TYPE_PREDICTOR_STATE_`, with 39 characters."""

_ID_PATTERN = re.compile(rf"[a-zA-Z0-9!\-_.'()]{{1,{MAX_ID_LENGTH}}}")


def validate_id(value: object, owner: str) -> None:
"""Check that an ID can be part of a key-value store key.

Args:
value: The ID to check.
owner: The name of the class the ID belongs to, used in the error message.

Raises:
TypeError: If the ID isn't a string.
ValueError: If the ID is empty, too long, or contains a character that a key can't contain.
"""
if not isinstance(value, str):
raise TypeError(f'The `id` of `{owner}` must be a string, got {type(value).__name__}.')

if not _ID_PATTERN.fullmatch(value):
raise ValueError(
f'The `id` of `{owner}` must be at most {MAX_ID_LENGTH} characters long and contain only the characters '
f"a-zA-Z0-9!-_.'(), got {value!r}."
)
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from typing_extensions import override

from crawlee._utils.docs import docs_group
from crawlee._utils.ids import validate_id
from crawlee._utils.recoverable_state import RecoverableState

from ._utils import sklearn_model_serializer, sklearn_model_validator
Expand Down Expand Up @@ -141,15 +142,18 @@ def __init__(
detection_ratio: A number between 0 and 1 that determines the desired ratio of rendering type detections.
id: An identifier of the predictor, used in the default `persist_state_key`. Defaults to a per-process
counter of the `DefaultRenderingTypePredictor` instances created without an `id`. Explicit IDs share one
namespace with the generated ones, so avoid explicit IDs like `'0'` or `'1'`.
namespace with the generated ones, so avoid explicit IDs like `'0'` or `'1'`. It must be at most 217
characters long and contain only the characters `a-zA-Z0-9!-_.'()`.
persist_state_key: Key in the key-value storage where the trained model parameters will be saved.
Defaults to `CRAWLEE_RENDERING_TYPE_PREDICTOR_STATE_{id}`.
persistence_enabled: Whether to enable persistence of the trained model parameters for reuse.

"""
super().__init__()

if id is None:
if id is not None:
validate_id(id, type(self).__name__)
else:
id = str(DefaultRenderingTypePredictor.__next_id)
DefaultRenderingTypePredictor.__next_id += 1
self._id = id
Expand Down
10 changes: 8 additions & 2 deletions src/crawlee/crawlers/_basic/_basic_crawler.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
from crawlee._utils.file import atomic_write, export_csv_to_stream, export_json_to_stream
from crawlee._utils.globs import check_url_patterns
from crawlee._utils.http import parse_retry_after_header
from crawlee._utils.ids import validate_id
from crawlee._utils.log import LoggerOnce, request_log_extra
from crawlee._utils.recurring_task import RecurringTask
from crawlee._utils.robots import RobotsTxtFile
Expand Down Expand Up @@ -223,7 +224,8 @@ class _BasicCrawlerOptions(TypedDict):
every crawler but the first uses it in the alias of its default request queue. The crawler also passes it to the
default statistics and session pool. Without it, the ID follows the order in which crawlers are created, and the
statistics and the session pool generate their own IDs. Explicit IDs share one namespace with the generated ones, so
avoid explicit IDs like `'0'` or `'1'`."""
avoid explicit IDs like `'0'` or `'1'`. The ID is part of key-value store keys, so it must be at most 217 characters
long and contain only the characters `a-zA-Z0-9!-_.'()`."""


class _BasicCrawlerOptionsGeneric(TypedDict, Generic[TCrawlingContext, TStatisticsState]):
Expand Down Expand Up @@ -395,10 +397,14 @@ def __init__(
statistics, and every crawler but the first uses it in the alias of its default request queue. The
crawler also passes it to the default statistics and session pool. Without it, the ID follows the order
in which crawlers are created, and the statistics and the session pool generate their own IDs. Explicit
IDs share one namespace with the generated ones, so avoid explicit IDs like `'0'` or `'1'`.
IDs share one namespace with the generated ones, so avoid explicit IDs like `'0'` or `'1'`. The ID is
part of key-value store keys, so it must be at most 217 characters long and contain only the characters
`a-zA-Z0-9!-_.'()`.
_context_pipeline: Enables extending the request lifecycle and modifying the crawling context.
Intended for use by subclasses rather than direct instantiation of `BasicCrawler`.
"""
if id is not None:
validate_id(id, type(self).__name__)
self._id = str(BasicCrawler.__next_id) if id is None else id
self._default_rq_alias = None if BasicCrawler.__next_id == 0 else f'__default_{self._id}__'
BasicCrawler.__next_id += 1
Expand Down
8 changes: 7 additions & 1 deletion src/crawlee/sessions/_session_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from crawlee import service_locator
from crawlee._utils.context import ensure_context
from crawlee._utils.docs import docs_group
from crawlee._utils.ids import validate_id
from crawlee._utils.recoverable_state import RecoverableState
from crawlee.sessions import Session
from crawlee.sessions._models import SessionPoolModel
Expand Down Expand Up @@ -53,7 +54,8 @@ def __init__(
id: An identifier of the pool, used in the default `persist_state_key`. Defaults to a per-process counter of
the `SessionPool` instances created without an `id`, which includes the pools that crawlers without an
`id` create. Pass an `id` to a pool you persist, so that its key doesn't depend on the creation order.
Explicit IDs share one namespace with the generated ones, so avoid explicit IDs like `'0'` or `'1'`.
Explicit IDs share one namespace with the generated ones, so avoid explicit IDs like `'0'` or `'1'`. It
must be at most 217 characters long and contain only the characters `a-zA-Z0-9!-_.'()`.
max_pool_size: Maximum number of sessions to maintain in the pool. You can add more sessions to the pool
by using the `add_session` method.
create_session_settings: Settings for creating new session instances. If None, default settings will
Expand All @@ -66,9 +68,13 @@ def __init__(
persist_state_key: The key under which the session pool's state is stored in the `KeyValueStore`.
Defaults to `CRAWLEE_SESSION_POOL_STATE_{id}`.
"""
if id is not None:
validate_id(id, type(self).__name__)

if event_manager:
service_locator.set_event_manager(event_manager)

# A generated ID is taken only after the calls that can raise, so a failed construction doesn't skip one.
if id is None:
id = str(SessionPool.__next_id)
SessionPool.__next_id += 1
Expand Down
5 changes: 4 additions & 1 deletion src/crawlee/statistics/_statistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

from crawlee._utils.context import ensure_context
from crawlee._utils.docs import docs_group
from crawlee._utils.ids import validate_id
from crawlee._utils.recoverable_state import RecoverableState
from crawlee._utils.recurring_task import RecurringTask
from crawlee.statistics import FinalStatistics, StatisticsState
Expand Down Expand Up @@ -86,7 +87,9 @@ def __init__(
save_error_snapshots: bool = False,
id: str | None = None,
) -> None:
if id is None:
if id is not None:
validate_id(id, type(self).__name__)
else:
id = str(Statistics.__next_id)
Statistics.__next_id += 1
self._id = id
Expand Down
66 changes: 66 additions & 0 deletions tests/unit/_utils/test_ids.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
from __future__ import annotations

from typing import TYPE_CHECKING

import pytest

from crawlee._utils.ids import MAX_ID_LENGTH, validate_id
from crawlee.crawlers._adaptive_playwright._rendering_type_predictor import DefaultRenderingTypePredictor
from crawlee.sessions import SessionPool
from crawlee.statistics import Statistics

if TYPE_CHECKING:
from collections.abc import Callable


@pytest.mark.parametrize(
'value',
[
pytest.param('my-id', id='hyphen'),
pytest.param("a.b_c!(1)'", id='all allowed special characters'),
pytest.param('x' * MAX_ID_LENGTH, id='max length'),
],
)
def test_validate_id_accepts_valid_id(value: str) -> None:
"""An ID that can be part of a key-value store key passes."""
validate_id(value, 'Owner')


@pytest.mark.parametrize(
'value',
[
pytest.param('a/b', id='slash'),
pytest.param('', id='empty'),
pytest.param('x' * (MAX_ID_LENGTH + 1), id='too long'),
],
)
def test_validate_id_rejects_invalid_id(value: str) -> None:
"""An ID that can't be part of a key-value store key raises `ValueError` naming the owner."""
with pytest.raises(ValueError, match='The `id` of `Owner` must'):
validate_id(value, 'Owner')


def test_validate_id_rejects_non_string() -> None:
"""An ID that isn't a string raises `TypeError` naming the owner and the type."""
with pytest.raises(TypeError, match='The `id` of `Owner` must be a string, got int'):
validate_id(5, 'Owner')


@pytest.mark.parametrize(
'create_component',
[
pytest.param(lambda id: SessionPool(id=id), id='session pool'),
pytest.param(lambda id: Statistics.with_default_state(id=id), id='statistics'),
pytest.param(lambda id: DefaultRenderingTypePredictor(id=id), id='rendering type predictor'),
],
)
def test_components_reject_invalid_id(create_component: Callable[[str], object]) -> None:
"""The components that use their ID in a key-value store key reject an invalid ID."""
with pytest.raises(ValueError, match='must be at most'):
create_component('a/b')


def test_longest_key_of_max_length_id_fits_key_limit() -> None:
"""The longest key built from an ID of the maximum length is a valid 256-character key."""
predictor = DefaultRenderingTypePredictor(id='x' * MAX_ID_LENGTH)
assert len(predictor._state._persist_state_key) == 256
43 changes: 38 additions & 5 deletions tests/unit/crawlers/_basic/test_basic_crawler.py
Original file line number Diff line number Diff line change
Expand Up @@ -1521,13 +1521,46 @@ async def test_crawlers_do_not_share_requests() -> None:
assert stats_2.requests_finished == 1


async def test_id_invalid_as_request_queue_alias() -> None:
"""A later crawler whose ID can't form an RQ alias fails to open its RQ, unless it gets a request manager."""
@pytest.mark.parametrize(
'crawler_id',
[
pytest.param('shop/products', id='slash'),
pytest.param('my crawler', id='space'),
pytest.param('crawler-\u00fc', id='non-ascii'),
pytest.param('', id='empty'),
pytest.param('x' * 218, id='too long'),
],
)
def test_invalid_id_is_rejected(crawler_id: str) -> None:
"""A crawler `id` that can't be part of a key-value store key is rejected."""
with pytest.raises(ValueError, match='The `id` of `BasicCrawler` must'):
BasicCrawler(id=crawler_id)


def test_non_string_id_is_rejected() -> None:
"""A crawler `id` that isn't a string, such as a v1 `int`, is rejected with a `TypeError` that names it."""
with pytest.raises(TypeError, match='The `id` of `BasicCrawler` must be a string, got int'):
BasicCrawler(id=5) # ty: ignore[invalid-argument-type]


@pytest.mark.parametrize(
'crawler_id',
[
pytest.param('my-crawler', id='hyphen'),
pytest.param("a.b_c!(1)'", id='all allowed special characters'),
pytest.param('x' * 217, id='max length'),
],
)
def test_valid_id_is_accepted(crawler_id: str) -> None:
"""A crawler `id` that can be part of a key-value store key is accepted."""
assert BasicCrawler(id=crawler_id)._id == crawler_id


async def test_later_crawler_with_request_manager_uses_it() -> None:
"""A crawler created after the first one, with an explicit ID and a `request_manager`, uses that manager."""
BasicCrawler()
with pytest.raises(ValueError, match='Invalid storage alias'):
await BasicCrawler(id='shop/products').get_request_manager()
request_manager = Mock()
crawler = BasicCrawler(id='shop/products', request_manager=request_manager)
crawler = BasicCrawler(id='shop-products', request_manager=request_manager)
assert await crawler.get_request_manager() is request_manager


Expand Down
Loading