Skip to content
Open
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/01_architecture_overview.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ Crawlee defines several built-in event types:
- `MIGRATING` - Signals that the crawler is migrating to a different environment.
- `ABORTING` - Indicates the crawler is aborting execution.
- `EXIT` - Emitted when the crawler is exiting.
- `CRAWLER_STATUS` - Provides status updates from crawlers.
- `STATUS_MESSAGE` - Provides status updates from crawlers, including a terminal one when a run finishes.

Additional specialized events for browser and session management are also available.

Expand Down
2 changes: 1 addition & 1 deletion docs/03_concepts/21_events.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ The <ApiLink to="class/Event">`Event`</ApiLink> enum lists the event names. Each

- `PERSIST_STATE` carries <ApiLink to="class/EventPersistStateData">`EventPersistStateData`</ApiLink>. It's emitted when the event manager starts, then at every `persist_state_interval`, and one last time when it closes. Its `is_migrating` flag tells whether the process is about to be migrated.
- `SYSTEM_INFO` carries <ApiLink to="class/EventSystemInfoData">`EventSystemInfoData`</ApiLink> with the CPU usage ratio and the memory used by the current process and its children. The `LocalEventManager` emits it at every `system_info_interval`.
- `CRAWLER_STATUS` carries <ApiLink to="class/EventCrawlerStatusData">`EventCrawlerStatusData`</ApiLink> with the same status message that the crawler periodically logs.
- `STATUS_MESSAGE` carries <ApiLink to="class/EventStatusMessageData">`EventStatusMessageData`</ApiLink> with the same status message that the crawler periodically logs and its log level. When a run finishes, the crawler emits a summary of the finished requests with `is_status_message_terminal` set to `True`.
- `MIGRATING`, `ABORTING`, and `EXIT` carry <ApiLink to="class/EventMigratingData">`EventMigratingData`</ApiLink>, <ApiLink to="class/EventAbortingData">`EventAbortingData`</ApiLink>, and <ApiLink to="class/EventExitData">`EventExitData`</ApiLink>. Crawlee itself never emits them locally. They come from a platform, for example from the event manager of the [Apify SDK](https://docs.apify.com/sdk/python) when an Actor run is migrated to another server or aborted.

The enum also defines session pool and browser pool event names, such as `SESSION_RETIRED` or `BROWSER_LAUNCHED`, which Crawlee for Python doesn't emit.
Expand Down
43 changes: 42 additions & 1 deletion docs/06_upgrading/upgrading_to_v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,45 @@ async def main() -> None:

`Event` now subclasses `enum.StrEnum`. Calling `str()` on a member or formatting it in an f-string returns its value, for example `'systemInfo'`. In v1, `str()` returned `'Event.SYSTEM_INFO'`, and so did an f-string on Python 3.11 and newer. Comparisons with plain strings work the same way as in v1.

## `STATUS_MESSAGE` replaces `CRAWLER_STATUS`

The `Event.CRAWLER_STATUS` event is replaced by `Event.STATUS_MESSAGE`, whose value is `'statusMessage'`, the same as in Crawlee JS. Its payload model `EventCrawlerStatusData` is replaced by `EventStatusMessageData`, which keeps `crawler_id` and `message` and adds two fields:

- `is_status_message_terminal` is `True` for the final status message of a run, and `False` for the periodic ones.
- `level` is the log level the message was logged with.

When a `status_message_callback` returns `None`, the crawler neither logs nor emits that status message. In v1, it still emitted the event with the default message. The terminal message is emitted with or without a callback.

When a run finishes, the crawler logs and emits a terminal message at INFO, such as `Finished! Total 3 requests: 2 succeeded, 1 failed.` Integrations such as the Apify SDK can use it as the final status of the run.

**Before (v1):**

```python
from crawlee import service_locator
from crawlee.events import Event, EventCrawlerStatusData


def on_status(event_data: EventCrawlerStatusData) -> None:
print(event_data.message)


service_locator.get_event_manager().on(event=Event.CRAWLER_STATUS, listener=on_status)
```

**Now (v2):**

```python
from crawlee import service_locator
from crawlee.events import Event, EventStatusMessageData


def on_status(event_data: EventStatusMessageData) -> None:
print(event_data.message, event_data.is_status_message_terminal)


service_locator.get_event_manager().on(event=Event.STATUS_MESSAGE, listener=on_status)
```

## A zero timeout cancels right away

A zero `close_timeout` of an event manager, or a zero `timeout` passed to `EventManager.wait_for_all_listeners_to_complete()`, cancels the running listeners right away. A zero `wait_for_all_requests_to_be_added_timeout` in `add_requests()` with `wait_for_all_requests_to_be_added=True` does the same for the requests still being added. In v1, a zero timeout meant no limit. To wait without a limit, pass `None`.
Expand Down Expand Up @@ -550,7 +589,7 @@ async def main() -> None:

### Crawler `id` is a string

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 `id` argument of `BasicCrawler` and its subclasses is now a `str`, so pass a string wherever you passed an integer. `StatisticsState.stats_id` and `EventStatusMessageData.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.

Expand Down Expand Up @@ -1416,6 +1455,8 @@ The DEBUG messages that `AutoscaledPool` logged as it scheduled and finished tas

The periodic and final statistics logs name the renamed fields, for example `requests_succeeded` in place of `requests_finished`. For the full list, see [`*finished*` request statistics are renamed to `*succeeded*`](#finished-request-statistics-are-renamed-to-succeeded).

When a run finishes, the crawler logs a new INFO message `Finished! Total <n> requests: <succeeded> succeeded, <failed> failed.` For details, see [`STATUS_MESSAGE` replaces `CRAWLER_STATUS`](#status_message-replaces-crawler_status).

When a crawl processes no requests because its request manager holds only handled ones, the crawler logs a new warning. It starts with `This crawl processed no requests` and explains how to crawl the requests again.

Messages that mentioned a storage client name the storage backend instead. The DEBUG message about the implicit default backend now reads `No storage backend set, implicitly creating and using default FileSystemStorageBackend.` The warning about unsupported arguments of a dataset backend ends with the backend class name, for example `... of get_data are not supported by MemoryDatasetBackend.`
Expand Down
49 changes: 34 additions & 15 deletions src/crawlee/crawlers/_basic/_basic_crawler.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
UserDefinedErrorHandlerError,
UserHandlerTimeoutError,
)
from crawlee.events._types import Event, EventCrawlerStatusData
from crawlee.events._types import Event, EventStatusMessageData
from crawlee.http_clients import ImpitHttpClient
from crawlee.request_loaders import MinIntervalSignal, RateLimitedSignal
from crawlee.router import Router
Expand Down Expand Up @@ -1064,6 +1064,17 @@ async def _run_crawler(self) -> None:
event_manager.off(event=Event.MIGRATING, listener=self._pause_by_event)
event_manager.off(event=Event.ABORTING, listener=self._pause_by_event)

# The exit stack cancels the recurring task next, with no await in between, so no periodic status
# message can follow the terminal one.
state = self._statistics.state
total = state.requests_succeeded + state.requests_failed
self._set_status_message(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Finished! ... is logged before Error analysis, The crawl was interrupted... and Final request statistics. In Crawlee JS it is the last line. After Ctrl+C, the log says "Finished!" and then "interrupted". Fine to keep if emitting later is not practical.

✍️ Drafted by Claude Code

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd keep it here. The Error analysis, interrupted and final statistics lines are logged in run(), after _run_crawler has exited the event manager, where emit raises unless someone else keeps it active. Moving the message there would mean restructuring how the contexts are entered.

Written with Claude Code (AI).

f'Finished! Total {total} requests: {state.requests_succeeded} succeeded, '
f'{state.requests_failed} failed.',
level='INFO',
is_terminal=True,
)

async def _pause_by_event(self) -> None:
"""Pause the crawl before the process migrates or is aborted, so that no request is left half-done."""
if self._dispatching_run is not None:
Expand Down Expand Up @@ -2087,20 +2098,33 @@ async def _find_txt_file_for_url(self, url: str) -> RobotsTxtFile:

raise RuntimeError('Unreachable code')

def _log_status_message(self, message: str, level: LogLevel = 'DEBUG') -> None:
"""Log a status message for the crawler.
def _set_status_message(
self,
message: str,
*,
level: LogLevel,
is_terminal: bool = False,
) -> None:
"""Log a status message for the crawler and emit it as a `STATUS_MESSAGE` event.

Args:
message: The status message to log.
message: The status message.
level: The logging level for the message.
is_terminal: Whether this is the final status message of the run.
"""
log_level = string_to_log_level(level)
self.log.log(log_level, message)
self.log.log(string_to_log_level(level), message)

async def _crawler_state_task(self) -> None:
"""Emit a persist state event with the given migration status."""
event_manager = self._service_locator.get_event_manager()
event_data = EventStatusMessageData(
crawler_id=self._id,
message=message,
is_status_message_terminal=is_terminal,
level=level,
)
event_manager.emit(event=Event.STATUS_MESSAGE, event_data=event_data)

async def _crawler_state_task(self) -> None:
"""Log and emit the periodic status message of the crawler."""
current_state = self.statistics.state

if (
Expand Down Expand Up @@ -2128,14 +2152,9 @@ async def _crawler_state_task(self) -> None:
if self._status_message_callback:
new_message = await self._status_message_callback(current_state, self._run.previous_state, message)
if new_message:
message = new_message
self._log_status_message(message, level='INFO')
self._set_status_message(new_message, level='INFO')
else:
self._log_status_message(message, level='INFO')

event_manager.emit(
event=Event.CRAWLER_STATUS, event_data=EventCrawlerStatusData(message=message, crawler_id=self._id)
)
self._set_status_message(message, level='INFO')

# `Statistics` updates its state in place, so the next status update compares against a copy.
self._run.previous_state = current_state.model_copy(deep=True)
Expand Down
4 changes: 2 additions & 2 deletions src/crawlee/events/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,25 @@
from ._types import (
Event,
EventAbortingData,
EventCrawlerStatusData,
EventData,
EventExitData,
EventListener,
EventMigratingData,
EventPersistStateData,
EventStatusMessageData,
EventSystemInfoData,
)

__all__ = [
'Event',
'EventAbortingData',
'EventCrawlerStatusData',
'EventData',
'EventExitData',
'EventListener',
'EventManager',
'EventMigratingData',
'EventPersistStateData',
'EventStatusMessageData',
'EventSystemInfoData',
'LocalEventManager',
]
6 changes: 3 additions & 3 deletions src/crawlee/events/_event_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@
from crawlee.events._types import (
Event,
EventAbortingData,
EventCrawlerStatusData,
EventExitData,
EventListener,
EventMigratingData,
EventPersistStateData,
EventStatusMessageData,
EventSystemInfoData,
)

Expand Down Expand Up @@ -157,7 +157,7 @@ def on(self, *, event: Literal[Event.ABORTING], listener: EventListener[EventAbo
@overload
def on(self, *, event: Literal[Event.EXIT], listener: EventListener[EventExitData]) -> None: ...
@overload
def on(self, *, event: Literal[Event.CRAWLER_STATUS], listener: EventListener[EventCrawlerStatusData]) -> None: ...
def on(self, *, event: Literal[Event.STATUS_MESSAGE], listener: EventListener[EventStatusMessageData]) -> None: ...
@overload
def on(self, *, event: Event, listener: EventListener[None]) -> None: ...

Expand Down Expand Up @@ -198,7 +198,7 @@ def emit(self, *, event: Literal[Event.ABORTING], event_data: EventAbortingData)
@overload
def emit(self, *, event: Literal[Event.EXIT], event_data: EventExitData) -> None: ...
@overload
def emit(self, *, event: Literal[Event.CRAWLER_STATUS], event_data: EventCrawlerStatusData) -> None: ...
def emit(self, *, event: Literal[Event.STATUS_MESSAGE], event_data: EventStatusMessageData) -> None: ...
@overload
def emit(self, *, event: Event, event_data: Any) -> None: ...

Expand Down
25 changes: 18 additions & 7 deletions src/crawlee/events/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from pydantic import BaseModel, ConfigDict, Field
from pydantic.alias_generators import to_camel

from crawlee._types import LogLevel
from crawlee._utils.docs import docs_group
from crawlee._utils.models import timedelta_secs
from crawlee._utils.system import CpuInfo, MemoryUsageInfo
Expand Down Expand Up @@ -34,7 +35,7 @@ class Event(StrEnum):
PAGE_CLOSED = 'pageClosed'

# State events
CRAWLER_STATUS = 'crawlerStatus'
STATUS_MESSAGE = 'statusMessage'


@docs_group('Event data')
Expand Down Expand Up @@ -82,25 +83,35 @@ class EventExitData(BaseModel):


@docs_group('Event data')
class EventCrawlerStatusData(BaseModel):
"""Data for the crawler status event."""
class EventStatusMessageData(BaseModel):
"""Data for the status message event.

model_config = ConfigDict(validate_by_name=True, validate_by_alias=True)
A crawler emits it with each periodic status message and with a terminal summary when its run finishes.
Integrations such as the Apify SDK can forward the message to their status-reporting backend.
"""

message: str
"""A message describing the current status of the crawler."""
model_config = ConfigDict(alias_generator=to_camel, validate_by_name=True, validate_by_alias=True)

crawler_id: str
"""The ID of the crawler that emitted the event."""

message: str
"""A message describing the current status of the crawler."""

is_status_message_terminal: bool = False
"""Whether this is the final status message of the run."""

level: LogLevel
"""The log level the message was logged with."""


EventData = (
EventPersistStateData
| EventSystemInfoData
| EventMigratingData
| EventAbortingData
| EventExitData
| EventCrawlerStatusData
| EventStatusMessageData
)
"""A helper type for all possible event payloads"""

Expand Down
82 changes: 76 additions & 6 deletions tests/unit/crawlers/_basic/test_basic_crawler.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@
from crawlee.events import (
Event,
EventAbortingData,
EventCrawlerStatusData,
EventMigratingData,
EventStatusMessageData,
LocalEventManager,
)
from crawlee.http_clients import HttpClient, HttpResponse, ImpitHttpClient
Expand Down Expand Up @@ -3718,23 +3718,93 @@ async def handler(context: BasicCrawlingContext) -> None:


async def test_status_message_emit() -> None:
"""Periodic status messages are emitted as non-terminal `STATUS_MESSAGE` events with the logged level."""
event_manager = service_locator.get_event_manager()

status_message_listener = Mock()

def listener(event_data: EventCrawlerStatusData) -> None:
# A sync listener runs in a thread, which doesn't keep the order of the events.
async def listener(event_data: EventStatusMessageData) -> None:
status_message_listener(event_data)

event_manager.on(event=Event.CRAWLER_STATUS, listener=listener)
event_manager.on(event=Event.STATUS_MESSAGE, listener=listener)

crawler = BasicCrawler(request_handler=AsyncMock(), id='my-crawler')

await crawler.run(['https://a.placeholder.com'])

event_manager.off(event=Event.CRAWLER_STATUS, listener=listener)
event_manager.off(event=Event.STATUS_MESSAGE, listener=listener)

assert status_message_listener.called
assert status_message_listener.call_args.args[0].crawler_id == 'my-crawler'
first_event = status_message_listener.call_args_list[0].args[0]
assert first_event.crawler_id == 'my-crawler'
assert first_event.message.startswith('Crawled ')
assert first_event.is_status_message_terminal is False
assert first_event.level == 'INFO'


async def test_status_message_terminal_on_finish() -> None:
"""The last `STATUS_MESSAGE` event of a run is a terminal summary of the finished requests."""

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Please add a test for the callback paths: level='INFO' when the callback returns a message, and level=None when it returns None.

✍️ Drafted by Claude Code

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added test_status_message_emit_with_callback: a returned message is emitted with level='INFO'. Since None no longer emits, that case asserts there is no event.

Written with Claude Code (AI).

event_manager = service_locator.get_event_manager()

status_message_listener = Mock()

# A sync listener runs in a thread, which doesn't keep the order of the events.
async def listener(event_data: EventStatusMessageData) -> None:
status_message_listener(event_data)

event_manager.on(event=Event.STATUS_MESSAGE, listener=listener)

async def handler(context: BasicCrawlingContext) -> None:
if 'fail' in context.request.url:
raise RuntimeError('Arbitrary crash for testing purposes')

crawler = BasicCrawler(request_handler=handler, max_request_retries=0, id='my-crawler')

await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com', 'https://fail.placeholder.com'])

event_manager.off(event=Event.STATUS_MESSAGE, listener=listener)

events = [call.args[0] for call in status_message_listener.call_args_list]
terminal_events = [event for event in events if event.is_status_message_terminal]
assert terminal_events == [events[-1]]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: EventManager runs sync listeners through asyncio.to_thread, so the Mock call order is not guaranteed to match the emit order. An async def listener keeps the order fixed. The same applies to call_args_list[0] in test_status_message_emit.

✍️ Drafted by Claude Code

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, both tests now use an async def listener.

Written with Claude Code (AI).

assert events[-1] == EventStatusMessageData(
crawler_id='my-crawler',
message='Finished! Total 3 requests: 2 succeeded, 1 failed.',
is_status_message_terminal=True,
level='INFO',
)


@pytest.mark.parametrize(
('callback_result', 'expected_events'),
[
pytest.param('Custom status.', [('Custom status.', 'INFO')], id='message'),
pytest.param(None, [], id='none'),
],
)
async def test_status_message_emit_with_callback(
callback_result: str | None, expected_events: list[tuple[str, str]]
) -> None:
"""A status update emits the message that the callback returns, and nothing when it returns `None`."""
event_manager = service_locator.get_event_manager()

status_message_listener = Mock()

async def listener(event_data: EventStatusMessageData) -> None:
status_message_listener(event_data)

crawler = BasicCrawler(status_message_callback=AsyncMock(return_value=callback_result))
crawler._last_run = Mock(previous_state=None)
crawler._statistics = Mock(state=StatisticsState())

async with event_manager:
event_manager.on(event=Event.STATUS_MESSAGE, listener=listener)
await crawler._crawler_state_task()
await event_manager.wait_for_all_listeners_to_complete()
event_manager.off(event=Event.STATUS_MESSAGE, listener=listener)

events = [call.args[0] for call in status_message_listener.call_args_list]
assert [(event.message, event.level) for event in events] == expected_events


async def test_status_message_reports_failed_request_count() -> None:
Expand Down
Loading