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
21 changes: 21 additions & 0 deletions docs/06_upgrading/upgrading_to_v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,25 @@ for urls in batches:

`Configuration.purge_on_start` isn't affected. Unnamed storages are still purged once per process, when they're first opened. With `SqlStorageBackend` and `RedisStorageBackend`, each instance now opens its own storages, so it purges them once per instance.

## A timeout or cancellation around `run()` raises

In v1, `crawler.run()` caught the cancellation of the task that awaited it and returned the final statistics. A timeout around `run()`, such as `asyncio.wait_for()` or `asyncio.timeout()`, that expired during the crawl didn't raise `TimeoutError`, and a task running `run()` returned the statistics even after `task.cancel()`. In v2, `run()` lets the requests in progress finish and then raises `CancelledError`, which a timeout turns into `TimeoutError`. A repeated cancellation, which anyio cancel scopes keep sending, cancels the requests in progress. A cancelled run doesn't log the final statistics or the error analysis, the same as a failed run. Ctrl+C still ends the crawl gracefully and returns the statistics.

To limit how long a crawl runs and still get the statistics, stop the crawler when the time is up. The requests in progress still finish, so the crawl can end after the limit:

```python
# v1
stats = await asyncio.wait_for(crawler.run(urls), timeout=600)

# v2
stop_handle = asyncio.get_running_loop().call_later(600, crawler.stop)
Comment thread
Mantisus marked this conversation as resolved.
Resolved
try:
stats = await crawler.run(urls)
finally:
# A stop called after the run ends would stop the next run.
stop_handle.cancel()
```

## `RequestQueue.purge` raises when the storage backend can't purge

In v1, `RequestQueue.purge()` worked around a storage backend that didn't support purging. It dropped an unnamed queue and opened the default queue in its place, and it skipped a named queue with a warning. In v2, it raises the backend's `NotImplementedError`, the same as Crawlee JS. The Apify platform's storage backend doesn't support purging, so on the platform, call `drop()` or open a new queue instead.
Expand Down Expand Up @@ -688,6 +707,8 @@ Messages that mentioned a storage client name the storage backend instead. The D

`RequestQueue.purge()` no longer logs the `Storage client "..." does not support purging the request queue.` warnings. It raises `NotImplementedError` instead. For details, see [`RequestQueue.purge` raises when the storage backend can't purge](#requestqueuepurge-raises-when-the-storage-backend-cant-purge).

A cancelled `run()` doesn't log `Final request statistics` or `Error analysis`. For details, see [A timeout or cancellation around `run()` raises](#a-timeout-or-cancellation-around-run-raises).

The ERROR message the crawler logs before raising `PersistentRateLimitError` now reads "Giving up the crawl because the request manager can't make progress." instead of "Giving up the crawl because a domain keeps rate-limiting every request."

The two DEBUG messages that `RequestQueue.is_finished` logged, "Background add requests tasks are still in progress." and "The request queue is finished.", are removed together with the method.
Expand Down
21 changes: 19 additions & 2 deletions src/crawlee/crawlers/_basic/_basic_crawler.py
Original file line number Diff line number Diff line change
Expand Up @@ -839,6 +839,10 @@ async def run(self, requests: Sequence[str | Request] | None = None) -> FinalSta
run handled, failed ones included, aren't processed again. To crawl them again, purge the request manager, or
create a new crawler with a freshly opened request queue.

Cancelling the task that awaits `run()`, such as with a timeout around it, raises `CancelledError` once the
requests in progress finish. A repeated cancellation, which anyio cancel scopes keep sending, cancels them.
Ctrl+C also lets them finish, and then returns the final statistics.

Args:
requests: The requests to be enqueued before the crawler starts.

Expand Down Expand Up @@ -917,14 +921,27 @@ def sigint_handler() -> None:
)
remove_sigint_handler = partial(signal.signal, signal.SIGINT, previous_sigint_handler)

current_task = asyncio.current_task()
cancelling_before = current_task.cancelling() if current_task is not None else 0
cancellation: CancelledError | None = None

try:
await run_task
except CancelledError:
pass
except CancelledError as exc:
cancellation = exc
finally:
if remove_sigint_handler is not None:
remove_sigint_handler()

# SIGINT cancels only `run_task`, and the crawl then ends gracefully. A cancellation of the task that awaits
# `run()`, such as a timeout around it, propagates, also when the crawl swallowed it. An earlier one that
# the caller caught doesn't count. The caught exception is raised again, since anyio cancel scopes
# recognize their cancellation by its message. A cancelled run counts as finished, so the next one starts
# afresh.
if current_task is not None and current_task.cancelling() > cancelling_before:
self._has_finished_before = True
raise cancellation or CancelledError()

if self._statistics.error_tracker.total > 0:
self._logger.info(
'Error analysis: total_errors=%s unique_errors=%s',
Expand Down
156 changes: 132 additions & 24 deletions tests/unit/crawlers/_basic/test_basic_crawler.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from asyncio import Future
from collections import Counter
from concurrent.futures import ProcessPoolExecutor
from contextlib import suppress
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from itertools import chain, product, repeat
Expand Down Expand Up @@ -2191,10 +2192,7 @@ async def handler(context: BasicCrawlingContext) -> None:
await asyncio.wait_for(pause_task, timeout=10)

crawler.stop()
# `run` swallows a cancellation, so `wait_for` would return after its timeout instead of raising.
await asyncio.wait([run_task], timeout=10)
assert run_task.done()
await run_task
await asyncio.wait_for(run_task, timeout=10)

assert visited == urls[:1]

Expand All @@ -2221,10 +2219,7 @@ async def handler(context: BasicCrawlingContext) -> None:

release.set()
await asyncio.wait_for(pause_task, timeout=10)
# `run` swallows a cancellation, so `wait_for` would return after its timeout instead of raising.
await asyncio.wait([run_task], timeout=10)
assert run_task.done()
await run_task
await asyncio.wait_for(run_task, timeout=10)

assert visited == urls[:1]

Expand All @@ -2249,10 +2244,7 @@ async def handler(context: BasicCrawlingContext) -> None:
await crawler.pause(timeout=timedelta(milliseconds=50))

release.set()
# `run` swallows a cancellation, so `wait_for` would return after its timeout instead of raising.
await asyncio.wait([run_task], timeout=10)
assert run_task.done()
await run_task
await asyncio.wait_for(run_task, timeout=10)

assert visited == urls[:1]

Expand All @@ -2279,10 +2271,7 @@ async def handler(context: BasicCrawlingContext) -> None:

release.set()
await event_manager.wait_for_all_listeners_to_complete()
# `run` swallows a cancellation, so `wait_for` would return after its timeout instead of raising.
await asyncio.wait([run_task], timeout=10)
assert run_task.done()
await run_task
await asyncio.wait_for(run_task, timeout=10)

assert visited == urls[:1]

Expand Down Expand Up @@ -2311,10 +2300,7 @@ async def handler(context: BasicCrawlingContext) -> None:
await crawler.pause(timeout=timedelta(milliseconds=50))

release.set()
# `run` swallows a cancellation, so `wait_for` would return after its timeout instead of raising.
await asyncio.wait([run_task], timeout=10)
assert run_task.done()
await run_task
await asyncio.wait_for(run_task, timeout=10)

assert visited == urls[:1]

Expand Down Expand Up @@ -2355,10 +2341,7 @@ async def handler(context: BasicCrawlingContext) -> None:

release.set()
await asyncio.wait_for(pause_task, timeout=10)
# `run` swallows a cancellation, so `wait_for` would return after its timeout instead of raising.
await asyncio.wait([run_task], timeout=10)
assert run_task.done()
await run_task
await asyncio.wait_for(run_task, timeout=10)

assert len(visited) == 2

Expand Down Expand Up @@ -4459,6 +4442,131 @@ async def handler(context: BasicCrawlingContext) -> None:
assert signal.getsignal(signal.SIGINT) is sigint_handler_before_run


async def test_run_raises_when_cancelled(caplog: pytest.LogCaptureFixture) -> None:
"""Cancelling the task that awaits `run()` raises `CancelledError` once the requests in progress finish."""
caplog.set_level(logging.INFO, logger='crawlee')
crawler = BasicCrawler(configure_logging=False)
handler_started = asyncio.Event()
release_handler = asyncio.Event()
handler_finished = Mock()

@crawler.router.default_handler
async def handler(_context: BasicCrawlingContext) -> None:
handler_started.set()
await release_handler.wait()
handler_finished()

run_task = asyncio.create_task(crawler.run(['https://a.placeholder.com']))
await handler_started.wait()
# The message shows that the caller's own cancellation propagates, not a new one.
run_task.cancel('caller cancelled')
# The crawl lets the running request finish before it ends.
release_handler.set()

with pytest.raises(asyncio.CancelledError, match='caller cancelled'):
await run_task

handler_finished.assert_called_once()
assert 'Final request statistics' not in caplog.text


async def test_run_raises_timeout_error_on_timeout() -> None:
"""A timeout around `run()` raises `TimeoutError` once the requests in progress finish."""
crawler = BasicCrawler(configure_logging=False)
handler_finished = Mock()

@crawler.router.default_handler
async def handler(_context: BasicCrawlingContext) -> None:
# Expire the timeout while the request is in progress, and finish only once it has cancelled the run.
run_timeout.reschedule(asyncio.get_running_loop().time())
await poll_until_condition(run_timeout.expired)
handler_finished()

with pytest.raises(TimeoutError):
async with asyncio.timeout(None) as run_timeout:
await crawler.run(['https://a.placeholder.com'])

handler_finished.assert_called_once()


async def test_run_raises_when_crawl_swallows_cancellation() -> None:
"""Cancelling the task that awaits `run()` raises `CancelledError` even when the crawl swallows the cancellation."""
crawler = BasicCrawler(configure_logging=False)
handler_started = asyncio.Event()
release_handler = asyncio.Event()
run_crawler = crawler._run_crawler

@crawler.router.default_handler
async def handler(_context: BasicCrawlingContext) -> None:
handler_started.set()
await release_handler.wait()

async def swallow_cancellation() -> None:
with suppress(asyncio.CancelledError):
await run_crawler()

with patch.object(crawler, '_run_crawler', swallow_cancellation):
run_task = asyncio.create_task(crawler.run(['https://a.placeholder.com']))
await handler_started.wait()
run_task.cancel()
release_handler.set()

with pytest.raises(asyncio.CancelledError):
await run_task


async def test_run_after_cancelled_run_resets_statistics() -> None:
"""A `run()` after a cancelled one starts with fresh statistics."""
crawler = BasicCrawler(configure_logging=False)
handler_started = asyncio.Event()
release_handler = asyncio.Event()

@crawler.router.default_handler
async def handler(_context: BasicCrawlingContext) -> None:
handler_started.set()
await release_handler.wait()

run_task = asyncio.create_task(crawler.run(['https://a.placeholder.com']))
await handler_started.wait()
run_task.cancel()
release_handler.set()

with pytest.raises(asyncio.CancelledError):
await run_task

stats = await crawler.run(['https://b.placeholder.com'])

assert stats.requests_finished == 1


async def test_sigint_after_caught_cancellation() -> None:
"""SIGINT ends the crawl gracefully even when the task that awaits `run()` caught an earlier cancellation."""
crawler = BasicCrawler(
configure_logging=False,
concurrency_settings=ConcurrencySettings(desired_concurrency=1, max_concurrency=1),
)

@crawler.router.default_handler
async def handler(_context: BasicCrawlingContext) -> None:
signal.raise_signal(signal.SIGINT)
# The pause lets the running request finish, so keep it running until the pause takes effect.
await asyncio.sleep(0.5)

async def run_after_caught_cancellation() -> FinalStatistics:
with suppress(asyncio.CancelledError):
await asyncio.Event().wait()

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

run_task = asyncio.create_task(run_after_caught_cancellation())
await asyncio.sleep(0)
run_task.cancel()

stats = await run_task

assert stats.requests_finished == 1


async def test_concurrency_system_excludes_settings() -> None:
"""The settings configure the default concurrency system, so a supplied one leaves them nowhere to go."""
with pytest.raises(ValueError, match='cannot be combined'):
Expand Down
Loading