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
4 changes: 4 additions & 0 deletions docs/06_upgrading/upgrading_to_v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,10 @@ A crawler keeps the lock at least as long as its longest request handler timeout

`RequestQueueMetadata` no longer has the `had_multiple_clients` field, the same as in Crawlee JS. In v1, only `SqlStorageClient` set it to `True`, and the other built-in storage clients always reported `False`. A custom request queue backend can stop setting it. `SqlStorageBackend` no longer creates the `had_multiple_clients` column of the `request_queues` table and the `client_id` column of the `request_queue_metadata_buffer` table, so request queues don't work in a database created by v1. Datasets and key-value stores in such a database keep working.

### Metadata timestamps are approximate

`FileSystemStorageBackend`, `SqlStorageBackend` and `RedisStorageBackend` now write `accessed_at` and `modified_at` to the storage metadata less often, so the stored timestamps can trail the last access or modification by a few seconds. In v1, they were written at once, and `MemoryStorageBackend` still writes them that way. A purge writes them at once on every backend.

## Datasets

`Dataset` now checks each pushed item and passes a JSON copy of it to the storage backend, and reads the items from the backend a page at a time. In v1, each storage backend did both on its own. The rules are the same for every storage backend.
Expand Down
37 changes: 28 additions & 9 deletions src/crawlee/storage_backends/_file_system/_dataset_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from crawlee._utils.log import LoggerOnce
from crawlee._utils.raise_if_too_many_kwargs import raise_if_too_many_kwargs
from crawlee.storage_backends._base import DatasetBackend
from crawlee.storage_backends._utils import slice_dataset_page, warn_unsupported_list_options
from crawlee.storage_backends._utils import TimestampThrottle, slice_dataset_page, warn_unsupported_list_options
from crawlee.storage_backends.models import DatasetItemsListPage, DatasetMetadata

if TYPE_CHECKING:
Expand Down Expand Up @@ -78,6 +78,9 @@ def __init__(
self._logger_once = LoggerOnce(logger)
"""Logs the warning about each set of unsupported list options once for this dataset."""

self._timestamp_throttle = TimestampThrottle()
"""Spares the metadata file writes of timestamps alone that aren't due yet."""

@override
async def get_metadata(self) -> DatasetMetadata:
return self._metadata
Expand Down Expand Up @@ -226,6 +229,8 @@ async def purge(self) -> None:
for file_path in await self._get_sorted_data_files():
await asyncio.to_thread(file_path.unlink, missing_ok=True)

# A purge writes its timestamps at once, also when the dataset was empty already.
self._timestamp_throttle.reset()
await self._update_metadata(
update_accessed_at=True,
update_modified_at=True,
Expand Down Expand Up @@ -338,24 +343,38 @@ async def _update_metadata(

Args:
new_item_count: If provided, update the item count to this value.
update_accessed_at: If True, update the `accessed_at` timestamp to the current time.
update_modified_at: If True, update the `modified_at` timestamp to the current time.
update_accessed_at: If True, update the `accessed_at` timestamp to the current time when it's due.
update_modified_at: If True, update the `modified_at` timestamp to the current time when it's due.
"""
now = datetime.now(UTC)

count_changed = new_item_count not in (None, self._metadata.item_count)

if update_accessed_at or update_modified_at:
update_accessed_at, update_modified_at = self._timestamp_throttle.to_write(
now, modified=update_modified_at, with_other_changes=count_changed
)
if not update_accessed_at:
return

if update_accessed_at:
self._metadata.accessed_at = now
if update_modified_at:
self._metadata.modified_at = now
if new_item_count is not None:
self._metadata.item_count = new_item_count

# Ensure the parent directory for the metadata file exists.
await asyncio.to_thread(self.path_to_metadata.parent.mkdir, parents=True, exist_ok=True)

# Dump the serialized metadata to the file.
data = await json_dumps(self._metadata.model_dump(by_alias=True))
await atomic_write(self.path_to_metadata, data)
try:
# Ensure the parent directory for the metadata file exists.
await asyncio.to_thread(self.path_to_metadata.parent.mkdir, parents=True, exist_ok=True)

# Dump the serialized metadata to the file.
data = await json_dumps(self._metadata.model_dump(by_alias=True))
await atomic_write(self.path_to_metadata, data)
except BaseException:
# The file keeps the timestamps of the last write that went through, so the next write updates it at once.
self._timestamp_throttle.reset()
raise

async def _push_item(self, item: Mapping[str, JsonSerializable], item_id: int) -> None:
"""Push a single item to the dataset.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from crawlee._utils.file import atomic_write, json_dumps, validate_subdirectory
from crawlee._utils.raise_if_too_many_kwargs import raise_if_too_many_kwargs
from crawlee.storage_backends._base import KeyValueStoreBackend
from crawlee.storage_backends._utils import SortedKeys
from crawlee.storage_backends._utils import SortedKeys, TimestampThrottle
from crawlee.storage_backends.models import (
KeyValueStoreKeysListPage,
KeyValueStoreMetadata,
Expand Down Expand Up @@ -86,6 +86,9 @@ def __init__(
self._next_exclusive_start_key: str | None = None
"""The `exclusive_start_key` of the next page after the last listed page."""

self._timestamp_throttle = TimestampThrottle()
"""Spares the metadata file writes of timestamps alone that aren't due yet."""

@override
async def get_metadata(self) -> KeyValueStoreMetadata:
return self._metadata
Expand Down Expand Up @@ -220,6 +223,8 @@ async def drop(self) -> None:
async with self._lock:
self._sorted_keys = None
await asyncio.to_thread(shutil.rmtree, self.path_to_kvs)
# A write after the drop recreates the metadata file, whose timestamps would otherwise not be due yet.
self._timestamp_throttle.reset()

@override
async def purge(self) -> None:
Expand All @@ -232,6 +237,8 @@ async def purge(self) -> None:
continue
await asyncio.to_thread(file_path.unlink, missing_ok=True)

# A purge writes its timestamps at once.
self._timestamp_throttle.reset()
await self._update_metadata(
update_accessed_at=True,
update_modified_at=True,
Expand Down Expand Up @@ -410,22 +417,32 @@ async def _update_metadata(
"""Update the KVS metadata file with current information.

Args:
update_accessed_at: If True, update the `accessed_at` timestamp to the current time.
update_modified_at: If True, update the `modified_at` timestamp to the current time.
update_accessed_at: If True, update the `accessed_at` timestamp to the current time when it's due.
update_modified_at: If True, update the `modified_at` timestamp to the current time when it's due.
"""
now = datetime.now(UTC)

if update_accessed_at or update_modified_at:
update_accessed_at, update_modified_at = self._timestamp_throttle.to_write(now, modified=update_modified_at)
if not update_accessed_at:
return

if update_accessed_at:
self._metadata.accessed_at = now
if update_modified_at:
self._metadata.modified_at = now

# Ensure the parent directory for the metadata file exists.
await asyncio.to_thread(self.path_to_metadata.parent.mkdir, parents=True, exist_ok=True)

# Dump the serialized metadata to the file.
data = await json_dumps(self._metadata.model_dump(by_alias=True))
await atomic_write(self.path_to_metadata, data)
try:
# Ensure the parent directory for the metadata file exists.
await asyncio.to_thread(self.path_to_metadata.parent.mkdir, parents=True, exist_ok=True)

# Dump the serialized metadata to the file.
data = await json_dumps(self._metadata.model_dump(by_alias=True))
await atomic_write(self.path_to_metadata, data)
except BaseException:
# The file keeps the timestamps of the last write that went through, so the next write updates it at once.
self._timestamp_throttle.reset()
raise

def _read_record(self, key: str) -> KeyValueStoreRecord | None:
"""Read the record of the key from its files, or return `None` when it has none or they can't be read."""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from crawlee._utils.raise_if_too_many_kwargs import raise_if_too_many_kwargs
from crawlee._utils.recoverable_state import RecoverableState
from crawlee.storage_backends._base import RequestQueueBackend
from crawlee.storage_backends._utils import TimestampThrottle
from crawlee.storage_backends.models import (
AddRequestsResponse,
ProcessedRequest,
Expand Down Expand Up @@ -119,6 +120,9 @@ def __init__(
self._state = recoverable_state
"""Recoverable state to maintain request ordering, in-progress status, and handled status."""

self._timestamp_throttle = TimestampThrottle()
"""Spares the metadata file writes of timestamps alone that aren't due yet."""

@override
async def get_metadata(self) -> RequestQueueMetadata:
return self._metadata
Expand Down Expand Up @@ -306,6 +310,8 @@ async def purge(self) -> None:
self._request_cache.clear()
self._request_cache_needs_refresh = True

# A purge writes its timestamps at once, also when the queue was empty already.
self._timestamp_throttle.reset()
await self._update_metadata(
update_modified_at=True,
update_accessed_at=True,
Expand Down Expand Up @@ -678,12 +684,27 @@ async def _update_metadata(
new_handled_request_count: If provided, update the handled_request_count to this value.
new_pending_request_count: If provided, update the pending_request_count to this value.
new_total_request_count: If provided, update the total_request_count to this value.
update_accessed_at: If True, update the `accessed_at` timestamp to the current time.
update_modified_at: If True, update the `modified_at` timestamp to the current time.
update_accessed_at: If True, update the `accessed_at` timestamp to the current time when it's due.
update_modified_at: If True, update the `modified_at` timestamp to the current time when it's due.
"""
# Always create a new timestamp to ensure it's truly updated
now = datetime.now(UTC)

# An add of known requests only sets the counts to their current values.
counts_changed = any(
[
new_handled_request_count not in (None, self._metadata.handled_request_count),
new_pending_request_count not in (None, self._metadata.pending_request_count),
new_total_request_count not in (None, self._metadata.total_request_count),
]
)

if update_accessed_at or update_modified_at:
update_accessed_at, update_modified_at = self._timestamp_throttle.to_write(
now, modified=update_modified_at, with_other_changes=counts_changed
)
if not update_accessed_at:
return

# Update timestamps according to parameters
if update_accessed_at:
self._metadata.accessed_at = now
Expand All @@ -701,12 +722,17 @@ async def _update_metadata(
if new_total_request_count is not None:
self._metadata.total_request_count = new_total_request_count

# Ensure the parent directory for the metadata file exists.
await asyncio.to_thread(self.path_to_metadata.parent.mkdir, parents=True, exist_ok=True)

# Dump the serialized metadata to the file.
data = await json_dumps(self._metadata.model_dump(by_alias=True))
await atomic_write(self.path_to_metadata, data)
try:
# Ensure the parent directory for the metadata file exists.
await asyncio.to_thread(self.path_to_metadata.parent.mkdir, parents=True, exist_ok=True)

# Dump the serialized metadata to the file.
data = await json_dumps(self._metadata.model_dump(by_alias=True))
await atomic_write(self.path_to_metadata, data)
except BaseException:
# The file keeps the timestamps of the last write that went through, so the next write updates it at once.
self._timestamp_throttle.reset()
raise

async def _refresh_cache(self) -> None:
"""Refresh the request cache from the filesystem.
Expand Down
35 changes: 26 additions & 9 deletions src/crawlee/storage_backends/_redis/_backend_mixin.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from typing import TYPE_CHECKING, Any, ClassVar, TypedDict, overload

from crawlee._utils.crypto import crypto_random_object_id
from crawlee.storage_backends._utils import TimestampThrottle

from ._utils import await_redis_response, read_lua_script

Expand Down Expand Up @@ -55,6 +56,9 @@ def __init__(self, storage_name: str, storage_id: str, storage_backend: RedisSto

self._scripts_loaded = False

self._timestamp_throttle = TimestampThrottle()
"""Spares the metadata writes of timestamps alone that aren't due yet."""

@property
def redis(self) -> Redis:
"""Return the Redis client instance."""
Expand Down Expand Up @@ -197,13 +201,19 @@ async def _ensure_scripts_loaded(self) -> None:
@asynccontextmanager
async def _get_pipeline(self, *, with_execute: bool = True) -> AsyncGenerator[Pipeline]:
"""Create a new Redis pipeline."""
async with self.redis.pipeline() as pipe:
try:
pipe.multi()
yield pipe
finally:
if with_execute:
await pipe.execute()
try:
async with self.redis.pipeline() as pipe:
try:
pipe.multi()
yield pipe
finally:
if with_execute:
await pipe.execute()
except BaseException:
# The timestamps of a failed or cancelled transaction never reach Redis, so the next write, such as a retry,
# writes them at once.
self._timestamp_throttle.reset()
raise

async def _create_storage(self, pipeline: Pipeline) -> None:
"""Create the actual storage structure in Redis."""
Expand Down Expand Up @@ -250,6 +260,8 @@ async def _purge(self, extra_keys: list[str], metadata_kwargs: MetadataUpdatePar
async with self._get_pipeline() as pipe:
for key in extra_keys:
await pipe.delete(key)
# A purge writes its timestamps at once.
self._timestamp_throttle.reset()
await self._update_metadata(pipe, **metadata_kwargs)
await self._create_storage(pipe)

Expand Down Expand Up @@ -294,12 +306,17 @@ async def _update_metadata(

Args:
pipeline: The Redis pipeline to use for the update.
update_accessed_at: Whether to update accessed_at timestamp.
update_modified_at: Whether to update modified_at timestamp.
update_accessed_at: Whether to update accessed_at timestamp when it's due.
update_modified_at: Whether to update modified_at timestamp when it's due.
**kwargs: Additional arguments for _specific_update_metadata.
"""
now = datetime.now(UTC)

if update_accessed_at or update_modified_at:
update_accessed_at, update_modified_at = self._timestamp_throttle.to_write(
now, modified=update_modified_at, with_other_changes=bool(kwargs)
)

if update_accessed_at:
await await_redis_response(
pipeline.json().set(self.metadata_key, '$.accessed_at', now.isoformat(), nx=False, xx=True)
Expand Down
Loading
Loading