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
8 changes: 3 additions & 5 deletions src/crawlee/storage_backends/_redis/_request_queue_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -412,8 +412,9 @@ async def mark_request_as_handled(self, request: Request) -> ProcessedRequest |
raise RuntimeError('Scripts not loaded. Call _ensure_scripts_loaded() before using the client.')

now = datetime.now(UTC)
handled_at = request.handled_at or now
request_data = request.model_copy(update={'handled_at': handled_at}).model_dump_json(by_alias=True)
if request.handled_at is None:
request.handled_at = now
request_data = request.model_dump_json(by_alias=True)

if self._dedup_strategy == 'bloom':
dedup_keys = [self._handled_filter_key]
Expand All @@ -431,9 +432,6 @@ async def mark_request_as_handled(self, request: Request) -> ProcessedRequest |
logger.warning('Marking request %s as handled that is not in progress.', request.unique_key)
return None

# Set only once the script has marked the request, so a request that isn't in progress doesn't look handled.
request.handled_at = handled_at

return ProcessedRequest(
unique_key=request.unique_key,
was_already_present=True,
Expand Down
12 changes: 10 additions & 2 deletions src/crawlee/storages/_request_queue.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

import asyncio
from datetime import timedelta
from datetime import UTC, datetime, timedelta
from logging import getLogger
from typing import TYPE_CHECKING, TypeVar

Expand Down Expand Up @@ -274,13 +274,21 @@ async def mark_request_as_handled(self, request: Request) -> ProcessedRequest |
Once marked as handled, the request will be removed from the queue and will
not be returned in subsequent calls to `fetch_next_request` method.

The given request gets its `handled_at` only once the backend has marked it, so a call that fails or is
cancelled midway doesn't leave it looking handled.

Args:
request: The request to mark as handled.

Returns:
Information about the queue operation.
"""
return await self._backend.mark_request_as_handled(request)
handled_at = request.handled_at or datetime.now(UTC)
request_copy = request.model_copy(update={'handled_at': handled_at})
processed_request = await self._backend.mark_request_as_handled(request_copy)
if processed_request is not None:
request.handled_at = handled_at
return processed_request

async def reclaim_request(
self,
Expand Down
20 changes: 0 additions & 20 deletions tests/unit/storage_backends/_redis/test_redis_rq_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -359,26 +359,6 @@ async def test_mark_request_as_handled_concurrent_no_double_decrement(
assert metadata.handled_request_count == 1


async def test_mark_sets_handled_at_on_success(
rq_backend: RedisRequestQueueBackend,
) -> None:
"""Test that `mark_request_as_handled` sets `handled_at` only when it marks the request, and stores it."""
request = Request.from_url('https://example.com/handled-at')
await rq_backend.add_batch_of_requests([request])

assert await rq_backend.mark_request_as_handled(request) is None
assert request.handled_at is None

fetched = await rq_backend.fetch_next_request()
assert fetched is not None
assert await rq_backend.mark_request_as_handled(fetched) is not None
assert fetched.handled_at is not None

stored = await rq_backend.get_request(fetched.unique_key)
assert stored is not None
assert stored.handled_at == fetched.handled_at


async def test_failed_mark_keeps_in_progress(
rq_backend: RedisRequestQueueBackend,
) -> None:
Expand Down
55 changes: 42 additions & 13 deletions tests/unit/storages/test_request_queue.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

import asyncio
from datetime import timedelta
from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING
from unittest.mock import AsyncMock, call, create_autospec, patch

Expand Down Expand Up @@ -508,17 +508,6 @@ async def test_get_request_by_id(rq: RequestQueue) -> None:
assert retrieved_request.url == 'https://example.com'


async def test_handled_request_records_persistence(rq: RequestQueue) -> None:
request = Request.from_url('https://example.com/1')
await rq.add_request(request)
fetched_request = await rq.fetch_next_request()
assert isinstance(fetched_request, Request)
await rq.mark_request_as_handled(fetched_request)
fetched_request = await rq.get_request(request.unique_key)
assert isinstance(fetched_request, Request)
assert fetched_request.unique_key == request.unique_key


async def test_get_non_existent_request(rq: RequestQueue) -> None:
"""Test retrieving a request that doesn't exist."""
non_existent_request = await rq.get_request('non-existent-id')
Expand Down Expand Up @@ -665,14 +654,29 @@ async def test_get_pending_count(rq: RequestQueue) -> None:
assert await rq.get_pending_count() == 2


async def test_mark_sets_handled_at_on_success(rq: RequestQueue) -> None:
"""Test that `mark_request_as_handled` sets `handled_at` on the given request and stores it."""
await rq.add_request('https://example.com/handled-at')
request = await rq.fetch_next_request()
assert request is not None

assert await rq.mark_request_as_handled(request) is not None
assert request.handled_at is not None

stored = await rq.get_request(request.unique_key)
assert stored is not None
assert stored.handled_at == request.handled_at


async def test_mark_non_existent_request_as_handled(rq: RequestQueue) -> None:
"""Test marking a non-existent request as handled."""
"""Test that marking a non-existent request as handled returns `None` and leaves the request unhandled."""
# Create a request that hasn't been added to the queue
request = Request.from_url(url='https://example.com', id='non-existent-id')

# Attempt to mark it as handled
result = await rq.mark_request_as_handled(request)
assert result is None
assert request.handled_at is None


async def test_reclaim_non_existent_request(rq: RequestQueue) -> None:
Expand Down Expand Up @@ -1639,3 +1643,28 @@ async def test_extend_forwards_to_backend() -> None:

assert await rq.extend_request_processing_time(request, timedelta(minutes=1)) is True
backend.extend_request_processing_time.assert_awaited_once_with(request, timedelta(minutes=1))


@pytest.mark.parametrize(
'error',
[
pytest.param(RuntimeError('Write failed'), id='error'),
pytest.param(asyncio.CancelledError(), id='cancelled-error'),
],
)
async def test_failed_mark_leaves_request_unhandled(error: BaseException) -> None:
"""Test that a mark that fails after the backend set `handled_at` leaves the given request unhandled."""
backend = create_autospec(RequestQueueBackend, instance=True, spec_set=True)

def set_handled_at_and_fail(marked_request: Request) -> None:
marked_request.handled_at = datetime.now(UTC)
raise error

backend.mark_request_as_handled.side_effect = set_handled_at_and_fail
rq = RequestQueue(backend, id='test', name=None)
request = Request.from_url('https://example.com/1')

with pytest.raises(type(error)):
await rq.mark_request_as_handled(request)

assert request.handled_at is None
Loading