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
2 changes: 0 additions & 2 deletions docs/03_concepts/12_storage_backends.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,6 @@ class request_queues {
+ accessed_at
+ created_at
+ modified_at
+ had_multiple_clients
+ handled_request_count
+ pending_request_count
+ total_request_count
Expand Down Expand Up @@ -327,7 +326,6 @@ class request_queue_metadata_buffer {
+ id (PK)
+ accessed_at
+ modified_at
+ client_id
+ delta_handled_count
+ delta_pending_count
+ delta_total_count
Expand Down
6 changes: 5 additions & 1 deletion docs/06_upgrading/upgrading_to_v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ In the error handler, `context.request.retry_count` is the number of retries bef

The storage backends now write their JSON data with camelCase keys, the same as Crawlee JS. The change covers the metadata, request and record metadata files of `FileSystemStorageBackend`, the request and record metadata JSON stored by `RedisStorageBackend`, and the request JSON stored by `SqlStorageBackend`. For example, `item_count` in a dataset's `__metadata__.json` becomes `itemCount`. The storage metadata documents and request locks of `RedisStorageBackend` keep their snake_case keys. So does the `CRAWLEE_REQUEST_QUEUE_STATE_<id>` record that `FileSystemStorageBackend` keeps for each request queue in the default key-value store.

Data written by v1 still loads, so an existing storage directory, Redis instance or database keeps working. Any tooling that reads these files directly needs to handle both snake_case and camelCase keys, since v2 rewrites data written by v1 only when it changes it.
Data written by v1 still loads, so an existing storage directory or Redis instance keeps working. Any tooling that reads these files directly needs to handle both snake_case and camelCase keys, since v2 rewrites data written by v1 only when it changes it.
Comment thread
Mantisus marked this conversation as resolved.
Resolved

### Each SQL and Redis backend opens its own storages

Expand Down Expand Up @@ -311,6 +311,10 @@ A crawler keeps the lock at least as long as its longest request handler timeout

`RequestQueueBackend.is_finished` is now an abstract method. In v1, it fell back to `is_empty`, which ignores requests still being processed and could report the queue as finished too early. A subclass that doesn't implement it raises `TypeError` on instantiation. If you have a custom request queue backend, implement `is_finished` so that it returns `True` only when the queue is empty and no requests are in progress. The built-in backends already implement it.

### `RequestQueueMetadata.had_multiple_clients` is removed

`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.

## 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
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,6 @@ async def open(
created_at=now,
accessed_at=now,
modified_at=now,
had_multiple_clients=False,
handled_request_count=0,
pending_request_count=0,
total_request_count=0,
Expand Down Expand Up @@ -670,7 +669,6 @@ async def _update_metadata(
new_handled_request_count: int | None = None,
new_pending_request_count: int | None = None,
new_total_request_count: int | None = None,
update_had_multiple_clients: bool = False,
update_accessed_at: bool = False,
update_modified_at: bool = False,
) -> None:
Expand All @@ -680,7 +678,6 @@ 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_had_multiple_clients: If True, set had_multiple_clients to True.
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.
"""
Expand All @@ -704,9 +701,6 @@ async def _update_metadata(
if new_total_request_count is not None:
self._metadata.total_request_count = new_total_request_count

if update_had_multiple_clients:
self._metadata.had_multiple_clients = True

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,6 @@ async def open(
created_at=now,
accessed_at=now,
modified_at=now,
had_multiple_clients=False,
handled_request_count=0,
pending_request_count=0,
total_request_count=0,
Expand Down
11 changes: 0 additions & 11 deletions src/crawlee/storage_backends/_redis/_request_queue_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ class _QueueMetadataUpdateParams(MetadataUpdateParams):
delta_pending_request_count: NotRequired[int]
delta_total_request_count: NotRequired[int]
recalculate: NotRequired[bool]
update_had_multiple_clients: NotRequired[bool]


class RedisRequestQueueBackend(RequestQueueBackend, RedisBackendMixin):
Expand Down Expand Up @@ -213,7 +212,6 @@ async def open(
storage_backend=storage_backend,
metadata_model=RequestQueueMetadata,
extra_metadata_fields={
'had_multiple_clients': False,
'handled_request_count': 0,
'pending_request_count': 0,
'total_request_count': 0,
Expand Down Expand Up @@ -583,7 +581,6 @@ async def _specific_update_metadata(
new_pending_request_count: int | None = None,
delta_total_request_count: int | None = None,
new_total_request_count: int | None = None,
update_had_multiple_clients: bool = False,
**_kwargs: Any,
) -> None:
"""Update the dataset metadata with current information.
Expand All @@ -596,7 +593,6 @@ async def _specific_update_metadata(
delta_handled_request_count: If provided, add this value to the handled_request_count.
delta_pending_request_count: If provided, add this value to the pending_request_count.
delta_total_request_count: If provided, add this value to the total_request_count.
update_had_multiple_clients: If True, set had_multiple_clients to True.
"""
if new_pending_request_count is not None:
await await_redis_response(
Expand Down Expand Up @@ -630,10 +626,3 @@ async def _specific_update_metadata(
await await_redis_response(
pipeline.json().numincrby(self.metadata_key, '$.total_request_count', delta_total_request_count)
)

if update_had_multiple_clients:
await await_redis_response(
pipeline.json().set(
self.metadata_key, '$.had_multiple_clients', update_had_multiple_clients, nx=False, xx=True
)
)
8 changes: 0 additions & 8 deletions src/crawlee/storage_backends/_sql/_db_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,6 @@ class RequestQueueMetadataDb(StorageMetadataDb, Base):
request_queue_id: Mapped[str] = mapped_column(String(20), nullable=False, primary_key=True)
"""Unique identifier for the request queue."""

had_multiple_clients: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
"""Flag indicating if multiple clients have accessed this queue."""

handled_request_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
"""Number of requests processed."""

Expand Down Expand Up @@ -325,15 +322,10 @@ class RequestQueueMetadataBufferDb(MetadataBufferDb, Base):

__tablename__ = 'request_queue_metadata_buffer'

__table_args__ = (Index('idx_rq_client', 'request_queue_id', 'client_id'),)

# Don't use foreign key constraint to avoid DB locks on high concurrency.
request_queue_id: Mapped[str] = mapped_column(String(20), nullable=False, index=True)
"""ID of the request queue being updated."""

client_id: Mapped[str] = mapped_column(String(32), nullable=False)
"""Identifier of the client making this update."""

# Counter deltas - use SUM when aggregating.
delta_handled_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
"""Delta for handled_request_count."""
Expand Down
22 changes: 2 additions & 20 deletions src/crawlee/storage_backends/_sql/_request_queue_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ class _QueueMetadataUpdateParams(MetadataUpdateParams):
delta_pending_request_count: NotRequired[int]
delta_total_request_count: NotRequired[int]
recalculate: NotRequired[bool]
update_had_multiple_clients: NotRequired[bool]


class SqlRequestQueueBackend(
Expand Down Expand Up @@ -119,9 +118,6 @@ def __init__(
self.client_key = crypto_random_object_id(length=32)[:32]
"""Unique identifier for this client instance."""

self._had_multiple_clients = False
"""Indicates whether the queue has been accessed by multiple clients."""

self._block_request_time = self._DEFAULT_BLOCK_REQUEST_TIME
"""How long a request is considered blocked in the database after being fetched for processing."""

Expand Down Expand Up @@ -159,7 +155,6 @@ async def open(
storage_backend=storage_backend,
metadata_model=RequestQueueMetadata,
extra_metadata_fields={
'had_multiple_clients': False,
'handled_request_count': 0,
'pending_request_count': 0,
'total_request_count': 0,
Expand All @@ -170,9 +165,7 @@ async def open(
@override
async def get_metadata(self) -> RequestQueueMetadata:
# The database is a single place of truth
metadata = await self._get_metadata(RequestQueueMetadata)
self._had_multiple_clients = metadata.had_multiple_clients
return metadata
return await self._get_metadata(RequestQueueMetadata)

@retry_on_error(SQLAlchemyError)
@override
Expand Down Expand Up @@ -774,7 +767,6 @@ def _specific_update_metadata(
delta_total_request_count: int | None = None,
*,
recalculate: bool = False,
update_had_multiple_clients: bool = False,
**_kwargs: dict[str, Any],
) -> dict[str, Any]:
"""Update the request queue metadata in the database.
Expand All @@ -788,13 +780,9 @@ def _specific_update_metadata(
delta_pending_request_count: If provided, add this value to the pending_request_count.
delta_total_request_count: If provided, add this value to the total_request_count.
recalculate: If True, recalculate the pending_request_count, and total_request_count on request table.
update_had_multiple_clients: If True, set had_multiple_clients to True.
"""
values_to_set: dict[str, Any] = {}

if update_had_multiple_clients:
values_to_set['had_multiple_clients'] = True

if recalculate:
stmt = (
update(self._METADATA_TABLE)
Expand Down Expand Up @@ -880,9 +868,7 @@ def _prepare_buffer_data(
delta_total_request_count: If provided, add this value to the total_request_count.
recalculate: If True, recalculate the pending_request_count, and total_request_count on request table.
"""
buffer_data: dict[str, Any] = {
'client_id': self.client_key,
}
buffer_data: dict[str, Any] = {}

if delta_handled_request_count:
buffer_data['delta_handled_count'] = delta_handled_request_count
Expand All @@ -908,9 +894,6 @@ async def _apply_buffer_updates(self, session: AsyncSession, max_buffer_id: int)
func.sum(self._BUFFER_TABLE.delta_total_count).label('delta_total_count'),
]

if not self._had_multiple_clients:
aggregations.append(func.count(func.distinct(self._BUFFER_TABLE.client_id)).label('unique_clients_count'))

if self._storage_backend.get_dialect_name() == 'postgresql':
aggregations.append(func.bool_or(self._BUFFER_TABLE.need_recalc).label('need_recalc'))
else:
Expand All @@ -931,7 +914,6 @@ async def _apply_buffer_updates(self, session: AsyncSession, max_buffer_id: int)
**_QueueMetadataUpdateParams(
accessed_at=row.max_accessed_at,
modified_at=row.max_modified_at,
update_had_multiple_clients=not self._had_multiple_clients and row.unique_clients_count > 1,
delta_handled_request_count=row.delta_handled_count,
delta_pending_request_count=row.delta_pending_count,
delta_total_request_count=row.delta_total_count,
Expand Down
3 changes: 0 additions & 3 deletions src/crawlee/storage_backends/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,6 @@ class RequestQueueMetadata(StorageMetadata):
alias_generator=to_camel, validate_by_name=True, validate_by_alias=True, from_attributes=True
)

had_multiple_clients: bool
"""Indicates whether the queue has been accessed by multiple clients (consumers)."""

handled_request_count: int
Comment thread
vdusek marked this conversation as resolved.
Resolved
"""The number of requests that have been handled from the queue."""

Expand Down
Loading