Skip to content
Draft
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: 1 addition & 1 deletion docs/03_concepts/21_events.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ Persisted state only helps if it's still there on the next run. Crawlee purges t

The `use_state` helper of the crawling context returns a dictionary that's saved automatically. Every call within a crawler returns the same dictionary, so you can read and update it from any request handler. Crawlee saves it to the default key-value store on every `PERSIST_STATE` event and when the run finishes, and loads it back from there when the crawler starts again with existing storage. The optional argument sets the initial value when no saved state exists yet.

The dictionary is stored under the `CRAWLEE_STATE_<id>` key, where the id is the crawler's `id` argument or, without one, a per-process counter of crawler instances. Pass the same `id` to the constructors of several crawlers to make them share their state. Outside request handlers, use <ApiLink to="class/BasicCrawler#use_state">`crawler.use_state()`</ApiLink>. Values have to be JSON serializable.
The dictionary is stored under the `CRAWLEE_STATE_<id>` key, where the id is the crawler's `id` argument or, without one, a per-process counter of crawler instances. Each crawler instance in a process needs its own `id`. To share state between several crawlers, call the standalone <ApiLink to="function/use_state">`use_state`</ApiLink> function from `crawlee.storages` with an explicit key, which returns the same dictionary for the same key. Outside request handlers, use <ApiLink to="class/BasicCrawler#use_state">`crawler.use_state()`</ApiLink>. Values have to be JSON serializable.

The following example stores the page title of every visited URL in the crawler state and reads it after the run:

Expand Down
18 changes: 13 additions & 5 deletions src/crawlee/crawlers/_basic/_basic_crawler.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from http import HTTPStatus
from io import StringIO
from pathlib import Path
from typing import TYPE_CHECKING, Any, Generic, Literal, ParamSpec, cast
from typing import TYPE_CHECKING, Any, ClassVar, Generic, Literal, ParamSpec, cast
from weakref import WeakKeyDictionary

from cachetools import LRUCache
Expand Down Expand Up @@ -219,8 +219,8 @@ class _BasicCrawlerOptions(TypedDict):
Returning `None` suppresses the status message."""

id: NotRequired[int]
"""Identifier used for crawler state tracking. Use the same id across multiple crawlers to share state between
them."""
"""Identifier used for crawler state tracking. Two crawler instances in the same process cannot use the same
explicit id. To share state between crawlers, use `crawlee.storages.use_state` with an explicit key."""


class _BasicCrawlerOptionsGeneric(TypedDict, Generic[TCrawlingContext, TStatisticsState]):
Expand Down Expand Up @@ -280,6 +280,7 @@ class BasicCrawler(Generic[TCrawlingContext, TStatisticsState]):
_ROBOTS_TXT_MAX_ATTEMPTS = 3
_request_handler_timeout_text = 'Request handler timed out after'
__next_id = 0
__explicit_ids: ClassVar[set[int]] = set()

def __init__(
self,
Expand Down Expand Up @@ -366,8 +367,9 @@ def __init__(
status_message_logging_interval: Interval for logging the crawler status messages.
status_message_callback: Allows overriding the default status message. The default status message is
provided in the parameters. Returning `None` suppresses the status message.
id: Identifier used for crawler state tracking. Use the same id across multiple crawlers to share state
between them.
id: Identifier used for crawler state tracking. Two crawler instances in the same process cannot use the
same explicit id. To share state between crawlers, use `crawlee.storages.use_state` with an explicit
key.
_context_pipeline: Enables extending the request lifecycle and modifying the crawling context.
Intended for use by subclasses rather than direct instantiation of `BasicCrawler`.
_additional_context_managers: Additional context managers used throughout the crawler lifecycle.
Expand All @@ -378,6 +380,8 @@ def __init__(
if id is None:
self._id = BasicCrawler.__next_id
BasicCrawler.__next_id += 1
elif id in BasicCrawler.__explicit_ids:
raise ValueError(f'Crawler id {id} is already in use')
else:
self._id = id

Expand Down Expand Up @@ -522,6 +526,10 @@ async def persist_state_factory() -> KeyValueStore:
self._unexpected_stop = False
self._logger_once = LoggerOnce(self._logger)

# Registered last, so that a constructor that fails earlier leaves the id free for a retry.
if id is not None:
BasicCrawler.__explicit_ids.add(id)

@property
def log(self) -> logging.Logger:
"""The logger used by the crawler."""
Expand Down
2 changes: 2 additions & 0 deletions src/crawlee/storages/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from ._dataset import Dataset
from ._key_value_store import KeyValueStore
from ._request_queue import RequestQueue
from ._use_state import use_state

__all__ = [
'Dataset',
'KeyValueStore',
'RequestQueue',
'use_state',
]
47 changes: 47 additions & 0 deletions src/crawlee/storages/_use_state.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from __future__ import annotations

from typing import TYPE_CHECKING

from crawlee._utils.docs import docs_group

from ._key_value_store import KeyValueStore

if TYPE_CHECKING:
from collections.abc import MutableMapping

from crawlee._types import JsonSerializable
from crawlee.configuration import Configuration

GLOBAL_STATE_KEY = 'CRAWLEE_GLOBAL_STATE'


@docs_group('Functions')
async def use_state(
key: str = GLOBAL_STATE_KEY,
default_value: MutableMapping[str, JsonSerializable] | None = None,
*,
key_value_store_name: str | None = None,
configuration: Configuration | None = None,
) -> MutableMapping[str, JsonSerializable]:
"""Return a dictionary that is persisted automatically to a key-value store.

Every call with the same `key` and key-value store returns the same dictionary, so crawlers and any other code
in the process can share state through it. The dictionary is saved on every persist state event and loaded
back from the key-value store when it already holds a record under `key`. Values have to be JSON serializable.

Warning:
This is an experimental feature. The behavior and interface may change in future versions.

Args:
key: Key of the key-value store record that holds the state.
default_value: Initial value used when the key-value store has no record under `key` yet.
key_value_store_name: Name of the key-value store that holds the state. The default store is used if
not provided.
configuration: Configuration used to open the key-value store. The global configuration is used if not
provided.

Returns:
The persisted state dictionary.
"""
kvs = await KeyValueStore.open(name=key_value_store_name, configuration=configuration)
return await kvs.get_auto_saved_value(key, default_value)
1 change: 1 addition & 0 deletions tests/_fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ def _prepare_test_env() -> None:
KeyValueStore._autosaved_values = {}
Statistics._Statistics__next_id = 0 # ty:ignore[missing-attribute] # Mangled attribute
BasicCrawler._BasicCrawler__next_id = 0 # ty:ignore[missing-attribute] # Mangled attribute
BasicCrawler._BasicCrawler__explicit_ids.clear() # ty:ignore[missing-attribute] # Mangled attribute

return _prepare_test_env

Expand Down
39 changes: 30 additions & 9 deletions tests/unit/crawlers/_basic/test_basic_crawler.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import pytest

from crawlee import ConcurrencySettings, Glob, service_locator
from crawlee._autoscaling import Snapshotter
from crawlee._log_config import CrawleeLogFormatter
from crawlee._request import Request, RequestState
from crawlee._types import BasicCrawlingContext, EnqueueLinksKwargs
Expand All @@ -42,7 +43,7 @@
from crawlee.sessions import Session, SessionPool
from crawlee.statistics import FinalStatistics, StatisticsState
from crawlee.storage_clients import FileSystemStorageClient, MemoryStorageClient
from crawlee.storages import Dataset, KeyValueStore, RequestQueue
from crawlee.storages import Dataset, KeyValueStore, RequestQueue, use_state
from tests._utils import open_throttler_held_until_reclaim, poll_until_condition

if TYPE_CHECKING:
Expand Down Expand Up @@ -1105,31 +1106,51 @@ async def handler(context: BasicCrawlingContext) -> None:
await crawler.run(['https://hello.world'])


async def test_context_use_state_crawlers_share_state() -> None:
def test_duplicate_explicit_id_is_rejected() -> None:
"""A crawler with an explicit id that another crawler already uses fails, while a distinct id is accepted."""
BasicCrawler(id=1)

with pytest.raises(ValueError, match='Crawler id 1 is already in use'):
BasicCrawler(id=1)

BasicCrawler(id=2)


def test_explicit_id_is_released_when_construction_fails(monkeypatch: pytest.MonkeyPatch) -> None:
"""An explicit id can be reused after a constructor that used it raised."""
with monkeypatch.context() as patch_context:
patch_context.setattr(Snapshotter, 'from_config', Mock(side_effect=RuntimeError('construction failed')))

with pytest.raises(RuntimeError, match='construction failed'):
BasicCrawler(id=1)

BasicCrawler(id=1)


async def test_crawlers_share_state_through_standalone_use_state() -> None:
"""Crawlers with distinct ids share state through the standalone `use_state` with an explicit key."""

async def handler(context: BasicCrawlingContext) -> None:
state = await context.use_state({'urls': []})
state = await use_state('shared-state', {'urls': []})
assert isinstance(state['urls'], list)
state['urls'].append(context.request.url)

crawler_1 = BasicCrawler(id=0, request_handler=handler)
crawler_2 = BasicCrawler(id=0, request_handler=handler)
crawler_2 = BasicCrawler(id=1, request_handler=handler)

await crawler_1.run(['https://a.com'])
await crawler_2.run(['https://b.com'])

kvs = await KeyValueStore.open()
assert crawler_1._id == crawler_2._id == 0
assert await kvs.get_value(f'{BasicCrawler._CRAWLEE_STATE_KEY}_{crawler_1._id}') == {
'urls': ['https://a.com', 'https://b.com']
}
assert await kvs.get_value('shared-state') == {'urls': ['https://a.com', 'https://b.com']}


async def test_crawlers_share_stats() -> None:
async def handler(context: BasicCrawlingContext) -> None:
await context.use_state({'urls': []})

crawler_1 = BasicCrawler(id=0, request_handler=handler)
crawler_2 = BasicCrawler(id=0, request_handler=handler, statistics=crawler_1.statistics)
crawler_2 = BasicCrawler(id=1, request_handler=handler, statistics=crawler_1.statistics)

result1 = await crawler_1.run(['https://a.com'])
result2 = await crawler_2.run(['https://b.com'])
Expand Down
34 changes: 34 additions & 0 deletions tests/unit/storages/test_use_state.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from __future__ import annotations

from crawlee.storages import KeyValueStore, use_state


async def test_use_state_returns_same_dictionary_for_same_key() -> None:
"""Calls with the same key return the same dictionary, initialized from the default value."""
state = await use_state('my-state', {'count': 0})
state['count'] = 1

assert await use_state('my-state') is state
assert state == {'count': 1}


async def test_use_state_uses_global_key_by_default() -> None:
"""Without a key, the state is persisted under the global state key of the default store."""
state = await use_state()
state['hello'] = 'world'

kvs = await KeyValueStore.open()
await kvs.persist_autosaved_values()

assert await kvs.get_value('CRAWLEE_GLOBAL_STATE') == {'hello': 'world'}


async def test_use_state_uses_named_key_value_store() -> None:
"""The state is persisted to the key-value store with the given name."""
state = await use_state('my-state', {'hello': 'world'}, key_value_store_name='my-store')

kvs = await KeyValueStore.open(name='my-store')
await kvs.persist_autosaved_values()

assert await kvs.get_value('my-state') == state
assert await (await KeyValueStore.open()).get_value('my-state') is None
Loading