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
13 changes: 4 additions & 9 deletions src/crawlee/request_loaders/_request_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,21 +265,16 @@ async def get_state(self) -> RequestListState:
return state.model_copy(deep=True)

async def persist_state(self) -> None:
"""Persist the crawling position to the key-value store, logging a failed write.
"""Persist the crawling position to the key-value store, raising if the write fails.

Raises:
RuntimeError: If the request list has no `persist_state_key`.
Does nothing without a `persist_state_key`.
"""
if not self._persist_state_key:
raise RuntimeError('Cannot persist state. `persist_state_key` is not set.')
return

# Loads the persisted record first, so that a call before the first use writes the restored position.
await self._get_state()

try:
await self._state.persist_state()
except Exception:
logger.exception('Attempted to persist state, but failed.')
await self._state.persist_state()

async def close(self) -> None:
"""Stop persisting the crawling position on PERSIST_STATE events and persist it one last time.
Expand Down
24 changes: 12 additions & 12 deletions tests/unit/request_loaders/test_request_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -457,12 +457,16 @@ async def test_persisted_state_wins_over_state_option() -> None:
assert await drain(restored_list) == ['https://b.placeholder.com', 'https://c.placeholder.com']


async def test_persist_state_without_key_raises() -> None:
"""`persist_state` raises when the request list has no `persist_state_key`."""
request_list = RequestList(URLS)
async def test_persist_state_without_key_writes_nothing(monkeypatch: pytest.MonkeyPatch) -> None:
"""`persist_state` without a `persist_state_key` writes nothing, not even the `persist_requests_key` record."""
kvs = await KeyValueStore.open()
set_value = AsyncMock()
monkeypatch.setattr(kvs, 'set_value', set_value)
request_list = RequestList(URLS, persist_requests_key='requests')

with pytest.raises(RuntimeError, match=r'`persist_state_key` is not set'):
await request_list.persist_state()
await request_list.persist_state()

set_value.assert_not_called()


async def test_persist_state_before_first_use() -> None:
Expand All @@ -476,20 +480,16 @@ async def test_persist_state_before_first_use() -> None:
assert (await kvs.get_value('state'))['nextIndex'] == 1


async def test_failed_persist_state_is_logged(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
"""A failed write in `persist_state` is logged instead of raised."""
async def test_failed_persist_state_raises(monkeypatch: pytest.MonkeyPatch) -> None:
"""A failed write in `persist_state` raises."""
request_list = RequestList(URLS, persist_state_key='state')
await request_list.fetch_next_request()
kvs = await KeyValueStore.open()
monkeypatch.setattr(kvs, 'set_value', AsyncMock(side_effect=RuntimeError('store is on fire')))

with caplog.at_level(logging.ERROR):
with pytest.raises(RuntimeError, match='store is on fire'):
await request_list.persist_state()

assert any(record.message == 'Attempted to persist state, but failed.' for record in caplog.records)


async def test_close_persists_state_and_stops_listening() -> None:
"""Leaving the context persists the state once more, and later PERSIST_STATE events no longer persist it."""
Expand Down
Loading