Skip to content

Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.

refactor!: Align `RequestQueueClient` interface with its Python counterpart (#3729)

Jan Buchar32c0e74a6948
diff --git a/REBASE-DEFERRED.md b/REBASE-DEFERRED.md
index 0e0fbf4a4..e9016a01f 100644
--- a/REBASE-DEFERRED.md
+++ b/REBASE-DEFERRED.md
@@ -293,3 +293,65 @@ from both `browser-crawler.ts` and the pool. Removed the now-dead
`PAGE_CLOSE_TIMEOUT_MILLIS` constant from `browser-crawler.ts` (no other use).
Worth double-checking in review that no other caller of `closePage()` relies
on it settling faster than 5s.
+
+**Found and fixed a real regression in `packages/basic-crawler/src/internals/basic-crawler.ts`
+(surfaced while resolving commit `f1f095913`)**: master (`1430062c2`, via commit `b2296cea7
+fix: Correctly track the number of requests handled by a crawler (#3410)`) turned
+`handledRequestsCount` into a getter derived from `this.stats`, with a setter that
+*throws* if assigned to (property is meant to be read-only now). v4 has the same fix
+under a different hash (`93dda9656`), which is why it's absent from this rebase's
+todo — my rebase base already includes the master version. However, several later
+v4 commits I already applied earlier in this rebase (including `0c1fbcfe7`, the
+IRequestManager/IRequestLoader transition) reintroduced code written against the
+*old* pre-fix API: a `this.handledRequestsCount = 0;` reset in `_rotateRequestQueue`
+(or equivalent), a `_loadHandledRequestCount()` method that assigned to the setter,
+and a call to it from `_init()`. All three would throw at runtime the first time
+they ran (the setter always throws). Removed all three, and removed the
+`this.handledRequestsCount++` this conflict itself reintroduced in the failed-request
+path, matching master's already-established fix. Worth double-checking, once the
+rebase is fully done, that no other spot re-assigns `handledRequestsCount`.
+
+**Commit `f1f095913` (Align RequestQueueClient interface with Python counterpart)
+— ported master-only `addRequestsBatched` features into the new unified
+`request_queue.ts`**: this v4 commit deletes `request_provider.ts` and
+`request_queue_v2.ts` wholesale, replacing them with a single new
+`request_queue.ts` (already present, unconflicted, since it's a new file from
+v4's side). The new file's `addRequestsBatched()` was a rewrite from an older
+point in v4 history and was missing two features that only exist on master
+(`1430062c2`) and are still actively used by already-applied v4 commits later
+in this rebase (`enqueue_links.ts` reads `result.requestsOverLimit`, added by
+master commits `b23319bbe`/`f3d9a7967` — "Prevent accidental request dropping
+with maxRequestsPerCrawl"): the `maxNewRequests` budget/`requestsOverLimit`
+mechanism, and the `MAX_UNPROCESSED_REQUESTS_RETRIES` retry cap (master commit
+`b3170a60c`, prevents infinite retries when the platform permanently rejects a
+request). Neither commit is an ancestor of the current v4-derived HEAD nor
+present in the remaining rebase-todo (likely because they were independently
+backported to master under different hashes than their v4 equivalents,
+`a50afb62d`/`6d4a75e74`, which never made it into this rebase's commit list).
+Ported both pieces verbatim from master's `request_provider.ts` into the new
+`request_queue.ts` (constant, options fields, and the full
+`attemptToAddToQueueAndAddAnyUnprocessed`/`processChunk`/`buildResult` body),
+and restored the two master-only regression tests for them in
+`test/core/storages/request_queue.test.ts` (`addRequestsBatched does not retry
+permanently unprocessed requests forever`, `addRequestsBatched does not
+re-submit already enqueued requests beyond the initial batch (#3120)`).
+
+Also found and dropped a genuine dead/duplicated code block in
+`packages/memory-storage/src/resource-clients/request-queue.ts`'s
+`releaseOwnLocks()`: the conflict's HEAD side had a trailing block referencing
+`requestModel`, `isRequestHandledStateChanging`, `requestWasHandledBeforeUpdate`
+— variables that don't exist anywhere in `releaseOwnLocks()`'s scope. This was
+leftover orphaned content from an old, already-superseded unified `update()`
+method (removed from this file earlier in the rebase, per an earlier entry in
+this log) that got misattached to `releaseOwnLocks()` by an earlier merge in
+this same rebase. `releaseOwnLocks()` is self-contained in both master and v4
+and doesn't touch `handledRequestCount` — deleted the dead block entirely.
+
+Also dropped an orphaned 2-line test fragment in
+`test/core/storages/request_queue.test.ts`: `f1f095913` renamed `'should cache
+new requests locally'` to `'adding the same uniqueKey twice does not duplicate
+and is served from the local cache'` with a substantially rewritten body (a
+rename + rewrite, not a simple edit). Git's merge left the old test's opening
+two lines behind as an unconflicting fragment ahead of the conflict region;
+the renamed test's full new body already landed earlier in the file
+(confirmed via grep, `line 61`). Deleted the orphaned fragment.
diff --git a/docs/experiments/request_locking.mdx b/docs/experiments/request_locking.mdx
deleted file mode 100644
index 46ad112f4..000000000
--- a/docs/experiments/request_locking.mdx
+++ /dev/null
@@ -1,146 +0,0 @@
----
-id: experiments-request-locking
-title: Request Locking
-description: Parallelize crawlers with ease using request locking
----
-
-import ApiLink from '@site/src/components/ApiLink';
-
-:::tip Release announcement
-
-As of **May 2024** (`crawlee` version `3.10.0`), this experiment is now enabled by default! With that said, if you encounter issues you can:
-
-- set `requestLocking` to `false` in the `experiments` object of your crawler options
-- update all imports of `RequestQueue` to `RequestQueueV1`
-- open an issue on our [GitHub repository](https://github.com/apify/crawlee)
-
-The content below is kept for documentation purposes.
-If you're interested in the changes, you can read the [blog post about the new Request Queue storage system on the Apify blog](https://blog.apify.com/new-apify-request-queue/).
-
-:::
-
----
-
-:::caution
-
-This is an experimental feature. While we welcome testers, keep in mind that it is currently not recommended to use this in production.
-
-The API is subject to change, and we might introduce breaking changes in the future.
-
-Should you be using this, feel free to open issues on our [GitHub repository](https://github.com/apify/crawlee), and we'll take a look.
-
-:::
-
-Starting with `crawlee` version `3.5.5`, we have introduced a new crawler option that lets you enable using a new request locking
-API. With this API, you will be able to pass a `RequestQueue` to multiple crawlers to parallelize the crawling process.
-
-:::info Keep in mind
-
-The request queue that supports request locking is currently exported via the `RequestQueueV2` class. Once the experiment is over, this class will replace
-the current `RequestQueue` class
-
-:::
-
-## How to enable the experiment
-
-### In crawlers
-
-:::note
-
-This example shows how to enable the experiment in the <ApiLink to="cheerio-crawler/class/CheerioCrawler">`CheerioCrawler`</ApiLink>,
-but you can apply this to any crawler type.
-
-:::
-
-```ts
-import { CheerioCrawler } from 'crawlee';
-
-const crawler = new CheerioCrawler({
- // highlight-next-line
- experiments: {
- // highlight-next-line
- requestLocking: true,
- // highlight-next-line
- },
- async requestHandler({ $, request }) {
- const title = $('title').text();
- console.log(`The title of "${request.url}" is: ${title}.`);
- },
-});
-
-await crawler.run(['https://crawlee.dev']);
-```
-
-### Outside crawlers (to setup your own request queue that supports locking)
-
-Previously, you would import `RequestQueue` from `crawlee`. To switch to the queue that supports locking, you need to import `RequestQueueV2` instead.
-
-```ts
-// highlight-next-line
-import { RequestQueueV2 } from 'crawlee';
-
-const queue = await RequestQueueV2.open('my-locking-queue');
-await queue.addRequests([
- { url: 'https://crawlee.dev' },
- { url: 'https://crawlee.dev/js/docs' },
- { url: 'https://crawlee.dev/js/api' },
-]);
-```
-
-### Using the new request queue in crawlers
-
-If you make your own request queue that supports locking, you will also need to enable the experiment in your crawlers.
-
-:::danger
-
-If you do not enable the experiment, you will receive a runtime error and the crawler will not start.
-
-:::
-
-```ts
-import { CheerioCrawler, RequestQueueV2 } from 'crawlee';
-
-// highlight-next-line
-const queue = await RequestQueueV2.open('my-locking-queue');
-
-const crawler = new CheerioCrawler({
- // highlight-next-line
- experiments: {
- // highlight-next-line
- requestLocking: true,
- // highlight-next-line
- },
- // highlight-next-line
- requestQueue: queue,
- async requestHandler({ $, request }) {
- const title = $('title').text();
- console.log(`The title of "${request.url}" is: ${title}.`);
- },
-});
-
-await crawler.run();
-```
-
-## Other changes
-
-:::info
-
-This section is only useful if you're a tinkerer and want to see what's going on under the hood.
-
-:::
-
-In order to facilitate the new request locking API, as well as keep both the current request queue logic and the new, locking based request queue
-logic, we have implemented a common starting point called `RequestProvider`.
-
-This class implements almost all functions by default, but expects you, the developer, to implement the following methods:
-`fetchNextRequest` and `ensureHeadIsNotEmpty`. These methods are responsible for loading and returning requests to process,
-and tell crawlers if there are more requests to process.
-
-You can use this base class to implement your own request providers if you need to fetch requests from a different source.
-
-:::tip
-
-We recommend you use TypeScript when implementing your own request provider, as it comes with suggestions for the abstract methods, as well as
-giving you the exact types you need to return.
-
-:::
diff --git a/docs/guides/parallel-scraping/parallel-scraper.mjs b/docs/guides/parallel-scraping/parallel-scraper.mjs
index ad6b9364b..78162002c 100644
--- a/docs/guides/parallel-scraping/parallel-scraper.mjs
+++ b/docs/guides/parallel-scraping/parallel-scraper.mjs
@@ -92,12 +92,8 @@ if (!process.env.IN_WORKER_THREAD) {
// Instead of the long requestHandler with
// if clauses we provide a router instance.
requestHandler: router,
- // Enable the request locking experiment so that we can actually use the queue.
- // highlight-start
- experiments: {
- requestLocking: true,
- },
// Provide the request queue we've pre-filled in previous steps
+ // highlight-start
requestQueue,
// highlight-end
// Let's also limit the crawler's concurrency, we don't want to overload a single process 🐌
diff --git a/docs/guides/parallel-scraping/parallel-scraping.mdx b/docs/guides/parallel-scraping/parallel-scraping.mdx
index a717e81bf..a22284a6f 100644
--- a/docs/guides/parallel-scraping/parallel-scraping.mdx
+++ b/docs/guides/parallel-scraping/parallel-scraping.mdx
@@ -12,12 +12,6 @@ import AdaptedRoutesSource from '!!raw-loader!./adapted-routes.mjs';
import ParallelScraperSource from '!!raw-loader!./parallel-scraper.mjs';
import ModifiedDetailRouteSource from '!!raw-loader!./modified-detail-route.mjs';
-:::warning Experimental features ahead
-
-At the time of writing this guide (December 2023), request locking is still an experimental feature. You can read more about the experiment by visiting the [request locking experiment](../experiments/experiments-request-locking) page.
-
-:::
-
In this guide, we will walk you through how you can turn your single scraper into a scraper that can be parallelized and run in multiple instances. This guide assumes you've read and walked through our [introduction guide](../introduction/setting-up) (or have a fully-fledged scraper already built), but if you haven't done so yet, take a break, go read through all that, and come back. We'll be waiting...
*Oh, you're back already! Let's proceed in making that scraper parallel!*
@@ -151,9 +145,9 @@ const config = new Configuration({
});
```
-#### Enabling the request locking experiment, and telling the crawler to use the worker configuration
+#### Telling the crawler to use the worker configuration
-You might have noticed several lines highlighted in the code above. Those show how you can enable the request locking experiment, as well as how you provide the request queue to the crawler. You can read more about the experiment by visiting the [request locking experiment](../experiments/experiments-request-locking) page.
+You might have noticed several lines highlighted in the code above. Those show how you provide the shared request queue to the crawler.
You might have also noticed we passed in a second parameter to the constructor of the crawler, the `config` variable we created earlier. This is needed to ensure the crawler uses the worker-specific storages for internal states, and that they do not collide with each other.
diff --git a/docs/guides/parallel-scraping/shared.mjs b/docs/guides/parallel-scraping/shared.mjs
index ff627fdee..0233e37fa 100644
--- a/docs/guides/parallel-scraping/shared.mjs
+++ b/docs/guides/parallel-scraping/shared.mjs
@@ -1,6 +1,6 @@
-import { RequestQueueV2 } from 'crawlee';
+import { RequestQueue } from 'crawlee';
-// Create the request queue that also supports parallelization
+// The request queue shared by all the parallel workers
let queue;
/**
@@ -12,11 +12,11 @@ export async function getOrInitQueue(makeFresh = false) {
return queue;
}
- queue = await RequestQueueV2.open('shop-urls');
+ queue = await RequestQueue.open('shop-urls');
if (makeFresh) {
await queue.drop();
- queue = await RequestQueueV2.open('shop-urls');
+ queue = await RequestQueue.open('shop-urls');
}
return queue;
diff --git a/docs/guides/request_loaders.mdx b/docs/guides/request_loaders.mdx
index 23b7444f7..d2be9bd6c 100644
--- a/docs/guides/request_loaders.mdx
+++ b/docs/guides/request_loaders.mdx
@@ -53,7 +53,7 @@ class IRequestLoader {
+ getPendingCount()
+ getHandledCount()
+ fetchNextRequest()
- + markRequestHandled()
+ + markRequestAsHandled()
+ isEmpty()
+ isFinished()
+ toTandem()
diff --git a/docs/guides/request_loaders_rl_basic.ts b/docs/guides/request_loaders_rl_basic.ts
index c974b668b..bea941f73 100644
--- a/docs/guides/request_loaders_rl_basic.ts
+++ b/docs/guides/request_loaders_rl_basic.ts
@@ -11,5 +11,5 @@ const requestList = await RequestList.open('my-list', [
// Iterate over the requests manually (a crawler does this for you under the hood).
for await (const request of requestList) {
console.log(request.url);
- await requestList.markRequestHandled(request);
+ await requestList.markRequestAsHandled(request);
}
diff --git a/docs/guides/request_loaders_sitemap_basic.ts b/docs/guides/request_loaders_sitemap_basic.ts
index fff7c2867..2e76f19a1 100644
--- a/docs/guides/request_loaders_sitemap_basic.ts
+++ b/docs/guides/request_loaders_sitemap_basic.ts
@@ -10,5 +10,5 @@ const sitemapRequestLoader = await SitemapRequestLoader.open({
for await (const request of sitemapRequestLoader) {
console.log(request.url);
- await sitemapRequestLoader.markRequestHandled(request);
+ await sitemapRequestLoader.markRequestAsHandled(request);
}
diff --git a/docs/upgrading/upgrading_v4.md b/docs/upgrading/upgrading_v4.md
index 67a965ba3..543284cb4 100644
--- a/docs/upgrading/upgrading_v4.md
+++ b/docs/upgrading/upgrading_v4.md
@@ -560,11 +560,58 @@ The sub-client interfaces (`DatasetClient`, `KeyValueStoreClient`, `RequestQueue
**`RequestQueueClient`:**
+The request queue client was reduced from 12 methods to 10. The distributed-locking protocol (`listAndLockHead` → `prolongRequestLock` → `deleteRequestLock`) and the queue-head/consistency bookkeeping that used to live in the `RequestQueue` frontend have been removed from the interface; coordinating multiple clients accessing the same queue (e.g. request locking on the Apify platform) is now an internal concern of the client implementation.
+
| Before (v3) | After (v4) |
|---|---|
+| `addRequest(request, opts?)` | `addBatchOfRequests([request], opts?)` |
+| `batchAddRequests(requests, opts?)` | `addBatchOfRequests(requests, opts?)` |
+| `getRequest(id)` | `getRequest(uniqueKey)` |
+| `updateRequest(request, opts?)` | `markRequestAsHandled(request)` / `reclaimRequest(request, opts?)` |
+| `listHead(opts?)` | `fetchNextRequest()` (returns a single request, marks it in progress) |
+| `listAndLockHead(opts)` | Removed (locking is internal to the client) |
+| `prolongRequestLock(id, opts)` | Removed |
+| `deleteRequestLock(id, opts?)` | Removed |
| `deleteRequest(id)` | Removed |
+| _(n/a)_ | `isEmpty()` (new — `true` when no pending requests are left to fetch) |
+| _(n/a)_ | `isFinished()` (new — `true` when no pending **and** no in-progress requests remain) |
+
+The lifecycle is now: `fetchNextRequest()` hands out a pending request and marks it in progress; once processed, call `markRequestAsHandled(request)`; on failure call `reclaimRequest(request, { forefront? })` to return it to the queue.
+
+`RequestQueueClient.isEmpty()` and `RequestQueueClient.isFinished()` answer two different questions:
+
+- `isEmpty()` is the weak check — `true` when the next `fetchNextRequest()` would return `null`, i.e. there is nothing left to fetch right now. Requests that are currently in progress (fetched but not yet handled or reclaimed) are **not** counted, because they are not fetchable. This is what drives the crawler's task scheduling.
+- `isFinished()` is the strong check — `true` only when there are no pending requests **and** no requests currently in progress (including those locked by other clients sharing the queue). This is what determines whether crawling is actually done. An in-progress request keeps the queue *empty but not finished*, which is what stops a crawler from shutting down while a request is still being processed.
+
+The separate `RequestQueueV1`/`RequestQueueV2` classes (and the `RequestProvider` base class) have been removed. They no longer differ in behavior — request coordination is now internal to the storage client — so they are merged into a single `RequestQueue` class. Replace any `RequestQueueV1`, `RequestQueueV2`, or `RequestProvider` imports with `RequestQueue`.
+
+The `requestLocking` crawler experiment has been removed, along with the `experiments` crawler option and the `CrawlerExperiments` type that contained it. Request locking has been the default since v3.10 and there is no longer an alternative implementation to opt out to, so the flag did nothing. Delete any `experiments: { requestLocking: ... }` from your crawler options:
+
+```diff
+ const crawler = new CheerioCrawler({
+ async requestHandler({ $, request }) {
+ // ...
+ },
+- experiments: {
+- requestLocking: true,
+- },
+ });
+```
-**Removed types** from `@crawlee/types`: `DatasetClientUpdateOptions`, `KeyValueStoreClientUpdateOptions`, `KeyValueStoreRecordOptions`, `KeyValueStoreClientListData`, `KeyValueStoreClientGetRecordOptions`. `KeyValueStoreClientListOptions` was renamed to `KeyValueStoreListKeysOptions`.
+The `RequestQueue.requestLockSecs` property has been removed. Because request locking is now internal to the storage client, the lock duration is no longer configured on the queue. When you run a crawler, it automatically tells the queue how long it expects to hold a request (based on `requestHandlerTimeoutMillis`), so a long-running request handler will not have its request handed out a second time — you usually don't need to configure anything.
+
+If you use a `RequestQueue` outside of a crawler and your processing may exceed the 3-minute default lock, call `setExpectedRequestProcessingTimeSecs(secs)` on the queue to raise it:
+
+```ts
+import { RequestQueue } from 'crawlee';
+
+const queue = await RequestQueue.open();
+queue.setExpectedRequestProcessingTimeSecs(600);
+```
+
+The `RequestQueue.internalTimeoutMillis` property and the associated "stuck queue" self-recovery have been removed. In v3 the `RequestQueue` frontend kept its own copy of the queue head and in-progress set, which could drift out of sync with the backing storage (an eventual-consistency hazard on the Apify platform); `isFinished()` watched for inactivity exceeding `internalTimeoutMillis` and reset that frontend state to recover. In v4 the frontend no longer holds any such bookkeeping — the storage client is the single source of truth — so there is nothing for a reset to fix, and stuck request locks now self-heal on expiry. Any consistency-recovery logic that is genuinely specific to the Apify platform's distributed storage belongs in the Apify SDK's client implementation instead, and is tracked in [apify/crawlee#3328](https://github.com/apify/crawlee/issues/3328).
+
+**Removed types** from `@crawlee/types`: `DatasetClientUpdateOptions`, `KeyValueStoreClientUpdateOptions`, `KeyValueStoreRecordOptions`, `KeyValueStoreClientListData`, `KeyValueStoreClientGetRecordOptions`, `QueueHead`, `RequestQueueHeadItem`, `ListOptions`, `ListAndLockOptions`, `ListAndLockHeadResult`, `ProlongRequestLockOptions`, `ProlongRequestLockResult`, `DeleteRequestLockOptions`. `KeyValueStoreClientListOptions` was renamed to `KeyValueStoreListKeysOptions`.
The high-level storage classes (`Dataset`, `KeyValueStore`, `RequestQueue`) now receive their sub-client directly in the constructor options instead of receiving a `StorageClient` and calling its methods.
@@ -608,7 +655,7 @@ If you explicitly pass a `requestQueue` (or `requestManager`) to the crawler, th
When calling `crawler.run()` multiple times on the same crawler instance, v3 would drop the default request queue and create a fresh one between runs. In v4, the crawler **purges** the queue instead — clearing all requests and resetting internal counters, but keeping the same queue object. This is more efficient and avoids edge cases around stale references.
-The new `purge()` method is available on `RequestProvider` (the base class for `RequestQueue`) and is also defined as an optional method on the `IRequestManager` interface.
+The new `purge()` method is available on `RequestQueue` and is also defined as an optional method on the `IRequestManager` interface.
By default, only queues that the crawler created itself (the "owned" queue) are purged between runs — a user-supplied queue is never touched unless you explicitly opt in. The `purgeRequestQueue` option in `CrawlerRunOptions` controls this behavior:
@@ -697,6 +744,7 @@ The harmonized loader interface differs from the old `IRequestList` in a few way
| `length(): number` | `getTotalCount(): Promise<number>` (renamed and now async) |
| _(n/a)_ | `getPendingCount(): Promise<number>` (new) |
| `handledCount(): number` | `getHandledCount(): Promise<number>` (renamed and now async) |
+| `markRequestHandled(request)` | `markRequestAsHandled(request)` (renamed) |
| `reclaimRequest()` on the interface | Removed from the read-only loaders entirely; reclaiming is a write operation that lives only on `IRequestManager` (e.g. `RequestQueue`, `RequestManagerTandem`) |
| `inProgress: Set<string>` on the interface | Removed from the interface |
| `persistState(): Promise<void>` (required) | `persistState?(): Promise<void>` (optional) |
@@ -704,6 +752,8 @@ The harmonized loader interface differs from the old `IRequestList` in a few way
`RequestList.length()` and `RequestList.handledCount()` (and their `SitemapRequestLoader` counterparts) were renamed to `getTotalCount()` and `getHandledCount()` and are now `async` — `await` them.
+`markRequestHandled()` was renamed to `markRequestAsHandled()` across the loader and manager interfaces (`RequestList`, `SitemapRequestLoader`, `RequestQueue`, `RequestManagerTandem`) to match the storage client method of the same name (and the Python `mark_request_as_handled`). Rename any calls accordingly.
+
**Before:**
```typescript
const total = requestList.length();
@@ -775,7 +825,7 @@ The public `requestList` and `requestQueue` instance fields are gone. The crawle
### `getRequestQueue()` deprecated in favor of `getRequestManager()`
-`BasicCrawler.getRequestQueue()` is deprecated. It still works as an alias, but now returns an `IRequestManager` that is no longer guaranteed to be a `RequestProvider`/`RequestQueue` (it may be a `RequestManagerTandem`). Use `getRequestManager()` instead.
+`BasicCrawler.getRequestQueue()` is deprecated. It still works as an alias, but now returns an `IRequestManager` that is no longer guaranteed to be a `RequestQueue` (it may be a `RequestManagerTandem`). Use `getRequestManager()` instead.
**Before:**
```typescript
diff --git a/packages/basic-crawler/src/internals/basic-crawler.ts b/packages/basic-crawler/src/internals/basic-crawler.ts
index ef5a90541..7ca17aa12 100644
--- a/packages/basic-crawler/src/internals/basic-crawler.ts
+++ b/packages/basic-crawler/src/internals/basic-crawler.ts
@@ -49,9 +49,7 @@ import {
purgeDefaultStorages,
RequestHandlerError,
RequestManagerTandem,
- RequestProvider,
RequestQueue,
- RequestQueueV1,
RequestState,
RetryRequestError,
Router,
@@ -204,7 +202,7 @@ export interface BasicCrawlerOptions<
* @deprecated Use the `requestManager` option instead. A `RequestQueue` is itself a request manager, so you can
* pass it directly as `requestManager`.
*/
- requestQueue?: RequestProvider;
+ requestQueue?: RequestQueue;
/**
* Manager of requests that should be processed by the crawler. Mutually exclusive with the deprecated
@@ -376,12 +374,6 @@ export interface BasicCrawlerOptions<
*/
onSkippedRequest?: SkippedRequestCallback;
- /**
- * Enables experimental features of Crawlee, which can alter the behavior of the crawler.
- * WARNING: these options are not guaranteed to be stable and may change or be removed at any time.
- */
- experiments?: CrawlerExperiments;
-
/**
* Customize the way statistics collecting works, such as logging interval or
* whether to output them to the Key-Value store.
@@ -450,22 +442,6 @@ export interface BasicCrawlerOptions<
additionalHttpErrorStatusCodes?: number[];
}
-/**
- * A set of options that you can toggle to enable experimental features in Crawlee.
- *
- * NOTE: These options will not respect semantic versioning and may be removed or changed at any time. Use at your own risk.
- * If you do use these and encounter issues, please report them to us.
- */
-export interface CrawlerExperiments {
- /**
- * @deprecated This experiment is now enabled by default, and this flag will be removed in a future release.
- * If you encounter issues due to this change, please:
- * - report it to us: https://github.com/apify/crawlee
- * - set `requestLocking` to `false` in the `experiments` option of the crawler
- */
- requestLocking?: boolean;
-}
-
/**
* Provides a simple framework for parallel crawling of web pages.
* The URLs to crawl are fed either from a static list of URLs
@@ -684,9 +660,7 @@ export class BasicCrawler<
protected onSkippedRequest?: SkippedRequestCallback;
private _ownsEventManager = false;
private loggedPerRun = new Set<string>();
- private experiments: CrawlerExperiments;
private readonly robotsTxtFileCache: LruCache<RobotsTxtFile>;
- private _experimentWarnings: Partial<Record<keyof CrawlerExperiments, boolean>> = {};
private readonly crawlerId: string;
private readonly hasExplicitId: boolean;
private readonly crawlerInstanceIndex: number;
@@ -739,9 +713,6 @@ export class BasicCrawler<
maxRequestsPerMinute: ow.optional.number.integerOrInfinite.positive.greaterThanOrEqual(1),
keepAlive: ow.optional.boolean,
- // internal
- experiments: ow.optional.object,
-
statisticsOptions: ow.optional.object,
id: ow.optional.string,
@@ -798,9 +769,6 @@ export class BasicCrawler<
statisticsOptions,
httpClient,
- // internal
- experiments = {},
-
id,
} = options;
@@ -861,7 +829,6 @@ export class BasicCrawler<
this.statusMessageLoggingInterval = statusMessageLoggingInterval;
this.statusMessageCallback = statusMessageCallback as StatusMessageCallback;
this.domainAccessedTime = new Map();
- this.experiments = experiments;
this.robotsTxtFileCache = new LruCache({ maxLength: 1000 });
this.handleSkippedRequest = this.handleSkippedRequest.bind(this);
@@ -888,8 +855,8 @@ export class BasicCrawler<
tryEnv(process.env.CRAWLEE_INTERNAL_TIMEOUT) ?? Math.max(this.requestHandlerTimeoutMillis * 2, 300e3);
// override the default internal timeout of request queue to respect `requestHandlerTimeoutMillis`
- if (this.requestManager instanceof RequestProvider) {
- this.applyRequestQueueTimeouts(this.requestManager);
+ if (this.requestManager !== undefined) {
+ this.applyRequestManagerTimeouts(this.requestManager);
}
this.maxRequestRetries = maxRequestRetries;
@@ -975,7 +942,7 @@ export class BasicCrawler<
// (e.g., doesn't match enqueue strategy after redirect). Just return gracefully.
if (error instanceof ContextPipelineInterruptedError) {
await this._timeoutAndRetry(
- async () => this.requestManager?.markRequestHandled(request),
+ async () => this.requestManager?.markRequestAsHandled(request),
this.internalTimeoutMillis,
`Marking request ${crawlingContext.request.url} (${crawlingContext.request.id}) as handled timed out after ${
this.internalTimeoutMillis / 1e3
@@ -1336,7 +1303,6 @@ export class BasicCrawler<
if (managerToPurge?.purge && shouldPurge) {
await managerToPurge.purge();
- this.handledRequestsCount = 0; // This would've been reset by this._init() further down below, but at that point `handledRequestsCount` could prevent `addRequests` from adding the initial requests
}
this.stats.reset();
@@ -1473,32 +1439,40 @@ export class BasicCrawler<
/**
* @deprecated Use {@apilink BasicCrawler.getRequestManager|`getRequestManager()`} instead. This returns the
- * crawler's request manager, which is no longer guaranteed to be a {@apilink RequestProvider}.
+ * crawler's request manager, which is no longer guaranteed to be a {@apilink RequestQueue}.
*/
async getRequestQueue(): Promise<IRequestManager> {
return this.getRequestManager();
}
/**
- * Opens the default {@apilink RequestQueue}, applies the crawler's internal timeouts and records it as the
+ * Opens the default {@apilink RequestQueue}, applies the crawler's timeouts to it and records it as the
* crawler-owned manager (so it gets purged between repeated `run()` calls).
* @private
*/
private async openOwnedRequestQueue(): Promise<IRequestManager> {
- const requestQueue = await this._getRequestQueue();
- this.applyRequestQueueTimeouts(requestQueue);
+ // The first crawler instance uses the default queue (null identifier);
+ // subsequent instances get their own queue via a unique alias so they don't collide.
+ const identifier =
+ this.crawlerInstanceIndex === 0 ? null : { alias: `__default_${this.crawlerInstanceIndex}__` };
+
+ const requestQueue = await RequestQueue.open(identifier, { config: serviceLocator.getConfiguration() });
+ this.applyRequestManagerTimeouts(requestQueue);
this.ownedRequestManager = requestQueue;
return requestQueue;
}
/**
- * Overrides the default internal timeouts of a {@apilink RequestProvider} to respect `requestHandlerTimeoutMillis`.
+ * Tells a request manager how long we expect to hold a fetched request, so that one backed by a
+ * locking storage client keeps it reserved for slightly longer than the request handler timeout
+ * (with some padding for overhead), but never for less than a minute. This prevents a long-running
+ * request from being handed out a second time while it is still being processed — and it works
+ * regardless of whether the manager is a plain {@apilink RequestQueue} or a `RequestManagerTandem`.
*/
- private applyRequestQueueTimeouts(requestQueue: RequestProvider): void {
- requestQueue.internalTimeoutMillis = this.internalTimeoutMillis;
- // for request queue v2, we want to lock requests for slightly longer than the request handler timeout so that
- // there is some padding for locking-related overhead, but never for less than a minute
- requestQueue.requestLockSecs = Math.max(this.requestHandlerTimeoutMillis / 1000 + 5, 60);
+ private applyRequestManagerTimeouts(requestManager: IRequestManager): void {
+ requestManager.setExpectedRequestProcessingTimeSecs?.(
+ Math.max(this.requestHandlerTimeoutMillis / 1000 + 5, 60),
+ );
}
/**
@@ -1798,13 +1772,9 @@ export class BasicCrawler<
this._ownsEventManager = true;
}
- // Initialize AutoscaledPool before awaiting _loadHandledRequestCount(),
- // so that the caller can get a reference to it before awaiting the promise returned from run()
- // (otherwise there would be no way)
this.autoscaledPool = new AutoscaledPool(this.autoscaledPoolOptions);
await this.getRequestManager();
- await this._loadHandledRequestCount();
}
protected async runRequestHandler(crawlingContext: ExtendedContext): Promise<void> {
@@ -1917,7 +1887,7 @@ export class BasicCrawler<
* adding it back to the queue after the timeout passes. Returns `true` if the request
* should be ignored and will be reclaimed to the queue once ready.
*/
- protected delayRequest(request: Request, source: RequestProvider | IRequestManager) {
+ protected delayRequest(request: Request, source: IRequestManager) {
const domain = getDomain(request.url);
if (!domain || !request) {
@@ -1932,11 +1902,6 @@ export class BasicCrawler<
return false;
}
- if (source instanceof RequestQueueV1) {
- // eslint-disable-next-line dot-notation
- source['inProgress']?.delete(request.id!);
- }
-
const delay = lastAccessTime + this.sameDomainDelayMillis - now;
this.log.debug(
`Request ${request.url} (${request.id}) will be reclaimed after ${delay} milliseconds due to same domain delay`,
@@ -1944,11 +1909,6 @@ export class BasicCrawler<
setTimeout(async () => {
this.log.debug(`Adding request ${request.url} (${request.id}) back to the queue`);
- if (source instanceof RequestQueueV1) {
- // eslint-disable-next-line dot-notation
- source['inProgress'].add(request.id!);
- }
-
await source.reclaimRequest(request, { forefront: request.userData?.__crawlee?.forefront });
}, delay);
@@ -1967,13 +1927,13 @@ export class BasicCrawler<
await this.runRequestHandler(crawlingContext);
await this._timeoutAndRetry(
- async () => requestSource.markRequestHandled(request!),
+ async () => requestSource.markRequestAsHandled(request!),
this.internalTimeoutMillis,
`Marking request ${request.url} (${request.id}) as handled timed out after ${
this.internalTimeoutMillis / 1e3
} seconds.`,
);
- isRequestLocked = false; // markRequestHandled succeeded and unlocked the request
+ isRequestLocked = false; // markRequestAsHandled succeeded and unlocked the request
this.stats.finishJob(statisticsId, request.retryCount);
@@ -1993,7 +1953,7 @@ export class BasicCrawler<
} seconds.`,
);
if (!(err instanceof CriticalError)) {
- isRequestLocked = false; // _requestFunctionErrorHandler calls either markRequestHandled or reclaimRequest
+ isRequestLocked = false; // _requestFunctionErrorHandler calls either markRequestAsHandled or reclaimRequest
}
request.state = RequestState.DONE;
} catch (secondaryError: any) {
@@ -2022,12 +1982,14 @@ export class BasicCrawler<
crawlingContext.session.markBad();
}
} finally {
- // Safety net - release the lock if nobody managed to do it before
- if (isRequestLocked && requestSource instanceof RequestProvider) {
+ // Safety net - return the request to the queue if nobody managed to mark it as handled
+ // or reclaim it before (e.g. after a CriticalError). Reclaiming a request that is no longer
+ // in progress is a harmless no-op on the storage client.
+ if (isRequestLocked && requestSource instanceof RequestQueue) {
try {
- await requestSource.client.deleteRequestLock(request.id!);
+ await requestSource.reclaimRequest(request);
} catch {
- // We don't have the lock, or the request was never locked. Either way it's fine
+ // The request was never in progress, or could not be reclaimed. Either way it's fine.
}
}
}
@@ -2240,7 +2202,7 @@ export class BasicCrawler<
// If we get here, the request is either not retryable
// or failed more than retryCount times and will not be retried anymore.
// Mark the request as failed and do not retry.
- await source.markRequestHandled(request);
+ await source.markRequestAsHandled(request);
this.stats.failJob(request.id || request.uniqueKey, request.retryCount);
await this._handleFailedRequestHandler(crawlingContext, error); // This function prints an error message.
@@ -2310,15 +2272,6 @@ export class BasicCrawler<
return request.retryCount < maxRequestRetries;
}
- /**
- * Updates handledRequestsCount from possibly stored counts, usually after worker migration.
- */
- protected async _loadHandledRequestCount(): Promise<void> {
- if (this.requestManager) {
- this.handledRequestsCount = await this.requestManager.getHandledCount();
- }
- }
-
/**
* Stops the crawler immediately.
*
@@ -2359,28 +2312,6 @@ export class BasicCrawler<
return request.headers?.Cookie || request.headers?.cookie || '';
}
- private async _getRequestQueue() {
- // The first crawler instance uses the default queue (null identifier);
- // subsequent instances get their own queue via a unique alias so they don't collide.
- const identifier =
- this.crawlerInstanceIndex === 0 ? null : { alias: `__default_${this.crawlerInstanceIndex}__` };
-
- // Check if it's explicitly disabled
- // oxlint-disable-next-line typescript/no-deprecated -- still honored for opt-out until the flag is removed
- if (this.experiments.requestLocking === false) {
- // oxlint-disable-next-line typescript/no-deprecated
- if (!this._experimentWarnings.requestLocking) {
- this.log.info('Using the old RequestQueue implementation without request locking.');
- // oxlint-disable-next-line typescript/no-deprecated
- this._experimentWarnings.requestLocking = true;
- }
-
- return RequestQueueV1.open(identifier, { config: serviceLocator.getConfiguration() });
- }
-
- return RequestQueue.open(identifier, { config: serviceLocator.getConfiguration() });
- }
-
private requestMatchesEnqueueStrategy(request: Request) {
// If `skipNavigation` was used, just return `true`
try {
diff --git a/packages/core/src/crawlers/crawler_commons.ts b/packages/core/src/crawlers/crawler_commons.ts
index 3b071d294..7f0c921e4 100644
--- a/packages/core/src/crawlers/crawler_commons.ts
+++ b/packages/core/src/crawlers/crawler_commons.ts
@@ -7,7 +7,7 @@ import type { CrawleeLogger } from '../log.js';
import type { Request, Source } from '../request.js';
import type { Dataset } from '../storages/dataset.js';
import { KeyValueStore, type RecordOptions } from '../storages/key_value_store.js';
-import type { RequestQueueOperationOptions } from '../storages/request_provider.js';
+import type { RequestQueueOperationOptions } from '../storages/request_queue.js';
import type { StorageIdentifier } from '../storages/storage_instance_manager.js';
/** @internal */
diff --git a/packages/core/src/enqueue_links/enqueue_links.ts b/packages/core/src/enqueue_links/enqueue_links.ts
index 2e70a037b..ca6eae95a 100644
--- a/packages/core/src/enqueue_links/enqueue_links.ts
+++ b/packages/core/src/enqueue_links/enqueue_links.ts
@@ -12,7 +12,7 @@ import type {
AddRequestsBatchedOptions,
AddRequestsBatchedResult,
RequestQueueOperationOptions,
-} from '../storages/request_provider.js';
+} from '../storages/request_queue.js';
import type {
GlobInput,
PseudoUrlInput,
diff --git a/packages/core/src/storages/index.ts b/packages/core/src/storages/index.ts
index cf66ee667..b66f8039f 100644
--- a/packages/core/src/storages/index.ts
+++ b/packages/core/src/storages/index.ts
@@ -3,10 +3,7 @@ export * from './key_value_store.js';
export * from './request_list.js';
export type * from './request_loader.js';
export type * from './request_manager.js';
-export * from './request_provider.js';
-export { RequestQueueV1 } from './request_queue.js';
-export { RequestQueue } from './request_queue_v2.js';
-export { RequestQueue as RequestQueueV2 } from './request_queue_v2.js';
+export * from './request_queue.js';
export * from './storage_instance_manager.js';
export * from './utils.js';
export * from './access_checking.js';
diff --git a/packages/core/src/storages/request_list.ts b/packages/core/src/storages/request_list.ts
index 02ac29b4a..7f253fbed 100644
--- a/packages/core/src/storages/request_list.ts
+++ b/packages/core/src/storages/request_list.ts
@@ -663,7 +663,7 @@ export class RequestList implements IRequestLoader {
/**
* @inheritDoc
*/
- async markRequestHandled(request: Request): Promise<void> {
+ async markRequestAsHandled(request: Request): Promise<void> {
const { uniqueKey } = request;
this._ensureUniqueKeyValid(uniqueKey);
@@ -827,7 +827,7 @@ export class RequestList implements IRequestLoader {
async toTandem(requestManager?: IRequestManager): Promise<IRequestManager> {
// Import here to avoid circular imports.
const { RequestManagerTandem } = await import('./request_manager_tandem.js');
- const { RequestQueue } = await import('./request_queue_v2.js');
+ const { RequestQueue } = await import('./request_queue.js');
return new RequestManagerTandem(this, requestManager ?? (await RequestQueue.open()));
}
diff --git a/packages/core/src/storages/request_loader.ts b/packages/core/src/storages/request_loader.ts
index 9292860f8..32687f6c9 100644
--- a/packages/core/src/storages/request_loader.ts
+++ b/packages/core/src/storages/request_loader.ts
@@ -2,7 +2,7 @@ import type { Dictionary } from '@crawlee/types';
import type { Request } from '../request.js';
import type { IRequestManager } from './request_manager.js';
-import type { RequestQueueOperationInfo } from './request_provider.js';
+import type { RequestQueueOperationInfo } from './request_queue.js';
/**
* An abstract interface defining a read-only stream of requests to crawl.
@@ -17,7 +17,7 @@ import type { RequestQueueOperationInfo } from './request_provider.js';
* ## Request lifecycle contract
*
* Every request returned by {@apilink IRequestLoader.fetchNextRequest} is considered **in progress**
- * until it is passed to {@apilink IRequestLoader.markRequestHandled}. Once you fetch a request, you are
+ * until it is passed to {@apilink IRequestLoader.markRequestAsHandled}. Once you fetch a request, you are
* obligated to eventually mark it as handled — there is no way to hand a request back to a loader
* (only an {@apilink IRequestManager} can reclaim requests for a retry). "Handled" therefore means
* "finished with this request", whether processing succeeded or was abandoned after exhausting retries.
@@ -29,7 +29,7 @@ import type { RequestQueueOperationInfo } from './request_provider.js';
* - **Termination detection:** {@apilink IRequestLoader.isFinished} only resolves to `true` once nothing is
* in progress. Leaving a request unmarked keeps the crawler running indefinitely.
* - **Bookkeeping:** the handled and pending counts are derived from the set of in-progress requests, so
- * skipping {@apilink IRequestLoader.markRequestHandled} corrupts {@apilink IRequestLoader.getHandledCount}
+ * skipping {@apilink IRequestLoader.markRequestAsHandled} corrupts {@apilink IRequestLoader.getHandledCount}
* and {@apilink IRequestLoader.getPendingCount}.
*
* Concrete implementations such as {@apilink RequestList} or {@apilink SitemapRequestLoader} build on this interface.
@@ -67,7 +67,7 @@ export interface IRequestLoader {
* Gets the next {@apilink Request} to process, or `null` if there are no more pending requests.
*
* The returned request is marked as **in progress** and remains so until it is passed to
- * {@apilink IRequestLoader.markRequestHandled}. The caller is responsible for eventually marking
+ * {@apilink IRequestLoader.markRequestAsHandled}. The caller is responsible for eventually marking
* every fetched request as handled; otherwise the loader never considers itself finished and the
* request may be re-served after a restart. See the request lifecycle contract on {@apilink IRequestLoader}.
*/
@@ -88,7 +88,7 @@ export interface IRequestLoader {
* signal completion; failing to do so prevents {@apilink IRequestLoader.isFinished} from ever resolving to
* `true` and skews the handled and pending counts. See the request lifecycle contract on {@apilink IRequestLoader}.
*/
- markRequestHandled(request: Request): Promise<RequestQueueOperationInfo | void | null>;
+ markRequestAsHandled(request: Request): Promise<RequestQueueOperationInfo | void | null>;
/**
* Persists the current state of the loader into the default {@apilink KeyValueStore}.
diff --git a/packages/core/src/storages/request_manager.ts b/packages/core/src/storages/request_manager.ts
index 64cae64e7..63095d453 100644
--- a/packages/core/src/storages/request_manager.ts
+++ b/packages/core/src/storages/request_manager.ts
@@ -5,7 +5,7 @@ import type {
AddRequestsBatchedResult,
RequestQueueOperationInfo,
RequestQueueOperationOptions,
-} from './request_provider.js';
+} from './request_queue.js';
export type RequestsLike = AsyncIterable<Source | string> | Iterable<Source | string> | (Source | string)[];
@@ -31,4 +31,14 @@ export interface IRequestManager extends IRequestLoader {
* Implementations that do not support purging may leave this `undefined`.
*/
purge?(): Promise<void>;
+
+ /**
+ * Tells the manager how long a consumer expects to hold a request fetched via `fetchNextRequest()`
+ * before marking it handled or reclaiming it (typically the request-handler timeout plus padding).
+ *
+ * Managers backed by a storage client that reserves requests via locking use this to avoid handing
+ * the same request out again while it is still being processed. Implementations that do not need
+ * this hint may leave it `undefined`.
+ */
+ setExpectedRequestProcessingTimeSecs?(secs: number): void;
}
diff --git a/packages/core/src/storages/request_manager_tandem.ts b/packages/core/src/storages/request_manager_tandem.ts
index d294f0b27..a6bc6c6ad 100644
--- a/packages/core/src/storages/request_manager_tandem.ts
+++ b/packages/core/src/storages/request_manager_tandem.ts
@@ -10,7 +10,7 @@ import type {
AddRequestsBatchedResult,
RequestQueueOperationInfo,
RequestQueueOperationOptions,
-} from './request_provider.js';
+} from './request_queue.js';
/**
* A request manager that combines a {@apilink IRequestLoader} (such as a `RequestList`) with a writable
@@ -25,6 +25,12 @@ export class RequestManagerTandem implements IRequestManager {
private requestManagerFactory: () => IRequestManager | Promise<IRequestManager>;
+ /**
+ * The latest expected request-processing time hinted via {@link setExpectedRequestProcessingTimeSecs}.
+ * Remembered so it can be applied to the writable manager once it is lazily resolved.
+ */
+ private expectedRequestProcessingSecs?: number;
+
/**
* @param requestLoader The read-only loader to read requests from first.
* @param requestManager The writable manager to transfer requests into and enqueue new ones. May be passed as a
@@ -48,6 +54,11 @@ export class RequestManagerTandem implements IRequestManager {
if (this.resolvedRequestManager === undefined) {
this.requestManagerPromise ??= Promise.resolve(this.requestManagerFactory());
this.resolvedRequestManager = await this.requestManagerPromise;
+
+ // Apply any hint received before the manager was resolved.
+ if (this.expectedRequestProcessingSecs !== undefined) {
+ this.resolvedRequestManager.setExpectedRequestProcessingTimeSecs?.(this.expectedRequestProcessingSecs);
+ }
}
return this.resolvedRequestManager;
}
@@ -81,7 +92,7 @@ export class RequestManagerTandem implements IRequestManager {
return false;
} finally {
// Mark it as handled so that the request doesn't get stuck in the `inProgress` state in the loader.
- await this.requestLoader.markRequestHandled(request);
+ await this.requestLoader.markRequestAsHandled(request);
}
}
@@ -173,8 +184,8 @@ export class RequestManagerTandem implements IRequestManager {
/**
* @inheritdoc
*/
- async markRequestHandled(request: Request): Promise<RequestQueueOperationInfo | void | null> {
- return (await this.getRequestManager()).markRequestHandled(request);
+ async markRequestAsHandled(request: Request): Promise<RequestQueueOperationInfo | void | null> {
+ return (await this.getRequestManager()).markRequestAsHandled(request);
}
/**
@@ -220,4 +231,14 @@ export class RequestManagerTandem implements IRequestManager {
async purge(): Promise<void> {
await (await this.getRequestManager()).purge?.();
}
+
+ /**
+ * Forwards the hint to the writable request manager — that is where requests are fetched from and
+ * reserved. The manager is opened lazily, so the value is remembered and applied once it resolves.
+ * @inheritdoc
+ */
+ setExpectedRequestProcessingTimeSecs(secs: number): void {
+ this.expectedRequestProcessingSecs = secs;
+ this.resolvedRequestManager?.setExpectedRequestProcessingTimeSecs?.(secs);
+ }
}
diff --git a/packages/core/src/storages/request_provider.ts b/packages/core/src/storages/request_provider.ts
deleted file mode 100644
index 99678e370..000000000
--- a/packages/core/src/storages/request_provider.ts
+++ /dev/null
@@ -1,1088 +0,0 @@
-import { inspect } from 'node:util';
-
-import type {
- BaseHttpClient,
- BatchAddRequestsResult,
- Dictionary,
- ProcessedRequest,
- QueueOperationInfo,
- RequestQueueClient,
- RequestQueueInfo,
-} from '@crawlee/types';
-import {
- chunkedAsyncIterable,
- downloadListOfUrls,
- getObjectType,
- isAsyncIterable,
- isIterable,
- peekableAsyncIterable,
- sleep,
-} from '@crawlee/utils';
-import ow from 'ow';
-import type { ReadonlyDeep } from 'type-fest';
-
-import { ListDictionary, LruCache } from '@apify/datastructures';
-import { cryptoRandomObjectId } from '@apify/utilities';
-
-import { Configuration } from '../configuration.js';
-import type { EventManager } from '../events/event_manager.js';
-import { EventType } from '../events/event_manager.js';
-import type { CrawleeLogger } from '../log.js';
-import type { ProxyConfiguration } from '../proxy_configuration.js';
-import type { InternalSource, RequestOptions, Source } from '../request.js';
-import { Request } from '../request.js';
-import { serviceLocator } from '../service_locator.js';
-import { checkStorageAccess } from './access_checking.js';
-import { RequestDeduplicationCache } from './request_dedup_cache.js';
-import type { IRequestManager, RequestsLike } from './request_manager.js';
-import type { IStorage, StorageIdentifier } from './storage_instance_manager.js';
-import { resolveStorageIdentifier } from './storage_instance_manager.js';
-import type { StorageOpenOptions } from './utils.js';
-import { getRequestId, purgeDefaultStorages, QUERY_HEAD_MIN_LENGTH } from './utils.js';
-
-/**
- * Maximum number of consecutive batch-add attempts that make no progress before the remaining
- * unprocessed requests are skipped, so permanently rejected requests don't retry forever.
- */
-const MAX_UNPROCESSED_REQUESTS_RETRIES = 3;
-
-
-export abstract class RequestProvider implements IStorage, IRequestManager {
- id: string;
- name?: string;
- timeoutSecs = 30;
- clientKey = cryptoRandomObjectId();
- client: RequestQueueClient;
- protected proxyConfiguration?: ProxyConfiguration;
-
- log: CrawleeLogger;
- internalTimeoutMillis = 5 * 60_000; // defaults to 5 minutes, will be overridden by BasicCrawler
- requestLockSecs = 3 * 60; // defaults to 3 minutes, will be overridden by BasicCrawler
-
- // We can trust these numbers only in a case that queue is used by a single client.
- // This information is returned by getHead() under the hadMultipleClients property.
- assumedTotalCount = 0;
- assumedHandledCount = 0;
-
- private isInitialized = false;
-
- protected queueHeadIds = new ListDictionary<string>();
- protected requestCache: LruCache<RequestLruItem>;
-
- /**
- * Remembers the `requestId` of every request already submitted to the client — including background
- * batches that `requestCache` skips — so overlapping URL sets aren't re-submitted.
- * See {@link RequestDeduplicationCache} for why this is a separate, cheaper cache.
- */
- protected requestSeenCache: RequestDeduplicationCache;
-
- protected recentlyHandledRequestsCache: LruCache<boolean>;
-
- protected queuePausedForMigration = false;
-
- protected lastActivity = new Date();
-
- protected isFinishedCalledWhileHeadWasNotEmpty = 0;
-
- protected inProgressRequestBatchCount = 0;
-
- protected httpClient?: BaseHttpClient;
-
- protected readonly events: EventManager;
-
- constructor(
- options: InternalRequestProviderOptions,
- protected readonly config: Configuration = Configuration.getGlobalConfig(),
- ) {
- this.id = options.id;
- this.name = options.name;
- this.events = serviceLocator.getEventManager();
- this.client = options.client;
-
- this.proxyConfiguration = options.proxyConfiguration;
-
- this.requestCache = new LruCache({ maxLength: options.requestCacheMaxSize });
- this.requestSeenCache = new RequestDeduplicationCache();
- this.recentlyHandledRequestsCache = new LruCache({ maxLength: options.recentlyHandledRequestsMaxSize });
- this.log = serviceLocator
- .getLogger()
- .child({ prefix: `${options.logPrefix}(${this.id}, ${this.name ?? 'no-name'})` });
-
- this.events.on(EventType.MIGRATING, async () => {
- this.queuePausedForMigration = true;
- });
- }
-
- /**
- * Returns the total number of requests in the queue (i.e. pending + handled).
- *
- * Survives restarts and actor migrations.
- */
- async getTotalCount() {
- const { totalRequestCount } = await this.getInfo();
- return totalRequestCount;
- }
-
- /**
- * Returns the total number of pending requests in the queue.
- *
- * Survives restarts and Actor migrations.
- */
- async getPendingCount() {
- const { totalRequestCount, handledRequestCount } = await this.getInfo();
- return totalRequestCount - handledRequestCount;
- }
-
- /**
- * Adds a request to the queue.
- *
- * If a request with the same `uniqueKey` property is already present in the queue,
- * it will not be updated. You can find out whether this happened from the resulting
- * {@apilink QueueOperationInfo} object.
- *
- * To add multiple requests to the queue by extracting links from a webpage,
- * see the {@apilink enqueueLinks} helper function.
- *
- * @param requestLike {@apilink Request} object or vanilla object with request data.
- * Note that the function sets the `uniqueKey` and `id` fields to the passed Request.
- * @param [options] Request queue operation options.
- */
- async addRequest(
- requestLike: Source,
- options: RequestQueueOperationOptions = {},
- ): Promise<RequestQueueOperationInfo> {
- checkStorageAccess();
-
- this.lastActivity = new Date();
-
- ow(requestLike, ow.object);
- ow(
- options,
- ow.object.exactShape({
- forefront: ow.optional.boolean,
- }),
- );
-
- const { forefront = false } = options;
-
- if ('requestsFromUrl' in requestLike) {
- const requests = await this._fetchRequestsFromUrl(requestLike as InternalSource);
- const processedRequests = await this._addFetchedRequests(requestLike as InternalSource, requests, options);
-
- return { ...processedRequests[0], forefront };
- }
-
- ow(
- requestLike,
- ow.object.partialShape({
- url: ow.string,
- id: ow.undefined,
- }),
- );
-
- const request = requestLike instanceof Request ? requestLike : new Request(requestLike);
-
- const cacheKey = getRequestId(request.uniqueKey);
- const cachedInfo = this.requestCache.get(cacheKey);
-
- if (cachedInfo) {
- request.id = cachedInfo.id;
- return {
- wasAlreadyPresent: true,
- // We may assume that if request is in local cache then also the information if the
- // request was already handled is there because just one client should be using one queue.
- wasAlreadyHandled: cachedInfo.isHandled,
- requestId: cachedInfo.id,
- uniqueKey: cachedInfo.uniqueKey,
- forefront,
- };
- }
-
- const queueOperationInfo = {
- ...(await this.client.addRequest(request, { forefront })),
- uniqueKey: request.uniqueKey,
- forefront,
- } satisfies RequestQueueOperationInfo;
-
- const { requestId, wasAlreadyPresent } = queueOperationInfo;
- this._cacheRequest(cacheKey, queueOperationInfo);
- this.requestSeenCache.add(cacheKey, requestId);
-
- if (!wasAlreadyPresent && !this.recentlyHandledRequestsCache.get(requestId)) {
- this.assumedTotalCount++;
-
- // Performance optimization: add request straight to head if possible
- this._maybeAddRequestToQueueHead(requestId, forefront);
- }
-
- return queueOperationInfo;
- }
-
- /**
- * Adds requests to the queue in batches of 25. This method will wait till all the requests are added
- * to the queue before resolving. You should prefer using `queue.addRequestsBatched()` or `crawler.addRequests()`
- * if you don't want to block the processing, as those methods will only wait for the initial 1000 requests,
- * start processing right after that happens, and continue adding more in the background.
- *
- * If a request passed in is already present due to its `uniqueKey` property being the same,
- * it will not be updated. You can find out whether this happened by finding the request in the resulting
- * {@apilink BatchAddRequestsResult} object.
- *
- * @param requestsLike {@apilink Request} objects or vanilla objects with request data.
- * Note that the function sets the `uniqueKey` and `id` fields to the passed requests if missing.
- * @param [options] Request queue operation options.
- */
- async addRequests(
- requestsLike: RequestsLike,
- options: RequestQueueOperationOptions = {},
- ): Promise<BatchAddRequestsResult> {
- checkStorageAccess();
-
- this.lastActivity = new Date();
-
- ow(
- requestsLike,
- ow.object
- .is((value: unknown) => isIterable(value) || isAsyncIterable(value))
- .message((value) => `Expected an iterable or async iterable, got ${getObjectType(value)}`),
- );
- ow(
- options,
- ow.object.exactShape({
- forefront: ow.optional.boolean,
- cache: ow.optional.boolean,
- }),
- );
-
- const { forefront = false, cache = true } = options;
-
- const uniqueKeyToCacheKey = new Map<string, string>();
- const getCachedRequestId = (uniqueKey: string) => {
- const cached = uniqueKeyToCacheKey.get(uniqueKey);
-
- if (cached) return cached;
-
- const newCacheKey = getRequestId(uniqueKey);
- uniqueKeyToCacheKey.set(uniqueKey, newCacheKey);
-
- return newCacheKey;
- };
-
- const results: BatchAddRequestsResult = {
- processedRequests: [],
- unprocessedRequests: [],
- };
-
- const requests: Request<Dictionary>[] = [];
-
- for await (const requestLike of requestsLike) {
- if (typeof requestLike === 'string') {
- requests.push(new Request({ url: requestLike }));
- } else if ('requestsFromUrl' in requestLike) {
- const fetchedRequests = await this._fetchRequestsFromUrl(requestLike as InternalSource);
- await this._addFetchedRequests(requestLike as InternalSource, fetchedRequests, options);
- } else {
- requests.push(
- requestLike instanceof Request ? requestLike : new Request(requestLike as RequestOptions),
- );
- }
- }
-
- const requestsToAdd = new Map<string, Request>();
-
- for (const request of requests) {
- const cacheKey = getCachedRequestId(request.uniqueKey);
- // Prefer the full `requestCache` record; fall back to the dedup cache for background batches it skips.
- const cachedInfo = this.requestCache.get(cacheKey);
- const knownRequestId = cachedInfo?.id ?? this.requestSeenCache.get(cacheKey);
-
- if (knownRequestId) {
- request.id = knownRequestId;
- results.processedRequests.push({
- wasAlreadyPresent: true,
- // The dedup cache doesn't track the handled state; only the full record does.
- wasAlreadyHandled: cachedInfo?.isHandled ?? false,
- requestId: knownRequestId,
- uniqueKey: request.uniqueKey,
- });
- } else if (!requestsToAdd.has(request.uniqueKey)) {
- requestsToAdd.set(request.uniqueKey, request);
- }
- }
-
- // Early exit if all provided requests were already added
- if (!requestsToAdd.size) {
- return results;
- }
-
- const apiResults = await this.client.batchAddRequests([...requestsToAdd.values()], { forefront });
-
- // Report unprocessed requests
- results.unprocessedRequests = apiResults.unprocessedRequests;
-
- // Add all new requests to the requestCache
- for (const newRequest of apiResults.processedRequests) {
- // Add the new request to the processed list
- results.processedRequests.push(newRequest);
-
- const cacheKey = getCachedRequestId(newRequest.uniqueKey);
-
- const { requestId, wasAlreadyPresent } = newRequest;
-
- if (cache) {
- this._cacheRequest(cacheKey, { ...newRequest, forefront });
- }
-
- // Unlike `requestCache`, populate this on every batch (including background ones).
- this.requestSeenCache.add(cacheKey, requestId);
-
- if (!wasAlreadyPresent && !this.recentlyHandledRequestsCache.get(requestId)) {
- this.assumedTotalCount++;
-
- // Performance optimization: add request straight to head if possible
- this._maybeAddRequestToQueueHead(requestId, forefront);
- }
- }
-
- return results;
- }
-
- /**
- * Adds requests to the queue in batches. By default, it will resolve after the initial batch is added, and continue
- * adding the rest in the background. You can configure the batch size via `batchSize` option and the sleep time in between
- * the batches via `waitBetweenBatchesMillis`. If you want to wait for all batches to be added to the queue, you can use
- * the `waitForAllRequestsToBeAdded` promise you get in the response object.
- *
- * @param requests The requests to add
- * @param options Options for the request queue
- */
- async addRequestsBatched(
- requests: ReadonlyDeep<RequestsLike>,
- options: AddRequestsBatchedOptions = {},
- ): Promise<AddRequestsBatchedResult> {
- checkStorageAccess();
-
- this.lastActivity = new Date();
- ow(
- requests,
- ow.object
- .is((value: unknown) => isIterable(value) || isAsyncIterable(value))
- .message((value) => `Expected an iterable or async iterable, got ${getObjectType(value)}`),
- );
-
- ow(
- options,
- ow.object.exactShape({
- forefront: ow.optional.boolean,
- waitForAllRequestsToBeAdded: ow.optional.boolean,
- batchSize: ow.optional.number,
- waitBetweenBatchesMillis: ow.optional.number,
- maxNewRequests: ow.optional.number,
- }),
- );
-
- const addRequest = this.addRequest.bind(this);
-
- async function* generateRequests() {
- for await (const opts of requests) {
- // Validate the input
- if (typeof opts === 'object' && opts !== null) {
- if (opts.url !== undefined && typeof opts.url !== 'string') {
- throw new Error(
- `Request options are not valid, the 'url' property is not a string. Input: ${inspect(opts)}`,
- );
- }
-
- if (opts.id !== undefined) {
- throw new Error(
- `Request options are not valid, the 'id' property must not be present. Input: ${inspect(opts)}`,
- );
- }
-
- if (
- (opts as any).requestsFromUrl !== undefined &&
- typeof (opts as any).requestsFromUrl !== 'string'
- ) {
- throw new Error(
- `Request options are not valid, the 'requestsFromUrl' property is not a string. Input: ${inspect(opts)}`,
- );
- }
- }
-
- if (opts && typeof opts === 'object' && 'requestsFromUrl' in opts) {
- // Handle URL lists right away
- await addRequest(opts, { forefront: options.forefront });
- } else {
- // Yield valid requests
- yield typeof opts === 'string' ? { url: opts } : (opts as RequestOptions);
- }
- }
- }
-
- const { batchSize = 1000, waitBetweenBatchesMillis = 1000, maxNewRequests } = options;
-
- let remainingBudget = maxNewRequests ?? Infinity;
- const requestsOverLimit: Source[] = [];
-
- // If there's a limit on the number of added requests, do not send batches bigger than the limit
- const effectiveChunkSize =
- maxNewRequests !== undefined ? () => Math.min(batchSize, remainingBudget) : batchSize;
-
- // Hold onto the underlying iterator so we can drain leftovers from it in buildResult
- const requestIterator = generateRequests();
-
- const chunks = peekableAsyncIterable(
- chunkedAsyncIterable(requestIterator, effectiveChunkSize) as AsyncIterable<Source[]>,
- );
- const chunksIterator = chunks[Symbol.asyncIterator]();
-
- const attemptToAddToQueueAndAddAnyUnprocessed = async (
- providedRequests: Source[],
- cache = true,
- unsuccessfulAttempts = 0,
- ) => {
- const resultsToReturn: ProcessedRequest[] = [];
- const apiResult = await this.addRequests(providedRequests, { forefront: options.forefront, cache });
- resultsToReturn.push(...apiResult.processedRequests);
-
- if (apiResult.unprocessedRequests.length) {
- // Count attempts that make no progress, so permanently rejected requests (e.g. a malformed
- // `userData` shape causing a 400) don't loop forever. Any progress resets the counter.
- const attempts = apiResult.processedRequests.length ? 0 : unsuccessfulAttempts + 1;
-
- if (attempts >= MAX_UNPROCESSED_REQUESTS_RETRIES) {
- this.log.warning(
- `Some requests were consistently rejected by the request queue and will be skipped after ${MAX_UNPROCESSED_REQUESTS_RETRIES} attempts. This usually means the request data is malformed (e.g. an invalid 'userData' shape).`,
- { unprocessedRequests: apiResult.unprocessedRequests },
- );
-
- return resultsToReturn;
- }
-
- await sleep(waitBetweenBatchesMillis);
-
- resultsToReturn.push(
- ...(await attemptToAddToQueueAndAddAnyUnprocessed(
- providedRequests.filter(
- (r) => !apiResult.processedRequests.some((pr) => pr.uniqueKey === r.uniqueKey),
- ),
- false,
- attempts,
- )),
- );
- }
-
- return resultsToReturn;
- };
-
- /**
- * Process a chunk: send it to the queue, then update the remaining budget if maxNewRequests is active.
- */
- const processChunk = async (chunk: Source[], cache = true) => {
- const results = await attemptToAddToQueueAndAddAnyUnprocessed(chunk, cache);
-
- if (maxNewRequests !== undefined) {
- remainingBudget -= results.filter((r) => !r.wasAlreadyPresent).length;
- }
-
- return results;
- };
-
- /**
- * Build the final result. When maxNewRequests is set, drains any remaining items
- * from the underlying request iterator into requestsOverLimit.
- *
- * We accept the iterator explicitly (rather than closing over it) to make it obvious
- * that this is the *same* iterator that `chunkedAsyncIterable` has been consuming —
- * so only unconsumed items are drained. We drain `requestIterator` (not `chunks`)
- * because `chunkedAsyncIterable` stops yielding when the budget-based chunk size
- * drops to 0, leaving unconsumed items in the underlying iterator.
- */
- const buildResult = async (
- addedRequests: ProcessedRequest[],
- waitForAllRequestsToBeAdded: Promise<ProcessedRequest[]>,
- unconsumedIterator: AsyncGenerator<RequestOptions>,
- ): Promise<AddRequestsBatchedResult> => {
- if (maxNewRequests !== undefined) {
- for await (const request of unconsumedIterator) {
- requestsOverLimit.push(request);
- }
- }
-
- return { addedRequests, waitForAllRequestsToBeAdded, requestsOverLimit };
- };
-
- // Add initial batch to process right away
- const initialChunk = await chunksIterator.peek();
- if (initialChunk === undefined) {
- return buildResult([], Promise.resolve([]), requestIterator);
- }
-
- const addedRequests = await processChunk(initialChunk);
- await chunksIterator.next();
-
- // If we have no more requests to add (either exhausted or budget hit), return immediately
- if ((await chunksIterator.peek()) === undefined) {
- return buildResult(addedRequests, Promise.resolve([]), requestIterator);
- }
-
- // eslint-disable-next-line no-async-promise-executor
- const promise = new Promise<ProcessedRequest[]>(async (resolve) => {
- const finalAddedRequests: ProcessedRequest[] = [];
-
- for await (const requestChunk of chunks) {
- finalAddedRequests.push(...(await processChunk(requestChunk, false)));
- await sleep(waitBetweenBatchesMillis);
- }
-
- resolve(finalAddedRequests);
- });
-
- this.inProgressRequestBatchCount += 1;
- void promise.finally(() => {
- this.inProgressRequestBatchCount -= 1;
- });
-
- // When maxNewRequests is set, we must wait for all batches so we can accurately report skipped requests.
- if (options.waitForAllRequestsToBeAdded || maxNewRequests !== undefined) {
- addedRequests.push(...(await promise));
- }
-
- return buildResult(addedRequests, promise, requestIterator);
- }
-
- /**
- * Gets the request from the queue specified by ID.
- *
- * @param id ID of the request.
- * @returns Returns the request object, or `null` if it was not found.
- */
- async getRequest<T extends Dictionary = Dictionary>(id: string): Promise<Request<T> | null> {
- checkStorageAccess();
-
- ow(id, ow.string);
-
- const requestOptions = await this.client.getRequest(id);
- if (!requestOptions) return null;
-
- return new Request(requestOptions as unknown as RequestOptions);
- }
-
- /**
- * Returns a next request in the queue to be processed, or `null` if there are no more pending requests.
- *
- * Once you successfully finish processing of the request, you need to call
- * {@apilink RequestQueue.markRequestHandled}
- * to mark the request as handled in the queue. If there was some error in processing the request,
- * call {@apilink RequestQueue.reclaimRequest} instead,
- * so that the queue will give the request to some other consumer in another call to the `fetchNextRequest` function.
- *
- * Note that the `null` return value doesn't mean the queue processing finished,
- * it means there are currently no pending requests.
- * To check whether all requests in queue were finished,
- * use {@apilink RequestQueue.isFinished} instead.
- *
- * @returns
- * Returns the request object or `null` if there are no more pending requests.
- */
- abstract fetchNextRequest<T extends Dictionary = Dictionary>(): Promise<Request<T> | null>;
-
- /**
- * Marks a request that was previously returned by the
- * {@apilink RequestQueue.fetchNextRequest}
- * function as handled after successful processing.
- * Handled requests will never again be returned by the `fetchNextRequest` function.
- */
- async markRequestHandled(request: Request): Promise<RequestQueueOperationInfo | null> {
- checkStorageAccess();
-
- this.lastActivity = new Date();
-
- ow(
- request,
- ow.object.partialShape({
- id: ow.string,
- uniqueKey: ow.string,
- handledAt: ow.optional.string,
- }),
- );
-
- const forefront = this.requestCache.get(getRequestId(request.uniqueKey))?.forefront ?? false;
-
- const handledAt = request.handledAt ?? new Date().toISOString();
- const queueOperationInfo = {
- ...(await this.client.updateRequest({
- ...request,
- handledAt,
- })),
- uniqueKey: request.uniqueKey,
- forefront,
- } satisfies RequestQueueOperationInfo;
- request.handledAt = handledAt;
-
- this.recentlyHandledRequestsCache.add(request.id, true);
-
- if (!queueOperationInfo.wasAlreadyHandled) {
- this.assumedHandledCount++;
- }
-
- this.queueHeadIds.remove(request.id);
-
- this._cacheRequest(getRequestId(request.uniqueKey), queueOperationInfo);
-
- return queueOperationInfo;
- }
-
- /**
- * Reclaims a failed request back to the queue, so that it can be returned for processing later again
- * by another call to {@apilink RequestQueue.fetchNextRequest}.
- * The request record in the queue is updated using the provided `request` parameter.
- * For example, this lets you store the number of retries or error messages for the request.
- */
- async reclaimRequest(
- request: Request,
- options: RequestQueueOperationOptions = {},
- ): Promise<RequestQueueOperationInfo | null> {
- checkStorageAccess();
-
- this.lastActivity = new Date();
-
- ow(
- request,
- ow.object.partialShape({
- id: ow.string,
- uniqueKey: ow.string,
- }),
- );
- ow(
- options,
- ow.object.exactShape({
- forefront: ow.optional.boolean,
- }),
- );
-
- const { forefront = false } = options;
-
- // TODO: If request hasn't been changed since the last getRequest(),
- // we don't need to call updateRequest() and thus improve performance.
- const queueOperationInfo = {
- ...(await this.client.updateRequest(request, {
- forefront,
- })),
- uniqueKey: request.uniqueKey,
- forefront,
- } satisfies RequestQueueOperationInfo;
- this._cacheRequest(getRequestId(request.uniqueKey), queueOperationInfo);
-
- return queueOperationInfo;
- }
-
- protected abstract ensureHeadIsNonEmpty(): Promise<void>;
-
- /**
- * Resolves to `true` if the next call to {@apilink RequestQueue.fetchNextRequest}
- * would return `null`, otherwise it resolves to `false`.
- * Note that even if the queue is empty, there might be some pending requests currently being processed.
- * If you need to ensure that there is no activity in the queue, use {@apilink RequestQueue.isFinished}.
- */
- async isEmpty(): Promise<boolean> {
- await this.ensureHeadIsNonEmpty();
- return this.queueHeadIds.length() === 0;
- }
-
- /**
- * Resolves to `true` if all requests were already handled and there are no more left.
- * Due to the nature of distributed storage used by the queue,
- * the function may occasionally return a false negative,
- * but it shall never return a false positive.
- */
- abstract isFinished(): Promise<boolean>;
-
- protected _reset() {
- this.lastActivity = new Date();
- this.queueHeadIds.clear();
- this.recentlyHandledRequestsCache.clear();
- this.assumedTotalCount = 0;
- this.assumedHandledCount = 0;
- this.requestCache.clear();
- this.requestSeenCache.clear();
- }
-
- /**
- * Caches information about request to beware of unneeded addRequest() calls.
- */
- protected _cacheRequest(cacheKey: string, queueOperationInfo: RequestQueueOperationInfo): void {
- // Remove the previous entry, as otherwise our cache will never update 👀
- this.requestCache.remove(cacheKey);
-
- this.requestCache.add(cacheKey, {
- id: queueOperationInfo.requestId,
- isHandled: queueOperationInfo.wasAlreadyHandled,
- uniqueKey: queueOperationInfo.uniqueKey,
- hydrated: null,
- lockExpiresAt: null,
- forefront: queueOperationInfo.forefront,
- });
- }
-
- /**
- * Adds a request straight to the queueHeadDict, to improve performance.
- */
- protected _maybeAddRequestToQueueHead(requestId: string, forefront: boolean): void {
- if (forefront) {
- this.queueHeadIds.add(requestId, requestId, true);
- } else if (this.assumedTotalCount < QUERY_HEAD_MIN_LENGTH) {
- this.queueHeadIds.add(requestId, requestId, false);
- }
- }
-
- /**
- * Removes the queue either from the Apify Cloud storage or from the local database,
- * depending on the mode of operation.
- */
- async drop(): Promise<void> {
- checkStorageAccess();
-
- await this.client.drop();
- serviceLocator.getStorageInstanceManager().removeFromCache(this);
- }
-
- /**
- * Remove all requests from the queue but keep the queue itself, resetting it
- * so it can be reused (e.g. across multiple `crawler.run()` calls).
- */
- async purge(): Promise<void> {
- checkStorageAccess();
-
- await this.client.purge();
-
- // Reset in-memory bookkeeping so the queue behaves as if freshly opened.
- this.assumedTotalCount = 0;
- this.assumedHandledCount = 0;
- this.queueHeadIds.clear();
- this.requestCache.clear();
- this.recentlyHandledRequestsCache.clear();
- this.lastActivity = new Date();
- this.isFinishedCalledWhileHeadWasNotEmpty = 0;
- this.inProgressRequestBatchCount = 0;
- }
-
- /**
- * @inheritdoc
- */
- async *[Symbol.asyncIterator]() {
- while (true) {
- const req = await this.fetchNextRequest();
- if (!req) break;
- yield req;
- }
- }
-
- /**
- * Returns the number of handled requests.
- *
- * This function is just a convenient shortcut for:
- *
- * ```javascript
- * const { handledRequestCount } = await queue.getInfo();
- * ```
- * @inheritdoc
- */
- async getHandledCount(): Promise<number> {
- // NOTE: We keep this function for compatibility with RequestList.getHandledCount()
- const { handledRequestCount } = await this.getInfo();
- return handledRequestCount;
- }
-
- /**
- * Returns an object containing general information about the request queue.
- *
- * **Example:**
- * ```
- * {
- * id: "WkzbQMuFYuamGv3YF",
- * name: "my-queue",
- * createdAt: new Date("2015-12-12T07:34:14.202Z"),
- * modifiedAt: new Date("2015-12-13T08:36:13.202Z"),
- * accessedAt: new Date("2015-12-14T08:36:13.202Z"),
- * totalRequestCount: 25,
- * handledRequestCount: 5,
- * pendingRequestCount: 20,
- * }
- * ```
- *
- * @throws If the underlying storage no longer exists (e.g. it was deleted externally).
- */
- async getInfo(): Promise<RequestQueueInfo> {
- checkStorageAccess();
-
- return this.client.getMetadata();
- }
-
- /**
- * Fetches URLs from requestsFromUrl and returns them in format of list of requests
- */
- protected async _fetchRequestsFromUrl(source: InternalSource): Promise<RequestOptions[]> {
- const { requestsFromUrl, regex, ...sharedOpts } = source;
-
- // Download remote resource and parse URLs.
- let urlsArr;
- try {
- urlsArr = await this._downloadListOfUrls({
- url: requestsFromUrl,
- urlRegExp: regex,
- proxyUrl: await this.proxyConfiguration?.newUrl(),
- });
- } catch (err) {
- throw new Error(`Cannot fetch a request list from ${requestsFromUrl}: ${err}`);
- }
-
- // Skip if resource contained no URLs.
- if (!urlsArr.length) {
- this.log.warning('The fetched list contains no valid URLs.', { requestsFromUrl, regex });
- return [];
- }
-
- return urlsArr.map((url) => ({ url, ...sharedOpts }));
- }
-
- /**
- * Adds all fetched requests from a URL from a remote resource.
- */
- protected async _addFetchedRequests(
- source: InternalSource,
- fetchedRequests: RequestOptions[],
- options: RequestQueueOperationOptions,
- ) {
- const { requestsFromUrl, regex } = source;
- const { addedRequests } = await this.addRequestsBatched(fetchedRequests, options);
-
- this.log.info('Fetched and loaded Requests from a remote resource.', {
- requestsFromUrl,
- regex,
- fetchedCount: fetchedRequests.length,
- importedCount: addedRequests.length,
- duplicateCount: fetchedRequests.length - addedRequests.length,
- sample: JSON.stringify(fetchedRequests.slice(0, 5)),
- });
-
- return addedRequests;
- }
-
- /**
- * @internal wraps public utility for mocking purposes
- */
- private async _downloadListOfUrls(options: {
- url: string;
- urlRegExp?: RegExp;
- proxyUrl?: string;
- }): Promise<string[]> {
- return downloadListOfUrls({
- ...options,
- httpClient: this.httpClient,
- });
- }
-
- /**
- * Opens a request queue and returns a promise resolving to an instance
- * of the {@apilink RequestQueue} class.
- *
- * {@apilink RequestQueue} represents a queue of URLs to crawl, which is stored either on local filesystem or in the cloud.
- * The queue is used for deep crawling of websites, where you start with several URLs and then
- * recursively follow links to other pages. The data structure supports both breadth-first
- * and depth-first crawling orders.
- *
- * For more details and code examples, see the {@apilink RequestQueue} class.
- *
- * @param [identifier]
- * ID or name of the request queue to be opened. If a string is provided, it will first be
- * looked up as an ID; if no such storage exists, it will be treated as a name.
- * If `null` or `undefined`, the function returns the default request queue associated with the crawler run.
- * @param [options] Open Request Queue options.
- */
- static async open(
- identifier?: string | StorageIdentifier | null,
- options: StorageOpenOptions = {},
- ): Promise<RequestProvider> {
- checkStorageAccess();
-
- ow(
- options,
- ow.object.exactShape({
- config: ow.optional.object.instanceOf(Configuration),
- storageClient: ow.optional.object,
- proxyConfiguration: ow.optional.object,
- httpClient: ow.optional.object,
- }),
- );
-
- const client = options.storageClient ?? serviceLocator.getStorageClient();
- const config = options.config ?? serviceLocator.getConfiguration();
-
- await purgeDefaultStorages({ onlyPurgeOnce: true, client, config });
-
- const resolved = await resolveStorageIdentifier(identifier, client, 'RequestQueue');
-
- const queue = await serviceLocator
- .getStorageInstanceManager()
- .openStorage<RequestProvider>(this as typeof BuiltRequestProvider, {
- ...resolved,
- clientOpener: () => client.createRequestQueueClient(resolved),
- clientCacheKey: client.getStorageClientCacheKey?.() ?? client.constructor.name,
- });
- queue.proxyConfiguration = options.proxyConfiguration;
- queue.httpClient = options.httpClient;
-
- if (!queue.isInitialized) {
- // Re-create the request queue client with clientKey and timeoutSecs so that
- // request locking works correctly for API-backed implementations.
- // TODO: clientKey/timeoutSecs are Apify-platform concerns and should eventually be pushed
- // down into the Apify SDK's client implementation, aligning with crawlee-python's approach
- // where locking is handled internally by the client (see crawlee-python PR #1194).
- queue.client = await client.createRequestQueueClient({
- id: queue.id,
- clientKey: queue.clientKey,
- timeoutSecs: queue.timeoutSecs,
- });
-
- queue.isInitialized = true;
- }
-
- return queue;
- }
-}
-
-declare class BuiltRequestProvider extends RequestProvider {
- override fetchNextRequest<T extends Dictionary = Dictionary>(
- options?: RequestOptions<Dictionary>,
- ): Promise<Request<T> | null>;
-
- protected override ensureHeadIsNonEmpty(): Promise<void>;
-
- override isFinished(): Promise<boolean>;
-}
-
-interface RequestLruItem {
- uniqueKey: string;
- isHandled: boolean;
- id: string;
- hydrated: Request | null;
- lockExpiresAt: number | null;
- forefront: boolean;
-}
-
-export interface RequestProviderOptions {
- id: string;
- name?: string;
- client: RequestQueueClient;
-
- /**
- * Used to pass the proxy configuration for the `requestsFromUrl` objects.
- * Takes advantage of the internal address rotation and authentication process.
- * If undefined, the `requestsFromUrl` requests will be made without proxy.
- */
- proxyConfiguration?: ProxyConfiguration;
-}
-
-/**
- * @deprecated Use {@apilink RequestProviderOptions} instead.
- */
-export interface RequestQueueOptions extends RequestProviderOptions {}
-
-/**
- * @internal
- */
-export interface InternalRequestProviderOptions extends RequestProviderOptions {
- logPrefix: string;
- requestCacheMaxSize: number;
- recentlyHandledRequestsMaxSize: number;
-}
-
-export interface RequestQueueOperationOptions {
- /**
- * If set to `true`:
- * - while adding the request to the queue: the request will be added to the foremost position in the queue.
- * - while reclaiming the request: the request will be placed to the beginning of the queue, so that it's returned
- * in the next call to {@apilink RequestQueue.fetchNextRequest}.
- * By default, it's put to the end of the queue.
- *
- * In case the request is already present in the queue, this option has no effect.
- *
- * If more requests are added with this option at once, their order in the following `fetchNextRequest` call
- * is arbitrary.
- * @default false
- */
- forefront?: boolean;
- /**
- * Should the requests be added to the local LRU cache?
- * @default false
- * @internal
- */
- cache?: boolean;
-}
-
-/**
- * @internal
- */
-export interface RequestQueueOperationInfo extends QueueOperationInfo {
- uniqueKey: string;
- forefront: boolean;
-}
-
-export interface AddRequestsBatchedOptions extends RequestQueueOperationOptions {
- /**
- * Whether to wait for all the provided requests to be added, instead of waiting just for the initial batch of up to `batchSize`.
- * @default false
- */
- waitForAllRequestsToBeAdded?: boolean;
-
- /**
- * @default 1000
- */
- batchSize?: number;
-
- /**
- * @default 1000
- */
- waitBetweenBatchesMillis?: number;
-
- /**
- * If set, only this many *actually new* requests (i.e. not already present in the queue) will be added.
- * Once the budget is reached, remaining requests from the iterable will be collected in
- * {@apilink AddRequestsBatchedResult.requestsOverLimit|`requestsOverLimit`} instead.
- *
- * This is useful in combination with `maxRequestsPerCrawl` to avoid duplicate URLs consuming the budget.
- *
- * **Note:** Setting this option implicitly enables {@apilink AddRequestsBatchedOptions.waitForAllRequestsToBeAdded|`waitForAllRequestsToBeAdded`},
- * since all batches must complete before leftover requests can be accurately reported.
- */
- maxNewRequests?: number;
-}
-
-export interface AddRequestsBatchedResult {
- addedRequests: ProcessedRequest[];
- /**
- * A promise which will resolve with the rest of the requests that were added to the queue.
- *
- * Alternatively, we can set {@apilink AddRequestsBatchedOptions.waitForAllRequestsToBeAdded|`waitForAllRequestsToBeAdded`} to `true`
- * in the {@apilink BasicCrawler.addRequests|`crawler.addRequests()`} options.
- *
- * **Example:**
- *
- * ```ts
- * // Assuming `requests` is a list of requests.
- * const result = await crawler.addRequests(requests);
- *
- * // If we want to wait for the rest of the requests to be added to the queue:
- * await result.waitForAllRequestsToBeAdded;
- * ```
- */
- waitForAllRequestsToBeAdded: Promise<ProcessedRequest[]>;
-
- /**
- * Requests from the input that were not added to the queue because the
- * {@apilink AddRequestsBatchedOptions.maxNewRequests|`maxNewRequests`} budget was reached.
- * Empty when `maxNewRequests` is not set.
- */
- requestsOverLimit?: Source[];
-}
diff --git a/packages/core/src/storages/request_queue.ts b/packages/core/src/storages/request_queue.ts
index 989301e35..783fd5189 100644
--- a/packages/core/src/storages/request_queue.ts
+++ b/packages/core/src/storages/request_queue.ts
@@ -1,32 +1,56 @@
-import { setTimeout as sleep } from 'node:timers/promises';
+import { inspect } from 'node:util';
-import type { Dictionary } from '@crawlee/types';
+import type {
+ BaseHttpClient,
+ BatchAddRequestsResult,
+ Dictionary,
+ ProcessedRequest,
+ QueueOperationInfo,
+ RequestQueueClient,
+ RequestQueueInfo,
+} from '@crawlee/types';
+import {
+ chunkedAsyncIterable,
+ downloadListOfUrls,
+ getObjectType,
+ isAsyncIterable,
+ isIterable,
+ peekableAsyncIterable,
+ sleep,
+} from '@crawlee/utils';
+import ow from 'ow';
+import type { ReadonlyDeep } from 'type-fest';
-import { REQUEST_QUEUE_HEAD_MAX_LIMIT } from '@apify/consts';
+import { LruCache } from '@apify/datastructures';
+import { cryptoRandomObjectId } from '@apify/utilities';
-import type { Configuration } from '../configuration.js';
-import type { Request } from '../request.js';
+import { Configuration } from '../configuration.js';
+import type { Constructor } from '../typedefs.js';
+import type { EventManager } from '../events/event_manager.js';
+import { EventType } from '../events/event_manager.js';
+import type { CrawleeLogger } from '../log.js';
+import type { ProxyConfiguration } from '../proxy_configuration.js';
+import type { InternalSource, RequestOptions, Source } from '../request.js';
+import { Request } from '../request.js';
import { serviceLocator } from '../service_locator.js';
import { checkStorageAccess } from './access_checking.js';
-import type { RequestProviderOptions, RequestQueueOperationInfo } from './request_provider.js';
-import { RequestProvider } from './request_provider.js';
-import {
- API_PROCESSED_REQUESTS_DELAY_MILLIS,
- getRequestId,
- MAX_QUERIES_FOR_CONSISTENCY,
- QUERY_HEAD_BUFFER,
- QUERY_HEAD_MIN_LENGTH,
- STORAGE_CONSISTENCY_DELAY_MILLIS,
-} from './utils.js';
+import type { IRequestManager, RequestsLike } from './request_manager.js';
+import type { IStorage, StorageIdentifier } from './storage_instance_manager.js';
+import type { StorageOpenOptions } from './utils.js';
+import { resolveStorageIdentifier } from './storage_instance_manager.js';
+import { getRequestId, purgeDefaultStorages } from './utils.js';
-const MAX_CACHED_REQUESTS = 1_000_000;
+/**
+ * The maximum number of requests cached locally to avoid redundant calls to the storage client.
+ * @internal
+ */
+const MAX_CACHED_REQUESTS = 2_000_000;
/**
- * This number must be large enough so that processing of all these requests cannot be done in
- * a time lower than expected maximum latency of DynamoDB, but low enough not to waste too much memory.
+ * The maximum number of consecutive no-progress retries for unprocessed requests in `addRequestsBatched()`.
* @internal
*/
-const RECENTLY_HANDLED_CACHE_SIZE = 1000;
+const MAX_UNPROCESSED_REQUESTS_RETRIES = 3;
/**
* Represents a queue of URLs to crawl, which is used for deep crawling of websites
@@ -46,18 +70,6 @@ const RECENTLY_HANDLED_CACHE_SIZE = 1000;
* Unlike {@apilink RequestList}, `RequestQueue` supports dynamic adding and removing of requests.
* On the other hand, the queue is not optimized for operations that add or remove a large number of URLs in a batch.
*
- * `RequestQueue` stores its data either on local disk or in the Apify Cloud,
- * depending on whether the `APIFY_LOCAL_STORAGE_DIR` or `APIFY_TOKEN` environment variable is set.
- *
- * If the `APIFY_LOCAL_STORAGE_DIR` environment variable is set, the queue data is stored in
- * that directory in an SQLite database file.
- *
- * If the `APIFY_TOKEN` environment variable is set but `APIFY_LOCAL_STORAGE_DIR` is not, the data is stored in the
- * [Apify Request Queue](https://docs.apify.com/storage/request-queue)
- * cloud storage. Note that you can force usage of the cloud storage also by passing the `forceCloud`
- * option to {@apilink RequestQueue.open} function,
- * even if the `APIFY_LOCAL_STORAGE_DIR` variable is set.
- *
* **Example usage:**
*
* ```javascript
@@ -74,44 +86,491 @@ const RECENTLY_HANDLED_CACHE_SIZE = 1000;
* ```
* @category Sources
*/
-class RequestQueue extends RequestProvider {
- private queryQueueHeadPromise?: Promise<{
- wasLimitReached: boolean;
- prevLimit: number;
- queueModifiedAt: Date;
- queryStartedAt: Date;
- hadMultipleClients?: boolean;
- }> | null = null;
+export class RequestQueue implements IStorage, IRequestManager {
+ id: string;
+ name?: string;
+ timeoutSecs = 30;
+ clientKey = cryptoRandomObjectId();
+ client: RequestQueueClient;
+ protected proxyConfiguration?: ProxyConfiguration;
+
+ log: CrawleeLogger;
+
+ private isInitialized = false;
- private inProgress = new Set<string>();
+ protected requestCache: LruCache<RequestLruItem>;
+
+ protected queuePausedForMigration = false;
+
+ protected inProgressRequestBatchCount = 0;
+
+ /**
+ * The largest expected request-processing time (in seconds) seen so far via
+ * {@link setExpectedRequestProcessingTimeSecs}. Used to ensure that value is only ever raised, never
+ * lowered, before being forwarded to the storage client.
+ */
+ protected expectedRequestProcessingSecs = 0;
+
+ protected httpClient?: BaseHttpClient;
+
+ protected readonly events: EventManager;
/**
* @internal
*/
- constructor(options: RequestProviderOptions, config: Configuration = serviceLocator.getConfiguration()) {
- super(
- {
- ...options,
- logPrefix: 'RequestQueue',
- recentlyHandledRequestsMaxSize: RECENTLY_HANDLED_CACHE_SIZE,
- requestCacheMaxSize: MAX_CACHED_REQUESTS,
- },
- config,
+ constructor(
+ options: RequestQueueOptions,
+ protected readonly config: Configuration = Configuration.getGlobalConfig(),
+ ) {
+ this.id = options.id;
+ this.name = options.name;
+ this.events = serviceLocator.getEventManager();
+ this.client = options.client;
+
+ this.proxyConfiguration = options.proxyConfiguration;
+
+ this.requestCache = new LruCache({ maxLength: MAX_CACHED_REQUESTS });
+ this.log = serviceLocator.getLogger().child({ prefix: `RequestQueue(${this.id}, ${this.name ?? 'no-name'})` });
+
+ this.events.on(EventType.MIGRATING, async () => {
+ this.queuePausedForMigration = true;
+ });
+ }
+
+ /**
+ * Returns the total number of requests in the queue (i.e. pending + handled).
+ *
+ * Survives restarts and actor migrations.
+ */
+ async getTotalCount() {
+ const { totalRequestCount } = await this.getInfo();
+ return totalRequestCount;
+ }
+
+ /**
+ * Returns the total number of pending requests in the queue.
+ *
+ * Survives restarts and Actor migrations.
+ */
+ async getPendingCount() {
+ const { totalRequestCount, handledRequestCount } = await this.getInfo();
+ return totalRequestCount - handledRequestCount;
+ }
+
+ /**
+ * Adds a request to the queue.
+ *
+ * If a request with the same `uniqueKey` property is already present in the queue,
+ * it will not be updated. You can find out whether this happened from the resulting
+ * {@apilink QueueOperationInfo} object.
+ *
+ * To add multiple requests to the queue by extracting links from a webpage,
+ * see the {@apilink enqueueLinks} helper function.
+ *
+ * @param requestLike {@apilink Request} object or vanilla object with request data.
+ * Note that the function sets the `uniqueKey` and `id` fields to the passed Request.
+ * @param [options] Request queue operation options.
+ */
+ async addRequest(
+ requestLike: Source,
+ options: RequestQueueOperationOptions = {},
+ ): Promise<RequestQueueOperationInfo> {
+ checkStorageAccess();
+
+ ow(requestLike, ow.object);
+ ow(
+ options,
+ ow.object.exactShape({
+ forefront: ow.optional.boolean,
+ }),
+ );
+
+ const { forefront = false } = options;
+
+ if ('requestsFromUrl' in requestLike) {
+ const requests = await this._fetchRequestsFromUrl(requestLike as InternalSource);
+ const processedRequests = await this._addFetchedRequests(requestLike as InternalSource, requests, options);
+
+ return { ...processedRequests[0], forefront };
+ }
+
+ ow(
+ requestLike,
+ ow.object.partialShape({
+ url: ow.string,
+ id: ow.undefined,
+ }),
);
+
+ const request = requestLike instanceof Request ? requestLike : new Request(requestLike);
+
+ const cacheKey = getRequestId(request.uniqueKey);
+ const cachedInfo = this.requestCache.get(cacheKey);
+
+ if (cachedInfo) {
+ request.id = cachedInfo.id;
+ return {
+ wasAlreadyPresent: true,
+ // We may assume that if request is in local cache then also the information if the
+ // request was already handled is there because just one client should be using one queue.
+ wasAlreadyHandled: cachedInfo.isHandled,
+ requestId: cachedInfo.id,
+ uniqueKey: cachedInfo.uniqueKey,
+ forefront,
+ };
+ }
+
+ const { processedRequests } = await this.client.addBatchOfRequests([request], { forefront });
+ const queueOperationInfo = {
+ ...processedRequests[0],
+ uniqueKey: request.uniqueKey,
+ forefront,
+ } satisfies RequestQueueOperationInfo;
+
+ this._cacheRequest(cacheKey, queueOperationInfo);
+
+ return queueOperationInfo;
}
/**
- * @internal
+ * Adds requests to the queue in batches of 25. This method will wait till all the requests are added
+ * to the queue before resolving. You should prefer using `queue.addRequestsBatched()` or `crawler.addRequests()`
+ * if you don't want to block the processing, as those methods will only wait for the initial 1000 requests,
+ * start processing right after that happens, and continue adding more in the background.
+ *
+ * If a request passed in is already present due to its `uniqueKey` property being the same,
+ * it will not be updated. You can find out whether this happened by finding the request in the resulting
+ * {@apilink BatchAddRequestsResult} object.
+ *
+ * @param requestsLike {@apilink Request} objects or vanilla objects with request data.
+ * Note that the function sets the `uniqueKey` and `id` fields to the passed requests if missing.
+ * @param [options] Request queue operation options.
+ */
+ async addRequests(
+ requestsLike: RequestsLike,
+ options: RequestQueueOperationOptions = {},
+ ): Promise<BatchAddRequestsResult> {
+ checkStorageAccess();
+
+ ow(
+ requestsLike,
+ ow.object
+ .is((value: unknown) => isIterable(value) || isAsyncIterable(value))
+ .message((value) => `Expected an iterable or async iterable, got ${getObjectType(value)}`),
+ );
+ ow(
+ options,
+ ow.object.exactShape({
+ forefront: ow.optional.boolean,
+ cache: ow.optional.boolean,
+ }),
+ );
+
+ const { forefront = false, cache = true } = options;
+
+ const uniqueKeyToCacheKey = new Map<string, string>();
+ const getCachedRequestId = (uniqueKey: string) => {
+ const cached = uniqueKeyToCacheKey.get(uniqueKey);
+
+ if (cached) return cached;
+
+ const newCacheKey = getRequestId(uniqueKey);
+ uniqueKeyToCacheKey.set(uniqueKey, newCacheKey);
+
+ return newCacheKey;
+ };
+
+ const results: BatchAddRequestsResult = {
+ processedRequests: [],
+ unprocessedRequests: [],
+ };
+
+ const requests: Request<Dictionary>[] = [];
+
+ for await (const requestLike of requestsLike) {
+ if (typeof requestLike === 'string') {
+ requests.push(new Request({ url: requestLike }));
+ } else if ('requestsFromUrl' in requestLike) {
+ const fetchedRequests = await this._fetchRequestsFromUrl(requestLike as InternalSource);
+ await this._addFetchedRequests(requestLike as InternalSource, fetchedRequests, options);
+ } else {
+ requests.push(
+ requestLike instanceof Request ? requestLike : new Request(requestLike as RequestOptions),
+ );
+ }
+ }
+
+ const requestsToAdd = new Map<string, Request>();
+
+ for (const request of requests) {
+ const cacheKey = getCachedRequestId(request.uniqueKey);
+ const cachedInfo = this.requestCache.get(cacheKey);
+
+ if (cachedInfo) {
+ request.id = cachedInfo.id;
+ results.processedRequests.push({
+ wasAlreadyPresent: true,
+ // We may assume that if request is in local cache then also the information if the
+ // request was already handled is there because just one client should be using one queue.
+ wasAlreadyHandled: cachedInfo.isHandled,
+ requestId: cachedInfo.id,
+ uniqueKey: cachedInfo.uniqueKey,
+ });
+ } else if (!requestsToAdd.has(request.uniqueKey)) {
+ requestsToAdd.set(request.uniqueKey, request);
+ }
+ }
+
+ // Early exit if all provided requests were already added
+ if (!requestsToAdd.size) {
+ return results;
+ }
+
+ const apiResults = await this.client.addBatchOfRequests([...requestsToAdd.values()], { forefront });
+
+ // Report unprocessed requests
+ results.unprocessedRequests = apiResults.unprocessedRequests;
+
+ // Add all new requests to the requestCache
+ for (const newRequest of apiResults.processedRequests) {
+ // Add the new request to the processed list
+ results.processedRequests.push(newRequest);
+
+ const cacheKey = getCachedRequestId(newRequest.uniqueKey);
+
+ if (cache) {
+ this._cacheRequest(cacheKey, { ...newRequest, forefront });
+ }
+ }
+
+ return results;
+ }
+
+ /**
+ * Adds requests to the queue in batches. By default, it will resolve after the initial batch is added, and continue
+ * adding the rest in the background. You can configure the batch size via `batchSize` option and the sleep time in between
+ * the batches via `waitBetweenBatchesMillis`. If you want to wait for all batches to be added to the queue, you can use
+ * the `waitForAllRequestsToBeAdded` promise you get in the response object.
+ *
+ * @param requests The requests to add
+ * @param options Options for the request queue
+ */
+ async addRequestsBatched(
+ requests: ReadonlyDeep<RequestsLike>,
+ options: AddRequestsBatchedOptions = {},
+ ): Promise<AddRequestsBatchedResult> {
+ checkStorageAccess();
+
+ ow(
+ requests,
+ ow.object
+ .is((value: unknown) => isIterable(value) || isAsyncIterable(value))
+ .message((value) => `Expected an iterable or async iterable, got ${getObjectType(value)}`),
+ );
+
+ ow(
+ options,
+ ow.object.exactShape({
+ forefront: ow.optional.boolean,
+ waitForAllRequestsToBeAdded: ow.optional.boolean,
+ batchSize: ow.optional.number,
+ waitBetweenBatchesMillis: ow.optional.number,
+ maxNewRequests: ow.optional.number,
+ }),
+ );
+
+ const addRequest = this.addRequest.bind(this);
+
+ async function* generateRequests() {
+ for await (const opts of requests) {
+ // Validate the input
+ if (typeof opts === 'object' && opts !== null) {
+ if (opts.url !== undefined && typeof opts.url !== 'string') {
+ throw new Error(
+ `Request options are not valid, the 'url' property is not a string. Input: ${inspect(opts)}`,
+ );
+ }
+
+ if (opts.id !== undefined) {
+ throw new Error(
+ `Request options are not valid, the 'id' property must not be present. Input: ${inspect(opts)}`,
+ );
+ }
+
+ if (
+ (opts as any).requestsFromUrl !== undefined &&
+ typeof (opts as any).requestsFromUrl !== 'string'
+ ) {
+ throw new Error(
+ `Request options are not valid, the 'requestsFromUrl' property is not a string. Input: ${inspect(opts)}`,
+ );
+ }
+ }
+
+ if (opts && typeof opts === 'object' && 'requestsFromUrl' in opts) {
+ // Handle URL lists right away
+ await addRequest(opts, { forefront: options.forefront });
+ } else {
+ // Yield valid requests
+ yield typeof opts === 'string' ? { url: opts } : (opts as RequestOptions);
+ }
+ }
+ }
+
+ const { batchSize = 1000, waitBetweenBatchesMillis = 1000, maxNewRequests = undefined } = options;
+
+ let remainingBudget = maxNewRequests ?? Infinity;
+ const requestsOverLimit: Source[] = [];
+
+ // If there's a limit on the number of added requests, do not send batches bigger than the limit
+ const effectiveChunkSize =
+ maxNewRequests !== undefined ? () => Math.min(batchSize, remainingBudget) : batchSize;
+
+ // Hold onto the underlying iterator so we can drain leftovers from it in buildResult
+ const requestIterator = generateRequests();
+
+ const chunks = peekableAsyncIterable(
+ chunkedAsyncIterable(requestIterator, effectiveChunkSize) as AsyncIterable<Source[]>,
+ );
+ const chunksIterator = chunks[Symbol.asyncIterator]();
+
+ const attemptToAddToQueueAndAddAnyUnprocessed = async (
+ providedRequests: Source[],
+ cache = true,
+ unsuccessfulAttempts = 0,
+ ) => {
+ const resultsToReturn: ProcessedRequest[] = [];
+ const apiResult = await this.addRequests(providedRequests, { forefront: options.forefront, cache });
+ resultsToReturn.push(...apiResult.processedRequests);
+
+ if (apiResult.unprocessedRequests.length) {
+ // Count attempts that make no progress, so permanently rejected requests (e.g. a malformed
+ // `userData` shape causing a 400) don't loop forever. Any progress resets the counter.
+ const attempts = apiResult.processedRequests.length ? 0 : unsuccessfulAttempts + 1;
+
+ if (attempts >= MAX_UNPROCESSED_REQUESTS_RETRIES) {
+ this.log.warning(
+ `Some requests were consistently rejected by the request queue and will be skipped after ${MAX_UNPROCESSED_REQUESTS_RETRIES} attempts. This usually means the request data is malformed (e.g. an invalid 'userData' shape).`,
+ { unprocessedRequests: apiResult.unprocessedRequests },
+ );
+
+ return resultsToReturn;
+ }
+
+ await sleep(waitBetweenBatchesMillis);
+
+ resultsToReturn.push(
+ ...(await attemptToAddToQueueAndAddAnyUnprocessed(
+ providedRequests.filter(
+ (r) => !apiResult.processedRequests.some((pr) => pr.uniqueKey === r.uniqueKey),
+ ),
+ false,
+ attempts,
+ )),
+ );
+ }
+
+ return resultsToReturn;
+ };
+
+ /**
+ * Process a chunk: send it to the queue, then update the remaining budget if maxNewRequests is active.
+ */
+ const processChunk = async (chunk: Source[], cache = true) => {
+ const results = await attemptToAddToQueueAndAddAnyUnprocessed(chunk, cache);
+
+ if (maxNewRequests !== undefined) {
+ remainingBudget -= results.filter((r) => !r.wasAlreadyPresent).length;
+ }
+
+ return results;
+ };
+
+ /**
+ * Build the final result. When maxNewRequests is set, drains any remaining items
+ * from the underlying request iterator into requestsOverLimit.
+ *
+ * We accept the iterator explicitly (rather than closing over it) to make it obvious
+ * that this is the *same* iterator that `chunkedAsyncIterable` has been consuming —
+ * so only unconsumed items are drained. We drain `requestIterator` (not `chunks`)
+ * because `chunkedAsyncIterable` stops yielding when the budget-based chunk size
+ * drops to 0, leaving unconsumed items in the underlying iterator.
+ */
+ const buildResult = async (
+ addedRequests: ProcessedRequest[],
+ waitForAllRequestsToBeAdded: Promise<ProcessedRequest[]>,
+ unconsumedIterator: AsyncGenerator<RequestOptions>,
+ ): Promise<AddRequestsBatchedResult> => {
+ if (maxNewRequests !== undefined) {
+ for await (const request of unconsumedIterator) {
+ requestsOverLimit.push(request);
+ }
+ }
+
+ return { addedRequests, waitForAllRequestsToBeAdded, requestsOverLimit };
+ };
+
+ // Add initial batch to process right away
+ const initialChunk = await chunksIterator.peek();
+ if (initialChunk === undefined) {
+ return buildResult([], Promise.resolve([]), requestIterator);
+ }
+
+ const addedRequests = await processChunk(initialChunk);
+ await chunksIterator.next();
+
+ // If we have no more requests to add (either exhausted or budget hit), return immediately
+ if ((await chunksIterator.peek()) === undefined) {
+ return buildResult(addedRequests, Promise.resolve([]), requestIterator);
+ }
+
+ // eslint-disable-next-line no-async-promise-executor
+ const promise = new Promise<ProcessedRequest[]>(async (resolve) => {
+ const finalAddedRequests: ProcessedRequest[] = [];
+
+ for await (const requestChunk of chunks) {
+ finalAddedRequests.push(...(await processChunk(requestChunk, false)));
+ await sleep(waitBetweenBatchesMillis);
+ }
+
+ resolve(finalAddedRequests);
+ });
+
+ this.inProgressRequestBatchCount += 1;
+ void promise.finally(() => {
+ this.inProgressRequestBatchCount -= 1;
+ });
+
+ // When maxNewRequests is set, we must wait for all batches so we can accurately report skipped requests.
+ if (options.waitForAllRequestsToBeAdded || maxNewRequests !== undefined) {
+ addedRequests.push(...(await promise));
+ }
+
+ return buildResult(addedRequests, promise, requestIterator);
+ }
+
+ /**
+ * Gets the request from the queue specified by its `uniqueKey`.
+ *
+ * @param uniqueKey Unique key of the request.
+ * @returns Returns the request object, or `null` if it was not found.
*/
- public inProgressCount(): number {
- return this.inProgress.size;
+ async getRequest<T extends Dictionary = Dictionary>(uniqueKey: string): Promise<Request<T> | null> {
+ checkStorageAccess();
+
+ ow(uniqueKey, ow.string);
+
+ const requestOptions = await this.client.getRequest(uniqueKey);
+ if (!requestOptions) return null;
+
+ return new Request(requestOptions as unknown as RequestOptions);
}
/**
* Returns a next request in the queue to be processed, or `null` if there are no more pending requests.
*
* Once you successfully finish processing of the request, you need to call
- * {@apilink RequestQueue.markRequestHandled}
+ * {@apilink RequestQueue.markRequestAsHandled}
* to mark the request as handled in the queue. If there was some error in processing the request,
* call {@apilink RequestQueue.reclaimRequest} instead,
* so that the queue will give the request to some other consumer in another call to the `fetchNextRequest` function.
@@ -124,258 +583,323 @@ class RequestQueue extends RequestProvider {
* @returns
* Returns the request object or `null` if there are no more pending requests.
*/
- override async fetchNextRequest<T extends Dictionary = Dictionary>(): Promise<Request<T> | null> {
+ async fetchNextRequest<T extends Dictionary = Dictionary>(): Promise<Request<T> | null> {
checkStorageAccess();
- this.lastActivity = new Date();
+ if (this.queuePausedForMigration) {
+ return null;
+ }
+
+ const requestOptions = await this.client.fetchNextRequest();
+ if (!requestOptions) return null;
+
+ return new Request(requestOptions as unknown as RequestOptions);
+ }
+
+ /**
+ * Marks a request that was previously returned by the
+ * {@apilink RequestQueue.fetchNextRequest}
+ * function as handled after successful processing.
+ * Handled requests will never again be returned by the `fetchNextRequest` function.
+ */
+ async markRequestAsHandled(request: Request): Promise<RequestQueueOperationInfo | null> {
+ checkStorageAccess();
- await this.ensureHeadIsNonEmpty();
+ ow(
+ request,
+ ow.object.partialShape({
+ id: ow.string,
+ uniqueKey: ow.string,
+ handledAt: ow.optional.string,
+ }),
+ );
- const nextRequestId = this.queueHeadIds.removeFirst();
+ const forefront = this.requestCache.get(getRequestId(request.uniqueKey))?.forefront ?? false;
- // We are likely done at this point.
- if (!nextRequestId) return null;
+ const handledAt = request.handledAt ?? new Date().toISOString();
+ const processedRequest = await this.client.markRequestAsHandled({
+ ...request,
+ handledAt,
+ });
- // This should never happen, but...
- if (this.inProgress.has(nextRequestId) || this.recentlyHandledRequestsCache.get(nextRequestId)) {
- this.log.warning('Queue head returned a request that is already in progress?!', {
- nextRequestId,
- inProgress: this.inProgress.has(nextRequestId),
- recentlyHandled: !!this.recentlyHandledRequestsCache.get(nextRequestId),
- });
+ // The request was not in progress (e.g. already handled) — nothing to do.
+ if (!processedRequest) {
return null;
}
- this.inProgress.add(nextRequestId);
- this.lastActivity = new Date();
+ request.handledAt = handledAt;
- let request: Request | null;
- try {
- request = await this.getRequest(nextRequestId);
- } catch (e) {
- // On error, remove the request from in progress, otherwise it would be there forever
- this.inProgress.delete(nextRequestId);
- throw e;
- }
+ const queueOperationInfo = {
+ ...processedRequest,
+ uniqueKey: request.uniqueKey,
+ forefront,
+ } satisfies RequestQueueOperationInfo;
- // NOTE: It can happen that the queue head index is inconsistent with the main queue table. This can occur in two situations:
+ this._cacheRequest(getRequestId(request.uniqueKey), queueOperationInfo);
- // 1) Queue head index is ahead of the main table and the request is not present in the main table yet (i.e. getRequest() returned null).
- // In this case, keep the request marked as in progress for a short while,
- // so that isFinished() doesn't return true and _ensureHeadIsNonEmpty() doesn't not load the request
- // into the queueHeadDict straight again. After the interval expires, fetchNextRequest()
- // will try to fetch this request again, until it eventually appears in the main table.
- if (!request) {
- this.log.debug('Cannot find a request from the beginning of queue, will be retried later', {
- nextRequestId,
- });
- setTimeout(() => {
- this.inProgress.delete(nextRequestId);
- }, STORAGE_CONSISTENCY_DELAY_MILLIS);
- return null;
- }
+ return queueOperationInfo;
+ }
+
+ /**
+ * Reclaims a failed request back to the queue, so that it can be returned for processing later again
+ * by another call to {@apilink RequestQueue.fetchNextRequest}.
+ * The request record in the queue is updated using the provided `request` parameter.
+ * For example, this lets you store the number of retries or error messages for the request.
+ */
+ async reclaimRequest(
+ request: Request,
+ options: RequestQueueOperationOptions = {},
+ ): Promise<RequestQueueOperationInfo | null> {
+ checkStorageAccess();
- // 2) Queue head index is behind the main table and the underlying request was already handled
- // (by some other client, since we keep the track of handled requests in recentlyHandled dictionary).
- // We just add the request to the recentlyHandled dictionary so that next call to _ensureHeadIsNonEmpty()
- // will not put the request again to queueHeadDict.
- if (request.handledAt) {
- this.log.debug('Request fetched from the beginning of queue was already handled', { nextRequestId });
- this.recentlyHandledRequestsCache.add(nextRequestId, true);
+ ow(
+ request,
+ ow.object.partialShape({
+ id: ow.string,
+ uniqueKey: ow.string,
+ }),
+ );
+ ow(
+ options,
+ ow.object.exactShape({
+ forefront: ow.optional.boolean,
+ }),
+ );
+
+ const { forefront = false } = options;
+
+ const processedRequest = await this.client.reclaimRequest(request, { forefront });
+
+ // The request was not in progress — nothing to reclaim.
+ if (!processedRequest) {
return null;
}
- return request;
+ const queueOperationInfo = {
+ ...processedRequest,
+ uniqueKey: request.uniqueKey,
+ forefront,
+ } satisfies RequestQueueOperationInfo;
+ this._cacheRequest(getRequestId(request.uniqueKey), queueOperationInfo);
+
+ return queueOperationInfo;
}
- protected override async ensureHeadIsNonEmpty(): Promise<void> {
- // Alias for backwards compatibility
- await this._ensureHeadIsNonEmpty();
+ /**
+ * Resolves to `true` if the next call to {@apilink RequestQueue.fetchNextRequest} would return
+ * `null`, i.e. there are no pending requests to fetch right now. Otherwise it resolves to `false`.
+ *
+ * Note that even if the queue is empty, there might be some requests currently being processed
+ * (fetched but not yet handled or reclaimed). An empty queue therefore does not mean crawling is
+ * finished — those in-progress requests may still be reclaimed, and background tasks may still be
+ * adding more requests. To check whether all activity in the queue has finished, use
+ * {@apilink RequestQueue.isFinished}.
+ */
+ async isEmpty(): Promise<boolean> {
+ checkStorageAccess();
+
+ return this.client.isEmpty();
}
/**
- * We always request more items than is in progress to ensure that something falls into head.
+ * Resolves to `true` if all requests were already handled and there are no more left — including no
+ * requests currently in progress (fetched but not yet handled or reclaimed, including requests
+ * locked by other clients sharing the same queue) and no background add operations still in flight.
*
- * @param [ensureConsistency] If true then query for queue head is retried until queueModifiedAt
- * is older than queryStartedAt by at least API_PROCESSED_REQUESTS_DELAY_MILLIS to ensure that queue
- * head is consistent.
- * @default false
- * @param [limit] How many queue head items will be fetched.
- * @param [iteration] Used when this function is called recursively to limit the recursion.
- * @returns Indicates if queue head is consistent (true) or inconsistent (false).
- */
- protected async _ensureHeadIsNonEmpty(
- ensureConsistency = false,
- limit = Math.max(this.inProgressCount() * QUERY_HEAD_BUFFER, QUERY_HEAD_MIN_LENGTH),
- iteration = 0,
- ): Promise<boolean> {
- // If we are paused for migration, resolve immediately.
- if (this.queuePausedForMigration) {
- return true;
- }
+ * Due to the nature of distributed storage used by the queue, the function may occasionally return
+ * a false negative, but it shall never return a false positive.
+ */
+ async isFinished(): Promise<boolean> {
+ checkStorageAccess();
- // If is nonempty resolve immediately.
- if (this.queueHeadIds.length() > 0) {
- return true;
+ // We are not finished if we're still adding new requests in the background.
+ if (this.inProgressRequestBatchCount > 0) {
+ return false;
}
- if (!this.queryQueueHeadPromise) {
- const queryStartedAt = new Date();
-
- this.queryQueueHeadPromise = this.client
- .listHead({ limit })
- .then(({ items, queueModifiedAt, hadMultipleClients }) => {
- items.forEach(({ id: requestId, uniqueKey }) => {
- // Queue head index might be behind the main table, so ensure we don't recycle requests
- if (
- !requestId ||
- !uniqueKey ||
- this.inProgress.has(requestId) ||
- this.recentlyHandledRequestsCache.get(requestId!)
- )
- return;
-
- this.queueHeadIds.add(requestId, requestId, false);
- const forefront = this.requestCache.get(getRequestId(uniqueKey))?.forefront ?? false;
- this._cacheRequest(getRequestId(uniqueKey), {
- requestId,
- wasAlreadyHandled: false,
- wasAlreadyPresent: true,
- uniqueKey,
- forefront,
- });
- });
-
- // This is needed so that the next call to _ensureHeadIsNonEmpty() will fetch the queue head again.
- this.queryQueueHeadPromise = null;
-
- return {
- wasLimitReached: items.length >= limit,
- prevLimit: limit,
- queueModifiedAt: new Date(queueModifiedAt),
- queryStartedAt,
- hadMultipleClients,
- };
- });
+ return this.client.isFinished();
+ }
+
+ /**
+ * Tells the queue how long a consumer expects to hold a fetched request before marking it handled
+ * or reclaiming it (typically the request-handler timeout plus padding), so that a storage client
+ * that reserves requests via locking does not hand the same request out again while it is still
+ * being processed.
+ *
+ * Several consumers may share one queue (and therefore one client) in a single process, so we only
+ * ever raise the reservation duration, never lower it — otherwise a short-lived consumer could cut
+ * short the reservation of a long-lived one and have its in-flight request stolen.
+ */
+ setExpectedRequestProcessingTimeSecs(secs: number): void {
+ if (secs <= this.expectedRequestProcessingSecs) {
+ return;
}
- const { queueModifiedAt, wasLimitReached, prevLimit, queryStartedAt, hadMultipleClients } =
- await this.queryQueueHeadPromise;
+ this.expectedRequestProcessingSecs = secs;
+ this.client.setExpectedRequestProcessingTimeSecs?.(secs);
+ }
- // TODO: I feel this code below can be greatly simplified...
+ /**
+ * Caches information about request to beware of unneeded addRequest() calls.
+ */
+ protected _cacheRequest(cacheKey: string, queueOperationInfo: RequestQueueOperationInfo): void {
+ // Remove the previous entry, as otherwise our cache will never update 👀
+ this.requestCache.remove(cacheKey);
- // If queue is still empty then one of the following holds:
- // - the other calls waiting for this promise already consumed all the returned requests
- // - the limit was too low and contained only requests in progress
- // - the writes from other clients were not propagated yet
- // - the whole queue was processed and we are done
+ this.requestCache.add(cacheKey, {
+ id: queueOperationInfo.requestId,
+ isHandled: queueOperationInfo.wasAlreadyHandled,
+ uniqueKey: queueOperationInfo.uniqueKey,
+ hydrated: null,
+ lockExpiresAt: null,
+ forefront: queueOperationInfo.forefront,
+ });
+ }
- // If limit was not reached in the call then there are no more requests to be returned.
- if (prevLimit >= REQUEST_QUEUE_HEAD_MAX_LIMIT) {
- this.log.warning(`Reached the maximum number of requests in progress: ${REQUEST_QUEUE_HEAD_MAX_LIMIT}.`);
- }
- const shouldRepeatWithHigherLimit =
- this.queueHeadIds.length() === 0 && wasLimitReached && prevLimit < REQUEST_QUEUE_HEAD_MAX_LIMIT;
-
- // If ensureConsistency=true then we must ensure that either:
- // - queueModifiedAt is older than queryStartedAt by at least API_PROCESSED_REQUESTS_DELAY_MILLIS
- // - hadMultipleClients=false and this.assumedTotalCount<=this.assumedHandledCount
- const isDatabaseConsistent = +queryStartedAt - +queueModifiedAt >= API_PROCESSED_REQUESTS_DELAY_MILLIS;
- const isLocallyConsistent = !hadMultipleClients && this.assumedTotalCount <= this.assumedHandledCount;
- // Consistent information from one source is enough to consider request queue finished.
- const shouldRepeatForConsistency = ensureConsistency && !isDatabaseConsistent && !isLocallyConsistent;
-
- // If both are false then head is consistent and we may exit.
- if (!shouldRepeatWithHigherLimit && !shouldRepeatForConsistency) return true;
-
- // If we are querying for consistency then we limit the number of queries to MAX_QUERIES_FOR_CONSISTENCY.
- // If this is reached then we return false so that empty() and finished() returns possibly false negative.
- if (!shouldRepeatWithHigherLimit && iteration > MAX_QUERIES_FOR_CONSISTENCY) return false;
-
- const nextLimit = shouldRepeatWithHigherLimit ? Math.round(prevLimit * 1.5) : prevLimit;
-
- // If we are repeating for consistency then wait required time.
- if (shouldRepeatForConsistency) {
- const delayMillis = API_PROCESSED_REQUESTS_DELAY_MILLIS - (Date.now() - +queueModifiedAt);
- this.log.info(
- `Waiting for ${delayMillis}ms before considering the queue as finished to ensure that the data is consistent.`,
- );
- await sleep(delayMillis);
- }
+ /**
+ * Removes the queue either from the Apify Cloud storage or from the local database,
+ * depending on the mode of operation.
+ */
+ async drop(): Promise<void> {
+ checkStorageAccess();
- return this._ensureHeadIsNonEmpty(ensureConsistency, nextLimit, iteration + 1);
+ await this.client.drop();
+ serviceLocator.getStorageInstanceManager().removeFromCache(this);
}
- // RequestQueue v1 behavior overrides below
- override async isFinished(): Promise<boolean> {
+ /**
+ * Remove all requests from the queue but keep the queue itself, resetting it
+ * so it can be reused (e.g. across multiple `crawler.run()` calls).
+ */
+ async purge(): Promise<void> {
checkStorageAccess();
- if (Date.now() - +this.lastActivity > this.internalTimeoutMillis) {
- const message = `The request queue seems to be stuck for ${
- this.internalTimeoutMillis / 1e3
- }s, resetting internal state.`;
- this.log.warning(message, { inProgress: [...this.inProgress] });
- this._reset();
- }
+ await this.client.purge();
- if (this.inProgressRequestBatchCount > 0) {
- return false;
- }
+ // Reset in-memory bookkeeping so the queue behaves as if freshly opened.
+ this.requestCache.clear();
+ this.inProgressRequestBatchCount = 0;
- if (this.queueHeadIds.length() > 0 || this.inProgressCount() > 0) return false;
+ // Reset the expected-processing-time high-water mark too, otherwise the monotonic-raise guard
+ // in `setExpectedRequestProcessingTimeSecs` would let a value raised in an earlier run leak into a
+ // later one and silently swallow a lower hint (the queue is meant to be reusable across runs).
+ this.expectedRequestProcessingSecs = 0;
+ }
- const isHeadConsistent = await this._ensureHeadIsNonEmpty(true);
- return isHeadConsistent && this.queueHeadIds.length() === 0 && this.inProgressCount() === 0;
+ /**
+ * @inheritdoc
+ */
+ async *[Symbol.asyncIterator]() {
+ while (true) {
+ const req = await this.fetchNextRequest();
+ if (!req) break;
+ yield req;
+ }
}
/**
- * Reclaims a failed request back to the queue, so that it can be returned for processing later again
- * by another call to {@apilink RequestQueue.fetchNextRequest}.
- * The request record in the queue is updated using the provided `request` parameter.
- * For example, this lets you store the number of retries or error messages for the request.
+ * Returns the number of handled requests.
+ *
+ * This function is just a convenient shortcut for:
+ *
+ * ```javascript
+ * const { handledRequestCount } = await queue.getInfo();
+ * ```
+ * @inheritdoc
*/
- override async reclaimRequest(...args: Parameters<RequestProvider['reclaimRequest']>) {
- checkStorageAccess();
+ async getHandledCount(): Promise<number> {
+ // NOTE: We keep this function for compatibility with RequestList.getHandledCount()
+ const { handledRequestCount } = await this.getInfo();
+ return handledRequestCount;
+ }
- const [request, options] = args;
- const forefront = options?.forefront ?? false;
+ /**
+ * Returns an object containing general information about the request queue.
+ *
+ * **Example:**
+ * ```
+ * {
+ * id: "WkzbQMuFYuamGv3YF",
+ * name: "my-queue",
+ * createdAt: new Date("2015-12-12T07:34:14.202Z"),
+ * modifiedAt: new Date("2015-12-13T08:36:13.202Z"),
+ * accessedAt: new Date("2015-12-14T08:36:13.202Z"),
+ * totalRequestCount: 25,
+ * handledRequestCount: 5,
+ * pendingRequestCount: 20,
+ * }
+ * ```
+ *
+ * @throws If the underlying storage no longer exists (e.g. it was deleted externally).
+ */
+ async getInfo(): Promise<RequestQueueInfo> {
+ checkStorageAccess();
- const result = await super.reclaimRequest(...args);
+ return this.client.getMetadata();
+ }
- // Wait a little to increase a chance that the next call to fetchNextRequest() will return the request with updated data.
- // This is to compensate for the limitation of DynamoDB, where writes might not be immediately visible to subsequent reads.
- setTimeout(() => {
- if (!this.inProgress.has(request.id!)) {
- this.log.debug('The request is no longer marked as in progress in the queue?!', {
- requestId: request.id,
- });
- return;
- }
+ /**
+ * Fetches URLs from requestsFromUrl and returns them in format of list of requests
+ */
+ protected async _fetchRequestsFromUrl(source: InternalSource): Promise<RequestOptions[]> {
+ const { requestsFromUrl, regex, ...sharedOpts } = source;
- this.inProgress.delete(request.id!);
+ // Download remote resource and parse URLs.
+ let urlsArr;
+ try {
+ urlsArr = await this._downloadListOfUrls({
+ url: requestsFromUrl,
+ urlRegExp: regex,
+ proxyUrl: await this.proxyConfiguration?.newUrl(),
+ });
+ } catch (err) {
+ throw new Error(`Cannot fetch a request list from ${requestsFromUrl}: ${err}`);
+ }
- // Performance optimization: add request straight to head if possible
- this._maybeAddRequestToQueueHead(request.id!, forefront);
- }, STORAGE_CONSISTENCY_DELAY_MILLIS);
+ // Skip if resource contained no URLs.
+ if (!urlsArr.length) {
+ this.log.warning('The fetched list contains no valid URLs.', { requestsFromUrl, regex });
+ return [];
+ }
- return result;
+ return urlsArr.map((url) => ({ url, ...sharedOpts }));
}
/**
- * @inheritdoc
+ * Adds all fetched requests from a URL from a remote resource.
*/
- override async markRequestHandled(request: Request): Promise<RequestQueueOperationInfo | null> {
- const res = await super.markRequestHandled(request);
+ protected async _addFetchedRequests(
+ source: InternalSource,
+ fetchedRequests: RequestOptions[],
+ options: RequestQueueOperationOptions,
+ ) {
+ const { requestsFromUrl, regex } = source;
+ const { addedRequests } = await this.addRequestsBatched(fetchedRequests, options);
- this.inProgress.delete(request.id!);
+ this.log.info('Fetched and loaded Requests from a remote resource.', {
+ requestsFromUrl,
+ regex,
+ fetchedCount: fetchedRequests.length,
+ importedCount: addedRequests.length,
+ duplicateCount: fetchedRequests.length - addedRequests.length,
+ sample: JSON.stringify(fetchedRequests.slice(0, 5)),
+ });
- return res;
+ return addedRequests;
}
- protected override _reset(): void {
- super._reset();
-
- this.inProgress.clear();
+ /**
+ * @internal wraps public utility for mocking purposes
+ */
+ private async _downloadListOfUrls(options: {
+ url: string;
+ urlRegExp?: RegExp;
+ proxyUrl?: string;
+ }): Promise<string[]> {
+ return downloadListOfUrls({
+ ...options,
+ httpClient: this.httpClient,
+ });
}
/**
@@ -389,14 +913,171 @@ class RequestQueue extends RequestProvider {
*
* For more details and code examples, see the {@apilink RequestQueue} class.
*
- * @param [queueIdOrName]
- * ID or name of the request queue to be opened. If `null` or `undefined`,
- * the function returns the default request queue associated with the crawler run.
+ * @param [identifier]
+ * ID or name of the request queue to be opened. If a string is provided, it will first be
+ * looked up as an ID; if no such storage exists, it will be treated as a name.
+ * If `null` or `undefined`, the function returns the default request queue associated with the crawler run.
* @param [options] Open Request Queue options.
*/
- static override async open(...args: Parameters<typeof RequestProvider.open>): Promise<RequestQueue> {
- return super.open(...args) as Promise<RequestQueue>;
+ static async open(
+ identifier?: string | StorageIdentifier | null,
+ options: StorageOpenOptions = {},
+ ): Promise<RequestQueue> {
+ checkStorageAccess();
+
+ ow(
+ options,
+ ow.object.exactShape({
+ config: ow.optional.object.instanceOf(Configuration),
+ storageClient: ow.optional.object,
+ proxyConfiguration: ow.optional.object,
+ httpClient: ow.optional.object,
+ }),
+ );
+
+ const client = options.storageClient ?? serviceLocator.getStorageClient();
+ const config = options.config ?? serviceLocator.getConfiguration();
+
+ await purgeDefaultStorages({ onlyPurgeOnce: true, client, config });
+
+ const resolved = await resolveStorageIdentifier(identifier, client, 'RequestQueue');
+
+ const queue = await serviceLocator
+ .getStorageInstanceManager()
+ .openStorage<RequestQueue>(this as unknown as Constructor<RequestQueue>, {
+ ...resolved,
+ clientOpener: () => client.createRequestQueueClient(resolved),
+ clientCacheKey: client.getStorageClientCacheKey?.() ?? client.constructor.name,
+ });
+ queue.proxyConfiguration = options.proxyConfiguration;
+ queue.httpClient = options.httpClient;
+
+ if (!queue.isInitialized) {
+ // Re-create the request queue client with clientKey and timeoutSecs so that
+ // request locking works correctly for API-backed implementations.
+ // TODO: clientKey/timeoutSecs are Apify-platform concerns and should eventually be pushed
+ // down into the Apify SDK's client implementation, aligning with crawlee-python's approach
+ // where locking is handled internally by the client (see crawlee-python PR #1194).
+ queue.client = await client.createRequestQueueClient({
+ id: queue.id,
+ clientKey: queue.clientKey,
+ timeoutSecs: queue.timeoutSecs,
+ });
+
+ queue.isInitialized = true;
+ }
+
+ return queue;
}
}
-export { RequestQueue as RequestQueueV1 };
+interface RequestLruItem {
+ uniqueKey: string;
+ isHandled: boolean;
+ id: string;
+ hydrated: Request | null;
+ lockExpiresAt: number | null;
+ forefront: boolean;
+}
+
+export interface RequestQueueOptions {
+ id: string;
+ name?: string;
+ client: RequestQueueClient;
+
+ /**
+ * Used to pass the proxy configuration for the `requestsFromUrl` objects.
+ * Takes advantage of the internal address rotation and authentication process.
+ * If undefined, the `requestsFromUrl` requests will be made without proxy.
+ */
+ proxyConfiguration?: ProxyConfiguration;
+}
+
+export interface RequestQueueOperationOptions {
+ /**
+ * If set to `true`:
+ * - while adding the request to the queue: the request will be added to the foremost position in the queue.
+ * - while reclaiming the request: the request will be placed to the beginning of the queue, so that it's returned
+ * in the next call to {@apilink RequestQueue.fetchNextRequest}.
+ * By default, it's put to the end of the queue.
+ *
+ * In case the request is already present in the queue, this option has no effect.
+ *
+ * If more requests are added with this option at once, their order in the following `fetchNextRequest` call
+ * is arbitrary.
+ * @default false
+ */
+ forefront?: boolean;
+ /**
+ * Should the requests be added to the local LRU cache?
+ * @default false
+ * @internal
+ */
+ cache?: boolean;
+}
+
+/**
+ * @internal
+ */
+export interface RequestQueueOperationInfo extends QueueOperationInfo {
+ uniqueKey: string;
+ forefront: boolean;
+}
+
+export interface AddRequestsBatchedOptions extends RequestQueueOperationOptions {
+ /**
+ * Whether to wait for all the provided requests to be added, instead of waiting just for the initial batch of up to `batchSize`.
+ * @default false
+ */
+ waitForAllRequestsToBeAdded?: boolean;
+
+ /**
+ * @default 1000
+ */
+ batchSize?: number;
+
+ /**
+ * @default 1000
+ */
+ waitBetweenBatchesMillis?: number;
+
+ /**
+ * If set, only this many *actually new* requests (i.e. not already present in the queue) will be added.
+ * Once the budget is reached, remaining requests from the iterable will be collected in
+ * {@apilink AddRequestsBatchedResult.requestsOverLimit|`requestsOverLimit`} instead.
+ *
+ * This is useful in combination with `maxRequestsPerCrawl` to avoid duplicate URLs consuming the budget.
+ *
+ * **Note:** Setting this option implicitly enables {@apilink AddRequestsBatchedOptions.waitForAllRequestsToBeAdded|`waitForAllRequestsToBeAdded`},
+ * since all batches must complete before leftover requests can be accurately reported.
+ */
+ maxNewRequests?: number;
+}
+
+export interface AddRequestsBatchedResult {
+ addedRequests: ProcessedRequest[];
+ /**
+ * A promise which will resolve with the rest of the requests that were added to the queue.
+ *
+ * Alternatively, we can set {@apilink AddRequestsBatchedOptions.waitForAllRequestsToBeAdded|`waitForAllRequestsToBeAdded`} to `true`
+ * in the {@apilink BasicCrawler.addRequests|`crawler.addRequests()`} options.
+ *
+ * **Example:**
+ *
+ * ```ts
+ * // Assuming `requests` is a list of requests.
+ * const result = await crawler.addRequests(requests);
+ *
+ * // If we want to wait for the rest of the requests to be added to the queue:
+ * await result.waitForAllRequestsToBeAdded;
+ * ```
+ */
+ waitForAllRequestsToBeAdded: Promise<ProcessedRequest[]>;
+
+ /**
+ * Requests from the input that were not added to the queue because the
+ * {@apilink AddRequestsBatchedOptions.maxNewRequests|`maxNewRequests`} budget was reached.
+ * Empty when `maxNewRequests` is not set.
+ */
+ requestsOverLimit?: Source[];
+}
diff --git a/packages/core/src/storages/request_queue_v2.ts b/packages/core/src/storages/request_queue_v2.ts
deleted file mode 100644
index a37a9587c..000000000
--- a/packages/core/src/storages/request_queue_v2.ts
+++ /dev/null
@@ -1,557 +0,0 @@
-import type { BatchAddRequestsResult, Dictionary } from '@crawlee/types';
-
-import type { Configuration } from '../configuration.js';
-import { EventType } from '../events/event_manager.js';
-import type { Request, Source } from '../request.js';
-import { serviceLocator } from '../service_locator.js';
-import { checkStorageAccess } from './access_checking.js';
-import type { RequestsLike } from './request_manager.js';
-import type {
- RequestProviderOptions,
- RequestQueueOperationInfo,
- RequestQueueOperationOptions,
-} from './request_provider.js';
-import { RequestProvider } from './request_provider.js';
-import { getRequestId } from './utils.js';
-
-// Double the limit of RequestQueue v1 (1_000_000) as we also store keyed by request.id, not just from uniqueKey
-const MAX_CACHED_REQUESTS = 2_000_000;
-
-/**
- * This number must be large enough so that processing of all these requests cannot be done in
- * a time lower than expected maximum latency of DynamoDB, but low enough not to waste too much memory.
- * @internal
- */
-const RECENTLY_HANDLED_CACHE_SIZE = 1000;
-
-const LIST_AND_LOCK_HEAD_LIMIT = 25;
-
-const QUEUE_HEAD_REFILL_THRESHOLD = 1;
-
-/**
- * Represents a queue of URLs to crawl, which is used for deep crawling of websites
- * where you start with several URLs and then recursively
- * follow links to other pages. The data structure supports both breadth-first and depth-first crawling orders.
- *
- * Each URL is represented using an instance of the {@apilink Request} class.
- * The queue can only contain unique URLs. More precisely, it can only contain {@apilink Request} instances
- * with distinct `uniqueKey` properties. By default, `uniqueKey` is generated from the URL, but it can also be overridden.
- * To add a single URL multiple times to the queue,
- * corresponding {@apilink Request} objects will need to have different `uniqueKey` properties.
- *
- * Do not instantiate this class directly, use the {@apilink RequestQueue.open} function instead.
- *
- * `RequestQueue` is used by {@apilink BasicCrawler}, {@apilink CheerioCrawler}, {@apilink PuppeteerCrawler}
- * and {@apilink PlaywrightCrawler} as a source of URLs to crawl.
- * Unlike {@apilink RequestList}, `RequestQueue` supports dynamic adding and removing of requests.
- * On the other hand, the queue is not optimized for operations that add or remove a large number of URLs in a batch.
- *
- * **Example usage:**
- *
- * ```javascript
- * // Open the default request queue associated with the crawler run
- * const queue = await RequestQueue.open();
- *
- * // Open a named request queue
- * const queueWithName = await RequestQueue.open('some-name');
- *
- * // Enqueue few requests
- * await queue.addRequest({ url: 'http://example.com/aaa' });
- * await queue.addRequest({ url: 'http://example.com/bbb' });
- * await queue.addRequest({ url: 'http://example.com/foo/bar' }, { forefront: true });
- * ```
- * @category Sources
- */
-export class RequestQueue extends RequestProvider {
- private listHeadAndLockPromise: Promise<void> | null = null;
- private queueHasLockedRequests: boolean | undefined = undefined;
- private shouldCheckForForefrontRequests = false;
- private dequeuedRequestCount = 0;
-
- constructor(options: RequestProviderOptions, config: Configuration = serviceLocator.getConfiguration()) {
- super(
- {
- ...options,
- logPrefix: 'RequestQueue2',
- recentlyHandledRequestsMaxSize: RECENTLY_HANDLED_CACHE_SIZE,
- requestCacheMaxSize: MAX_CACHED_REQUESTS,
- },
- config,
- );
-
- this.events.on(EventType.MIGRATING, async () => {
- await this._clearPossibleLocks();
- });
-
- this.events.on(EventType.ABORTING, async () => {
- await this._clearPossibleLocks();
- });
- }
-
- /**
- * Caches information about request to beware of unneeded addRequest() calls.
- */
- protected override _cacheRequest(cacheKey: string, queueOperationInfo: RequestQueueOperationInfo): void {
- super._cacheRequest(cacheKey, queueOperationInfo);
-
- this.requestCache.remove(queueOperationInfo.requestId);
-
- this.requestCache.add(queueOperationInfo.requestId, {
- id: queueOperationInfo.requestId,
- isHandled: queueOperationInfo.wasAlreadyHandled,
- uniqueKey: queueOperationInfo.uniqueKey,
- forefront: queueOperationInfo.forefront,
- hydrated: null,
- lockExpiresAt: null,
- });
- }
-
- /**
- * @inheritDoc
- */
- override async addRequest(
- requestLike: Source,
- options: RequestQueueOperationOptions = {},
- ): Promise<RequestQueueOperationInfo> {
- const result = await super.addRequest(requestLike, options);
- if (!result.wasAlreadyPresent && options.forefront) {
- this.shouldCheckForForefrontRequests = true;
- }
- return result;
- }
-
- /**
- * @inheritDoc
- */
- override async addRequests(
- requestsLike: RequestsLike,
- options: RequestQueueOperationOptions = {},
- ): Promise<BatchAddRequestsResult> {
- const result = await super.addRequests(requestsLike, options);
- for (const request of result.processedRequests) {
- if (!request.wasAlreadyPresent && options.forefront) {
- this.shouldCheckForForefrontRequests = true;
- break;
- }
- }
- return result;
- }
-
- /**
- * @inheritDoc
- */
- override async fetchNextRequest<T extends Dictionary = Dictionary>(): Promise<Request<T> | null> {
- checkStorageAccess();
-
- if (this.queuePausedForMigration) {
- return null;
- }
-
- this.lastActivity = new Date();
-
- await this.ensureHeadIsNonEmpty();
-
- const nextRequestId = this.queueHeadIds.removeFirst();
-
- // We are likely done at this point.
- if (!nextRequestId) {
- return null;
- }
-
- const request: Request | null = await this.getOrHydrateRequest(nextRequestId);
-
- // NOTE: It can happen that the queue head index is inconsistent with the main queue table. This can occur in two situations:
-
- // 1) Queue head index is ahead of the main table and the request is not present in the main table yet (i.e. getRequest() returned null).
- // In this case, keep the request marked as in progress for a short while,
- // so that isFinished() doesn't return true and _ensureHeadIsNonEmpty() doesn't not load the request
- // into the queueHeadDict straight again. After the interval expires, fetchNextRequest()
- // will try to fetch this request again, until it eventually appears in the main table.
- if (!request) {
- this.log.debug('Cannot find a request from the beginning of queue or lost lock, will be retried later', {
- nextRequestId,
- });
-
- return null;
- }
-
- // 2) Queue head index is behind the main table and the underlying request was already handled
- // (by some other client, since we keep the track of handled requests in recentlyHandled dictionary).
- // We just add the request to the recentlyHandled dictionary so that next call to _ensureHeadIsNonEmpty()
- // will not put the request again to queueHeadDict.
- if (request.handledAt) {
- this.log.debug('Request fetched from the beginning of queue was already handled', { nextRequestId });
- return null;
- }
-
- this.dequeuedRequestCount += 1;
-
- return request;
- }
-
- /**
- * @inheritDoc
- */
- override async markRequestHandled(request: Request): Promise<RequestQueueOperationInfo | null> {
- this.dequeuedRequestCount -= 1;
- return await super.markRequestHandled(request);
- }
-
- /**
- * @inheritDoc
- */
- override async isFinished(): Promise<boolean> {
- // We are not finished if we're still adding new requests in the background
- if (this.inProgressRequestBatchCount > 0) {
- return false;
- }
-
- // If the local queue head is non-empty, we don't need to query the "upstream" queue to know we are not finished yet
- if (this.queueHeadIds.length() > 0) {
- return false;
- }
-
- // Local queue head is empty - try to fetch and lock more requests
- await this.ensureHeadIsNonEmpty();
-
- // We managed to lock something - we are not finished
- if (this.queueHeadIds.length() > 0) {
- return false;
- }
-
- // We could not lock any new requests - decide based on whether the queue contains requests locked by another client
- if (this.queueHasLockedRequests !== undefined) {
- // The `% 25` was absolutely arbitrarily picked. It's just to not spam the logs too much.
- if (
- this.queueHasLockedRequests &&
- this.dequeuedRequestCount === 0 &&
- ++this.isFinishedCalledWhileHeadWasNotEmpty % 25 === 0
- ) {
- this.log.info('The queue still contains requests locked by another client');
- }
-
- return !this.queueHasLockedRequests;
- }
-
- // The following is a legacy algorithm for checking if the queue is finished. It is used only for request queue clients that do not provide the `queueHasLockedRequests` flag.
-
- const currentHead = await this.client.listHead({ limit: 2 });
-
- if (currentHead.items.length === 0) {
- return true;
- }
-
- // Give users some more concrete info as to why their crawlers seem to be "hanging" doing nothing while we're waiting because the queue is technically
- // not empty. We decided that a queue with elements in its head but that are also locked shouldn't return true in this function.
- // If that ever changes, this function might need a rewrite
- // The `% 25` was absolutely arbitrarily picked. It's just to not spam the logs too much. This is also a very specific path that most crawlers shouldn't hit
- if (++this.isFinishedCalledWhileHeadWasNotEmpty % 25 === 0) {
- const requests = await Promise.all(currentHead.items.map(async (item) => this.client.getRequest(item.id)));
-
- this.log.info(
- `Queue head still returned requests that need to be processed (or that are locked by other clients)`,
- {
- requests: requests
- .map((r) => {
- if (!r) {
- return null;
- }
-
- return {
- id: r.id,
- lockExpiresAt: r.lockExpiresAt,
- lockedBy: r.lockByClient,
- };
- })
- .filter(Boolean),
- clientKey: this.clientKey,
- },
- );
- } else {
- this.log.debug(
- 'Queue head still returned requests that need to be processed (or that are locked by other clients)',
- {
- requestIds: currentHead.items.map((item) => item.id),
- },
- );
- }
-
- return false;
- }
-
- /**
- * @inheritDoc
- */
- override async reclaimRequest(
- ...args: Parameters<RequestProvider['reclaimRequest']>
- ): ReturnType<RequestProvider['reclaimRequest']> {
- const res = await super.reclaimRequest(...args);
-
- if (res) {
- const [request, options] = args;
-
- if (options?.forefront) {
- this.shouldCheckForForefrontRequests = true;
- }
-
- // Try to delete the request lock if possible
- try {
- await this.client.deleteRequestLock(request.id!, { forefront: options?.forefront ?? false });
- } catch (err) {
- this.log.debug(`Failed to delete request lock for request ${request.id}`, { err });
- }
- }
-
- return res;
- }
-
- protected async ensureHeadIsNonEmpty() {
- checkStorageAccess();
-
- // Stop fetching if we are paused for migration
- if (this.queuePausedForMigration) {
- return;
- }
-
- // We want to fetch ahead of time to minimize dead time
- // If we need to check for newly added forefront requests, we do it even if we already have some locked requests
- if (this.queueHeadIds.length() > QUEUE_HEAD_REFILL_THRESHOLD && !this.shouldCheckForForefrontRequests) {
- return;
- }
-
- this.listHeadAndLockPromise ??= this._listHeadAndLock().finally(() => {
- this.listHeadAndLockPromise = null;
- });
-
- await this.listHeadAndLockPromise;
- }
-
- private async giveUpLock(id?: string, uniqueKey?: string) {
- if (id === undefined) {
- return;
- }
-
- try {
- await this.client.deleteRequestLock(id);
- } catch {
- this.log.debug('Failed to delete request lock', { id, uniqueKey });
- }
- }
-
- private async _listHeadAndLock(): Promise<void> {
- // Make a copy so that we can clear the flag only if the whole method executes after the flag was set
- // (i.e, it was not set in the middle of the execution of the method)
- const shouldCheckForForefrontRequests = this.shouldCheckForForefrontRequests;
-
- // NOTE: in theory, if we're not checking for forefront requests, we could fetch just enough requests to fill the local queue head to the limit.
- // We chose not to do this because 1. it's simpler and 2. the queue is being processed while we're fetching and we want to avoid underruns.
- // If we are checking for forefront requests, we need to fetch enough requests to be sure that we won't miss any new forefront ones.
- const headData = await this.client.listAndLockHead({
- limit: LIST_AND_LOCK_HEAD_LIMIT,
- lockSecs: this.requestLockSecs,
- });
-
- this.queueHasLockedRequests = headData.queueHasLockedRequests;
-
- const headIdBuffer = [];
- const forefrontHeadIdBuffer = [];
-
- // Go through the fetched requests, ensure they are cached locally and sort them into normal and forefront groups
- for (const { id, uniqueKey } of headData.items) {
- if (!id || !uniqueKey) {
- this.log.warning(
- `Skipping request from queue head as it's invalid. Please report this with the provided metadata!`,
- {
- id,
- uniqueKey,
- },
- );
-
- // Remove the lock from the request for now, so that it can be picked up later
- // This may/may not succeed, but that's fine
- await this.giveUpLock(id, uniqueKey);
- continue;
- }
-
- // If we remember that we added the request ourselves and we added it to the forefront,
- // we will put it to the beginning of the local queue head to preserve the expected order.
- // If we do not remember that, we will enqueue it normally.
- const forefront = this.requestCache.get(getRequestId(uniqueKey))?.forefront ?? false;
- if (forefront) {
- forefrontHeadIdBuffer.unshift(id);
- } else {
- headIdBuffer.push(id);
- }
-
- // Ensure that the request is cached locally
- this._cacheRequest(getRequestId(uniqueKey), {
- requestId: id,
- uniqueKey,
- wasAlreadyPresent: true,
- wasAlreadyHandled: false,
- forefront,
- });
- }
-
- // Insert the newly fetched requests into the local queue head
- for (const id of headIdBuffer) {
- this.queueHeadIds.add(id, id, false);
- }
-
- for (const id of forefrontHeadIdBuffer) {
- this.queueHeadIds.add(id, id, true);
- }
-
- // Unlock and forget requests that would make the local queue head grow over the limit
- const toUnlock = [];
- const limit = shouldCheckForForefrontRequests
- ? LIST_AND_LOCK_HEAD_LIMIT // we may have received up to LIST_AND_LOCK_HEAD_LIMIT newly added forefront requests - we need to make sure that anything we already had in the queue gets unlocked
- : LIST_AND_LOCK_HEAD_LIMIT + QUEUE_HEAD_REFILL_THRESHOLD; // we tolerate up to QUEUE_HEAD_REFILL_THRESHOLD additional requests to avoid frequent, yet unnecessary unlocks
- while (this.queueHeadIds.length() > limit) {
- toUnlock.push(this.queueHeadIds.removeLast()!);
- }
-
- if (toUnlock.length > 0) {
- await Promise.all(toUnlock.map(async (id) => await this.giveUpLock(id)));
- }
-
- // We went through the whole procedure after `this.shouldCheckForForefrontRequests` was set -> we can clear the flag now
- if (shouldCheckForForefrontRequests) {
- this.shouldCheckForForefrontRequests = false;
- }
- }
-
- private async getOrHydrateRequest<T extends Dictionary = Dictionary>(
- requestId: string,
- ): Promise<Request<T> | null> {
- checkStorageAccess();
-
- const cachedEntry = this.requestCache.get(requestId);
-
- if (!cachedEntry) {
- // 2.1. Attempt to prolong the request lock to see if we still own the request
- const prolongResult = await this._prolongRequestLock(requestId);
-
- if (!prolongResult) {
- return null;
- }
-
- // 2.1.1. If successful, hydrate the request and return it
- const hydratedRequest = await this.getRequest(requestId);
-
- // Queue head index is ahead of the main table and the request is not present in the main table yet (i.e. getRequest() returned null).
- if (!hydratedRequest) {
- // Remove the lock from the request for now, so that it can be picked up later
- // This may/may not succeed, but that's fine
- try {
- await this.client.deleteRequestLock(requestId);
- } catch {
- // Ignore
- }
-
- return null;
- }
-
- this.requestCache.add(requestId, {
- id: requestId,
- uniqueKey: hydratedRequest.uniqueKey,
- hydrated: hydratedRequest,
- isHandled: hydratedRequest.handledAt !== null,
- lockExpiresAt: prolongResult.getTime(),
- forefront: false,
- });
-
- return hydratedRequest;
- }
-
- // 1.1. If hydrated, prolong the lock more and return it
- if (cachedEntry.hydrated) {
- // 1.1.1. If the lock expired on the hydrated requests, try to prolong. If we fail, we lost the request (or it was handled already)
- if (cachedEntry.lockExpiresAt && cachedEntry.lockExpiresAt < Date.now()) {
- const prolonged = await this._prolongRequestLock(cachedEntry.id);
-
- if (!prolonged) {
- return null;
- }
-
- cachedEntry.lockExpiresAt = prolonged.getTime();
- }
-
- return cachedEntry.hydrated;
- }
-
- // 1.2. If not hydrated, try to prolong the lock first (to ensure we keep it in our queue), hydrate and return it
- const prolonged = await this._prolongRequestLock(cachedEntry.id);
-
- if (!prolonged) {
- return null;
- }
-
- // This might still return null if the queue head is inconsistent with the main queue table.
- const hydratedRequest = await this.getRequest(cachedEntry.id);
-
- cachedEntry.hydrated = hydratedRequest;
-
- // Queue head index is ahead of the main table and the request is not present in the main table yet (i.e. getRequest() returned null).
- if (!hydratedRequest) {
- // Remove the lock from the request for now, so that it can be picked up later
- // This may/may not succeed, but that's fine
- try {
- await this.client.deleteRequestLock(cachedEntry.id);
- } catch {
- // Ignore
- }
-
- return null;
- }
-
- return hydratedRequest;
- }
-
- private async _prolongRequestLock(requestId: string): Promise<Date | null> {
- try {
- const res = await this.client.prolongRequestLock(requestId, { lockSecs: this.requestLockSecs });
- return res.lockExpiresAt;
- } catch (err: any) {
- // Most likely we do not own the lock anymore
- this.log.warning(
- `Failed to prolong lock for cached request ${requestId}, either lost the lock or the request was already handled\n`,
- {
- err,
- },
- );
-
- return null;
- }
- }
-
- protected override _reset() {
- super._reset();
- this.listHeadAndLockPromise = null;
- this.queueHasLockedRequests = undefined;
- }
-
- protected override _maybeAddRequestToQueueHead() {
- // Do nothing for request queue v2, as we are only able to lock requests when listing the head
- }
-
- protected async _clearPossibleLocks() {
- this.queuePausedForMigration = true;
- let requestId: string | null;
-
- while ((requestId = this.queueHeadIds.removeFirst()) !== null) {
- try {
- await this.client.deleteRequestLock(requestId);
- } catch {
- // We don't have the lock, or the request was never locked. Either way it's fine
- }
- }
- }
-
- /**
- * @inheritDoc
- */
- static override async open(...args: Parameters<typeof RequestProvider.open>): Promise<RequestQueue> {
- return super.open(...args) as Promise<RequestQueue>;
- }
-}
diff --git a/packages/core/src/storages/sitemap_request_loader.ts b/packages/core/src/storages/sitemap_request_loader.ts
index 0ad8b9cb2..8f602ce53 100644
--- a/packages/core/src/storages/sitemap_request_loader.ts
+++ b/packages/core/src/storages/sitemap_request_loader.ts
@@ -481,7 +481,7 @@ export class SitemapRequestLoader implements IRequestLoader {
async toTandem(requestManager?: IRequestManager): Promise<IRequestManager> {
// Import here to avoid circular imports.
const { RequestManagerTandem } = await import('./request_manager_tandem.js');
- const { RequestQueue } = await import('./request_queue_v2.js');
+ const { RequestQueue } = await import('./request_queue.js');
return new RequestManagerTandem(this, requestManager ?? (await RequestQueue.open()));
}
@@ -642,7 +642,7 @@ export class SitemapRequestLoader implements IRequestLoader {
/**
* @inheritDoc
*/
- async markRequestHandled(request: Request): Promise<void> {
+ async markRequestAsHandled(request: Request): Promise<void> {
this.handledUrlCount += 1;
this.ensureInProgress(request.url);
this.inProgress.delete(request.url);
diff --git a/packages/core/test/request-queue/adding-the-same-request-should-not-call-the-api.test.ts b/packages/core/test/request-queue/adding-the-same-request-should-not-call-the-api.test.ts
index bcc7ebc16..831bf3c46 100644
--- a/packages/core/test/request-queue/adding-the-same-request-should-not-call-the-api.test.ts
+++ b/packages/core/test/request-queue/adding-the-same-request-should-not-call-the-api.test.ts
@@ -16,18 +16,17 @@ describe('RequestQueue#addRequest should not call the API if the request is alre
const rqInfo = await rqClient.getMetadata();
const requestQueue = new RequestQueue({ id: rqInfo.id, client: rqClient }, config);
- const clientSpy = vitest.spyOn(requestQueue.client, 'addRequest');
+ const clientSpy = vitest.spyOn(requestQueue.client, 'addBatchOfRequests');
- const requestData = await requestQueue.addRequest({ url: 'https://example.com' });
+ await requestQueue.addRequest({ url: 'https://example.com' });
expect(clientSpy).toHaveBeenCalledTimes(1);
- await requestQueue.markRequestHandled({
- id: requestData.requestId,
- url: 'https://example.com',
- uniqueKey: requestData.uniqueKey,
- } as any);
+ // Fetch and handle the request so it leaves the pending queue.
+ const fetched = await requestQueue.fetchNextRequest();
+ await requestQueue.markRequestAsHandled(fetched!);
+ // Adding the same request again is served from the local cache and must not hit the client.
await requestQueue.addRequest({ url: 'https://example.com' });
expect(clientSpy).toHaveBeenCalledTimes(1);
@@ -40,18 +39,17 @@ describe('RequestQueue#addRequests should not call the API if the request is alr
const rqInfo = await rqClient.getMetadata();
const requestQueue = new RequestQueue({ id: rqInfo.id, client: rqClient }, config);
- const clientSpy = vitest.spyOn(requestQueue.client, 'batchAddRequests');
+ const clientSpy = vitest.spyOn(requestQueue.client, 'addBatchOfRequests');
- const requestData = await requestQueue.addRequests([{ url: 'https://example2.com' }]);
+ await requestQueue.addRequests([{ url: 'https://example2.com' }]);
expect(clientSpy).toHaveBeenCalledTimes(1);
- await requestQueue.markRequestHandled({
- id: requestData.processedRequests[0].requestId,
- uniqueKey: requestData.processedRequests[0].uniqueKey,
- url: 'https://example2.com',
- } as any);
+ // Fetch and handle the request so it leaves the pending queue.
+ const fetched = await requestQueue.fetchNextRequest();
+ await requestQueue.markRequestAsHandled(fetched!);
+ // Adding the same request again is served from the local cache and must not hit the client.
await requestQueue.addRequests([{ url: 'https://example2.com' }]);
expect(clientSpy).toHaveBeenCalledTimes(1);
diff --git a/packages/core/test/request-queue/request-queue-v2.test.ts b/packages/core/test/request-queue/request-queue-v2.test.ts
deleted file mode 100644
index 802c0ca79..000000000
--- a/packages/core/test/request-queue/request-queue-v2.test.ts
+++ /dev/null
@@ -1,138 +0,0 @@
-import { MemoryStorage } from '@crawlee/memory-storage';
-import type { ListAndLockHeadResult, RequestQueueClient } from '@crawlee/types';
-import { RequestQueueV2 } from 'crawlee';
-import type { MockInstance } from 'vitest';
-
-const storage = new MemoryStorage({ persistStorage: false, writeMetadata: false });
-
-async function makeQueue(name: string, numOfRequestsToAdd = 0) {
- const rqClient = await storage.createRequestQueueClient({ name });
- const rqInfo = await rqClient.getMetadata();
-
- const queue = new RequestQueueV2({ id: rqInfo.id, client: rqClient });
-
- if (numOfRequestsToAdd) {
- await queue.addRequests(
- Array.from({ length: numOfRequestsToAdd }, (_, i) => ({ url: 'https://example.com', uniqueKey: `${i}` })),
- );
- }
-
- return queue;
-}
-
-vitest.setConfig({ restoreMocks: false });
-
-describe('RequestQueueV2#isFinished should use listHead instead of listAndLock', () => {
- let queue: RequestQueueV2;
- let clientListHeadSpy: MockInstance<typeof queue.client.listHead>;
-
- beforeAll(async () => {
- queue = await makeQueue('is-finished', 2);
- clientListHeadSpy = vitest.spyOn(queue.client, 'listHead');
- });
-
- test('should return false if there are still requests in the queue', async () => {
- expect(await queue.isFinished()).toBe(false);
- });
-
- test('should return false even if all requests are locked', async () => {
- queue.client.listAndLockHead = async (options) => ({
- lockSecs: options.lockSecs,
- queueModifiedAt: new Date(),
- limit: 10,
- items: [],
- queueHasLockedRequests: true,
- });
-
- expect(await queue.isFinished()).toBe(false);
- expect(clientListHeadSpy).not.toHaveBeenCalled();
- });
-});
-
-describe('RequestQueueV2#isFinished should return true once locked requests are handled', () => {
- let queue: RequestQueueV2;
- let clientListHeadSpy: MockInstance<typeof queue.client.listHead>;
- let listHeadCallCount = 0;
- let clientListAndLockHeadSpy: MockInstance<typeof queue.client.listAndLockHead>;
- let lockResult: ListAndLockHeadResult;
-
- beforeAll(async () => {
- queue = await makeQueue('is-finished-locked', 1);
- clientListHeadSpy = vitest.spyOn(queue.client, 'listHead');
- clientListAndLockHeadSpy = vitest.spyOn(queue.client, 'listAndLockHead');
-
- lockResult = await queue.client.listAndLockHead({ lockSecs: 60 });
- // eslint-disable-next-line dot-notation
- queue['queueHeadIds'].add(lockResult.items[0].id, lockResult.items[0].id);
- });
-
- test('should return true once locked requests are handled', async () => {
- // Check that, when locked request isn't handled yet, it returns false
- expect(await queue.isFinished()).toBe(false);
-
- // Mark the locked request as handled
- await queue.markRequestHandled((await queue.getRequest(lockResult.items[0].id))!);
-
- // Check that, when locked request is handled, it returns true
- expect(await queue.isFinished()).toBe(true);
- expect(clientListHeadSpy).toHaveBeenCalledWith({ limit: 2 });
- expect(clientListHeadSpy).toHaveBeenCalledTimes(++listHeadCallCount);
- // One time
- expect(clientListAndLockHeadSpy).toHaveBeenCalled();
- });
-});
-
-describe('RequestQueueV2#fetchNextRequest should use locking API', () => {
- let queue: RequestQueueV2;
- let clientListHeadSpy: MockInstance<typeof queue.client.listHead>;
- let clientListAndLockHeadSpy: MockInstance<typeof queue.client.listAndLockHead>;
- let clientProlongLockSpy: MockInstance<typeof queue.client.prolongRequestLock>;
- let listAndLockHeadCallCount = 0;
-
- beforeAll(async () => {
- queue = await makeQueue('fetch-next-request', 1);
- clientListHeadSpy = vitest.spyOn(queue.client, 'listHead');
- clientListAndLockHeadSpy = vitest.spyOn(queue.client, 'listAndLockHead');
- clientProlongLockSpy = vitest.spyOn(queue.client, 'prolongRequestLock');
- });
-
- test('should return the first request', async () => {
- expect(await queue.fetchNextRequest()).not.toBe(null);
-
- // Check that it uses the locking API
- expect(clientListAndLockHeadSpy).toHaveBeenCalledTimes(++listAndLockHeadCallCount);
- expect(clientListHeadSpy).not.toHaveBeenCalled();
-
- // Check that the lock is prolonged too
- expect(clientProlongLockSpy).toHaveBeenCalled();
- });
-
- test('should return null when all requests are locked', async () => {
- expect(await queue.fetchNextRequest()).toBe(null);
-
- expect(clientListAndLockHeadSpy).toHaveBeenCalledTimes(++listAndLockHeadCallCount);
- expect(clientListHeadSpy).not.toHaveBeenCalled();
- });
-});
-
-describe('RequestQueueV2#isEmpty should return true even if isFinished returns false due to locked requests', () => {
- let queue: RequestQueueV2;
- let lockResult: ListAndLockHeadResult;
-
- beforeAll(async () => {
- queue = await makeQueue('is-empty-vs-is-finished', 1);
- lockResult = await queue.client.listAndLockHead({ lockSecs: 60 });
- });
-
- test('should return true when isFinished returns false', async () => {
- expect(await queue.isEmpty()).toBe(true);
- expect(await queue.isFinished()).toBe(false);
- });
-
- test('should return true when isFinished returns true', async () => {
- await queue.markRequestHandled((await queue.getRequest(lockResult.items[0].id))!);
-
- expect(await queue.isEmpty()).toBe(true);
- expect(await queue.isFinished()).toBe(true);
- });
-});
diff --git a/packages/core/test/request-queue/request-queue.test.ts b/packages/core/test/request-queue/request-queue.test.ts
new file mode 100644
index 000000000..a14e8040e
--- /dev/null
+++ b/packages/core/test/request-queue/request-queue.test.ts
@@ -0,0 +1,85 @@
+import { MemoryStorage } from '@crawlee/memory-storage';
+import { RequestQueue } from 'crawlee';
+import type { MockInstance } from 'vitest';
+
+const storage = new MemoryStorage({ persistStorage: false, writeMetadata: false });
+
+async function makeQueue(name: string, numOfRequestsToAdd = 0) {
+ const rqClient = await storage.createRequestQueueClient({ name });
+ const rqInfo = await rqClient.getMetadata();
+
+ const queue = new RequestQueue({ id: rqInfo.id, client: rqClient });
+
+ if (numOfRequestsToAdd) {
+ await queue.addRequests(
+ Array.from({ length: numOfRequestsToAdd }, (_, i) => ({ url: 'https://example.com', uniqueKey: `${i}` })),
+ );
+ }
+
+ return queue;
+}
+
+vitest.setConfig({ restoreMocks: false });
+
+describe('RequestQueue#fetchNextRequest delegates to the client', () => {
+ let queue: RequestQueue;
+ let clientFetchNextSpy: MockInstance<typeof queue.client.fetchNextRequest>;
+
+ beforeAll(async () => {
+ queue = await makeQueue('fetch-next-request', 1);
+ clientFetchNextSpy = vitest.spyOn(queue.client, 'fetchNextRequest');
+ });
+
+ test('returns the first request via the client', async () => {
+ expect(await queue.fetchNextRequest()).not.toBe(null);
+ expect(clientFetchNextSpy).toHaveBeenCalled();
+ });
+
+ test('returns null once all requests are in progress', async () => {
+ // The single request was already fetched (and is in progress) above.
+ expect(await queue.fetchNextRequest()).toBe(null);
+ });
+});
+
+describe('RequestQueue#isEmpty and #isFinished treat in-progress requests differently', () => {
+ let queue: RequestQueue;
+
+ beforeAll(async () => {
+ queue = await makeQueue('is-empty-vs-is-finished', 1);
+ });
+
+ test('a fetched (in-progress) request leaves the queue empty but not finished', async () => {
+ const request = await queue.fetchNextRequest();
+ expect(request).not.toBe(null);
+
+ // The fetched request is in progress (locked), not handled. There is nothing left to fetch, so
+ // the queue is empty (`isEmpty` is the "would fetchNextRequest return null" check). It is not
+ // finished though — the in-progress request might still be reclaimed — and that is what prevents
+ // a crawler from shutting down while a request is still being processed.
+ expect(await queue.isEmpty()).toBe(true);
+ expect(await queue.isFinished()).toBe(false);
+ });
+
+ test('handling the in-progress request finishes the queue', async () => {
+ const request = await queue.getRequest('0');
+ await queue.markRequestAsHandled(request!);
+
+ expect(await queue.isEmpty()).toBe(true);
+ expect(await queue.isFinished()).toBe(true);
+ });
+});
+
+describe('RequestQueue#isFinished waits for background add operations', () => {
+ test('returns false while a background batch is still being added', async () => {
+ const queue = await makeQueue('is-finished-background');
+
+ // Simulate an in-flight background `addRequestsBatched` operation.
+ // eslint-disable-next-line dot-notation
+ queue['inProgressRequestBatchCount'] = 1;
+ expect(await queue.isFinished()).toBe(false);
+
+ // eslint-disable-next-line dot-notation
+ queue['inProgressRequestBatchCount'] = 0;
+ expect(await queue.isFinished()).toBe(true);
+ });
+});
diff --git a/packages/memory-storage/src/memory-storage.ts b/packages/memory-storage/src/memory-storage.ts
index c0c20a8ec..3fe71a3e9 100644
--- a/packages/memory-storage/src/memory-storage.ts
+++ b/packages/memory-storage/src/memory-storage.ts
@@ -349,6 +349,12 @@ export class MemoryStorage implements storage.StorageClient {
* This method should be called at the end of the process, to ensure all data is saved.
*/
async teardown(): Promise<void> {
+ // Release any request locks this process still holds so that requests fetched but not yet
+ // handled are not stuck (until their lock expires) for the next consumer of the same on-disk
+ // queue. Other storage backends don't need this: the Apify platform releases a run's locks
+ // automatically, and the file-system storage doesn't lock at all.
+ await Promise.all(this.requestQueueCache.map(async (queue) => queue.releaseOwnLocks()));
+
const promises = [...promiseMap.values()].map(async ({ promise }) => promise);
await Promise.all(promises);
diff --git a/packages/memory-storage/src/resource-clients/request-queue.ts b/packages/memory-storage/src/resource-clients/request-queue.ts
index 3699edbd5..cb5d40b37 100644
--- a/packages/memory-storage/src/resource-clients/request-queue.ts
+++ b/packages/memory-storage/src/resource-clients/request-queue.ts
@@ -55,6 +55,23 @@ export interface InternalRequest {
json: string;
}
+/**
+ * Default time (in seconds) for which a request fetched via {@link RequestQueueClient.fetchNextRequest}
+ * stays locked (in progress) before it becomes available again. Aligns with the historical request queue
+ * locking default. A consumer (e.g. a crawler) can raise this per queue via
+ * {@link RequestQueueClient.setExpectedRequestProcessingTimeSecs}.
+ */
+const DEFAULT_REQUEST_LOCK_SECS = 3 * 60;
+
+/**
+ * A request is "locked" (in progress) when its `orderNo` is pushed beyond the current time. The sign of
+ * `orderNo` is preserved so the original forefront / normal ordering is restored once the lock expires
+ * or the request is reclaimed.
+ */
+function isRequestLocked(orderNo: number | null, now: number): boolean {
+ return orderNo !== null && Math.abs(orderNo) > now;
+}
+
export class RequestQueueClient extends BaseClient implements storage.RequestQueueClient {
name?: string;
/**
@@ -68,12 +85,33 @@ export class RequestQueueClient extends BaseClient implements storage.RequestQue
handledRequestCount = 0;
pendingRequestCount = 0;
requestQueueDirectory: string;
- private readonly mutex = new AsyncQueue();
+ /**
+ * Serializes every operation that reads-then-writes this client's shared queue state — the
+ * `requests` map, the `forefrontRequestIds` array, the `inProgressRequestIds` set and the request
+ * counts. Those mutations span `await` points (disk/storage I/O), so without this lock a concurrent
+ * operation could interleave and corrupt them (e.g. a head scan pruning `forefrontRequestIds` while
+ * `addBatchOfRequests` pushes to it). Held by every mutating method as well as by `isEmpty`/
+ * `isFinished`, whose head scan also prunes `forefrontRequestIds`.
+ */
+ private readonly queueStateMutex = new AsyncQueue();
private forefrontRequestIds: string[] = [];
+ /**
+ * IDs of requests this client has locked (fetched but not yet handled or reclaimed). Used by
+ * {@link releaseOwnLocks} to free our own in-progress requests on process termination, so that
+ * a crashed/migrated consumer does not block its requests for the full lock duration.
+ */
+ private readonly inProgressRequestIds = new Set<string>();
+
private readonly requests = new Map<string, RequestQueueFileSystemEntry | RequestQueueMemoryEntry>();
private readonly client: MemoryStorage;
+ /**
+ * How long (in seconds) a request fetched from this client stays locked (in progress). Defaults to
+ * {@link DEFAULT_REQUEST_LOCK_SECS} and is overridable via {@link setExpectedRequestProcessingTimeSecs}.
+ */
+ private lockSecs = DEFAULT_REQUEST_LOCK_SECS;
+
constructor(options: RequestQueueClientOptions) {
super(options.id ?? randomUUID());
this.name = options.name;
@@ -82,6 +120,15 @@ export class RequestQueueClient extends BaseClient implements storage.RequestQue
this.client = options.client;
}
+ /**
+ * Applies how long {@link fetchNextRequest} locks a request before it becomes available again. The
+ * caller (the `RequestQueue` frontend) owns the policy of what this value should be — this method
+ * just applies it.
+ */
+ setExpectedRequestProcessingTimeSecs(secs: number): void {
+ this.lockSecs = secs;
+ }
+
async getMetadata(): Promise<storage.RequestQueueInfo> {
this.updateTimestamps(false);
return this.toRequestQueueInfo();
@@ -100,54 +147,87 @@ export class RequestQueueClient extends BaseClient implements storage.RequestQue
}
async purge(): Promise<void> {
- // Clear all in-memory state
- this.requests.clear();
- this.forefrontRequestIds = [];
- this.handledRequestCount = 0;
- this.pendingRequestCount = 0;
-
- // Remove request files from disk but keep the directory
- if (this.client.persistStorage) {
- const { readdir } = await import('node:fs/promises');
- const entries = await readdir(this.requestQueueDirectory).catch(() => []);
- for (const entry of entries) {
- if (entry !== '__metadata__.json') {
- await rm(resolve(this.requestQueueDirectory, entry), { force: true });
+ // Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so a concurrent
+ // operation cannot observe or repopulate half-cleared state across the `await` below.
+ await this.queueStateMutex.wait();
+
+ try {
+ // Clear all in-memory state
+ this.requests.clear();
+ this.forefrontRequestIds = [];
+ this.inProgressRequestIds.clear();
+ this.handledRequestCount = 0;
+ this.pendingRequestCount = 0;
+
+ // Reset the lock duration back to the default so a value raised via
+ // `setExpectedRequestProcessingTimeSecs` in an earlier run does not leak into a later one
+ this.lockSecs = DEFAULT_REQUEST_LOCK_SECS;
+
+ // Remove request files from disk but keep the directory
+ if (this.client.persistStorage) {
+ const { readdir } = await import('node:fs/promises');
+ const entries = await readdir(this.requestQueueDirectory).catch(() => []);
+ for (const entry of entries) {
+ if (entry !== '__metadata__.json') {
+ await rm(resolve(this.requestQueueDirectory, entry), { force: true });
+ }
}
}
- }
- this.updateTimestamps(true);
+ this.updateTimestamps(true);
+ } finally {
+ this.queueStateMutex.shift();
+ }
}
- private *requestKeyIterator(rqClient: RequestQueueClient): IterableIterator<string> {
+ private *requestKeyIterator(): IterableIterator<string> {
for (let i = this.forefrontRequestIds.length - 1; i >= 0; i--) {
yield this.forefrontRequestIds[i];
}
- for (const key of rqClient.requests.keys()) {
+ for (const key of this.requests.keys()) {
yield key;
}
}
- async listHead(options: storage.ListOptions = {}): Promise<storage.QueueHead> {
- const { limit } = s
- .object({
- limit: s.number().optional().default(100),
- })
- .parse(options);
-
- this.updateTimestamps(false);
-
- const items = [];
-
- // Tracks processed request IDs to avoid duplicates when a request is in both `forefrontRequestIds` and `requests`.
+ /**
+ * Scans the queue and returns the pending head — requests that are neither handled nor currently
+ * locked (in progress) — ordered by `orderNo`, deduplicated.
+ *
+ * When `detectLockedRequests` is set, the result also carries a `hasLockedRequests` flag telling
+ * whether any unhandled-but-locked request was skipped along the way. This mirrors the Apify
+ * platform shared client's `queueHasLockedRequests` signal: it lets {@link isFinished} distinguish
+ * "no work left at all" from "work remains, but it is currently locked by some consumer (possibly
+ * another process)". Without it, a consumer would consider the queue finished and let the crawler
+ * shut down while another consumer still holds the last requests.
+ *
+ * Computing the flag is expensive: because a lock may sit anywhere in the queue, it forces a scan
+ * of every pending entry even when only `limit` items are wanted. Callers that only need the head
+ * (e.g. {@link fetchNextRequest}, {@link isEmpty}) leave it off so the scan can stop as soon as the
+ * page is filled, keeping those calls O(head) instead of O(N).
+ *
+ * Lock state lives in the persisted `orderNo` (see {@link isRequestLocked}), so that processes
+ * sharing the same on-disk queue observe each other's locks. We therefore re-read entries from
+ * storage to obtain fresh lock state, except for entries we can cheaply rule out as permanently
+ * handled via their cached `orderNo === null`.
+ */
+ private async listPendingHead(
+ limit: number,
+ detectLockedRequests = false,
+ ): Promise<{ items: InternalRequest[]; hasLockedRequests?: boolean }> {
+ const now = Date.now();
+ const items: InternalRequest[] = [];
+ let hasLockedRequests = false;
+
+ // Tracks processed request IDs to avoid duplicates (request in both `forefrontRequestIds` and `requests`).
const seenRequestIds = new Set<string>();
// Tracks handled request IDs from `forefrontRequestIds` to be removed.
const handledForefrontIds = new Set<string>();
- for (const requestId of this.requestKeyIterator(this)) {
- if (items.length === limit) {
+ for (const requestId of this.requestKeyIterator()) {
+ // Once the requested page is filled we can stop — unless the caller asked us to detect locked
+ // requests and we have not yet seen one, in which case we must keep scanning to find them.
+ if (items.length >= limit && (!detectLockedRequests || hasLockedRequests)) {
break;
}
@@ -159,357 +239,361 @@ export class RequestQueueClient extends BaseClient implements storage.RequestQue
const storageEntry = this.requests.get(requestId)!;
- let { orderNo } = storageEntry;
- let loaded: InternalRequest;
+ // Cheap rejection of permanently-handled requests using the cached `orderNo` (handled is a
+ // terminal state, so the cached value can be trusted without re-reading from storage).
+ if (storageEntry.orderNo === null) {
+ if (this.forefrontRequestIds.includes(requestId)) {
+ handledForefrontIds.add(requestId);
+ }
+ continue;
+ }
- // Uncached entry
- if (typeof orderNo === 'undefined') {
- loaded = await storageEntry.get();
+ // Re-read from storage to get fresh lock state — another process may have locked (or handled)
+ // this request since we last cached it.
+ const request = await storageEntry.get(true);
- orderNo = loaded.orderNo;
+ // Handled in the meantime.
+ if (request.orderNo === null) {
+ if (this.forefrontRequestIds.includes(requestId)) {
+ handledForefrontIds.add(requestId);
+ }
+ continue;
}
- // Have an order no -> fetch from fs/memory and return
- if (orderNo) {
- items.push(await storageEntry.get());
- } else if (this.forefrontRequestIds.includes(requestId)) {
- handledForefrontIds.add(requestId);
+ // Locked (in progress) by us or another process — skip until the lock expires, but remember
+ // that the queue is not truly empty.
+ if (isRequestLocked(request.orderNo, now)) {
+ hasLockedRequests = true;
+ continue;
+ }
+
+ if (items.length < limit) {
+ items.push(request);
}
}
this.forefrontRequestIds = this.forefrontRequestIds.filter((id) => !handledForefrontIds.has(id));
return {
- limit,
- hadMultipleClients: false,
- queueModifiedAt: this.modifiedAt,
- items: items.sort((a, b) => a.orderNo! - b.orderNo!).map(({ json }) => this._jsonToRequest(json)!),
+ items: items.sort((a, b) => a.orderNo! - b.orderNo!),
+ hasLockedRequests: detectLockedRequests ? hasLockedRequests : undefined,
};
}
- async listAndLockHead(options: storage.ListAndLockOptions): Promise<storage.ListAndLockHeadResult> {
- const { limit, lockSecs } = s
- .object({
- limit: s.number().lessThanOrEqual(25).optional().default(25),
- lockSecs: s.number(),
- })
- .parse(options);
-
+ async fetchNextRequest(): Promise<storage.RequestOptions | null> {
this.updateTimestamps(false);
- const start = Date.now();
- const isLocked = (request: InternalRequest) =>
- !request.orderNo || request.orderNo > start || request.orderNo < -start;
+ await this.queueStateMutex.wait();
- const items = [];
+ try {
+ const {
+ items: [head],
+ } = await this.listPendingHead(1);
+
+ if (!head) {
+ return null;
+ }
- await this.mutex.wait();
+ // Lock the request by pushing its `orderNo` beyond the lock expiry, preserving the sign so
+ // its original (forefront / normal) position is restored once the lock expires. The lock is
+ // persisted so other processes sharing this queue will not fetch the same request.
+ const lockExpiresAt = Date.now() + this.lockSecs * 1000;
+ head.orderNo = lockExpiresAt * (head.orderNo! > 0 ? 1 : -1);
+ await this.requests.get(head.id)!.update(head);
+
+ // Remember that this client owns the lock, so we can release it on process termination
+ // (see `releaseOwnLocks`) instead of leaving the request stuck until the lock expires.
+ this.inProgressRequestIds.add(head.id);
+
+ return this._jsonToRequest(head.json) ?? null;
+ } finally {
+ this.queueStateMutex.shift();
+ }
+ }
+
+ async addBatchOfRequests(
+ requests: storage.RequestSchema[],
+ options: storage.RequestOptions = {},
+ ): Promise<storage.BatchAddRequestsResult> {
+ batchRequestShapeWithoutId.parse(requests);
+ requestOptionsShape.parse(options);
+
+ // Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so that the
+ // shared `requests` map, `forefrontRequestIds` array and request counts are not corrupted by a
+ // concurrent operation interleaving at one of the `await` points below.
+ await this.queueStateMutex.wait();
try {
- // Tracks processed request IDs to avoid duplicates (when a request is in both `forefrontRequestIds` and `requests`).
- const seenRequestIds = new Set<string>();
- // Tracks handled request IDs from `forefrontRequestIds` (to be all removed at once).
- const handledForefrontIds = new Set<string>();
-
- for (const requestId of this.requestKeyIterator(this)) {
- if (items.length === limit) {
- break;
- }
+ const result: storage.BatchAddRequestsResult = {
+ processedRequests: [],
+ unprocessedRequests: [],
+ };
- if (seenRequestIds.has(requestId)) {
- continue;
- }
+ for (const model of requests) {
+ const requestModel = this._createInternalRequest(model, options.forefront);
- seenRequestIds.add(requestId);
+ const existingRequestWithIdEntry = this.requests.get(requestModel.id);
- const storageEntry = this.requests.get(requestId)!;
+ if (existingRequestWithIdEntry) {
+ const existingRequestWithId = await existingRequestWithIdEntry.get();
+
+ result.processedRequests.push({
+ requestId: existingRequestWithId.id,
+ uniqueKey: existingRequestWithId.uniqueKey,
+ wasAlreadyHandled: existingRequestWithId.orderNo === null,
+ wasAlreadyPresent: true,
+ });
- // This is set to null when the request has been handled, so we don't need to re-fetch from fs
- if (storageEntry.orderNo === null) {
- if (this.forefrontRequestIds.includes(requestId)) {
- handledForefrontIds.add(requestId);
- }
continue;
}
- // Always fetch from fs, as this also locks and we do not want to end up in a state where another process locked the request but we have cached it as unlocked
- const request = await storageEntry.get(true);
+ const newEntry = createRequestQueueStorageImplementation({
+ persistStorage: this.client.persistStorage,
+ requestId: requestModel.id,
+ storeDirectory: this.requestQueueDirectory,
+ });
- if (isLocked(request)) {
- continue;
+ await newEntry.update(requestModel);
+
+ this.requests.set(requestModel.id, newEntry);
+
+ if (requestModel.orderNo) {
+ this.pendingRequestCount += 1;
+ } else {
+ this.handledRequestCount += 1;
}
- request.orderNo = (start + lockSecs * 1000) * (request.orderNo! > 0 ? 1 : -1);
- await storageEntry.update(request);
+ if (options.forefront) {
+ this.forefrontRequestIds.push(requestModel.id);
+ }
- items.push(request);
+ result.processedRequests.push({
+ requestId: requestModel.id,
+ uniqueKey: requestModel.uniqueKey,
+ // We return wasAlreadyHandled: false even though the request may
+ // have been added as handled, because that's how API behaves.
+ wasAlreadyHandled: false,
+ wasAlreadyPresent: false,
+ });
}
- this.forefrontRequestIds = this.forefrontRequestIds.filter((id) => !handledForefrontIds.has(id));
+ this.updateTimestamps(true);
- return {
- limit,
- lockSecs,
- hadMultipleClients: false,
- queueModifiedAt: this.modifiedAt,
- items: items.map(({ json }) => this._jsonToRequest(json)!),
- };
+ return result;
} finally {
- this.mutex.shift();
+ this.queueStateMutex.shift();
}
}
- async prolongRequestLock(
- id: string,
- options: storage.ProlongRequestLockOptions,
- ): Promise<storage.ProlongRequestLockResult> {
- s.string().parse(id);
- const { lockSecs, forefront } = s
- .object({
- lockSecs: s.number(),
- forefront: s.boolean().optional().default(false),
- })
- .parse(options);
-
+ async getRequest(uniqueKey: string): Promise<storage.RequestOptions | undefined> {
+ s.string().parse(uniqueKey);
this.updateTimestamps(false);
-
- const request = this.requests.get(id);
- const internalRequest = await request?.get();
-
- if (!internalRequest) {
- throw new Error(`Request with ID ${id} not found in queue ${this.name ?? this.id}`);
- }
-
- const canProlong = (r: InternalRequest) => !!r.orderNo;
-
- if (!canProlong(internalRequest)) {
- throw new Error(`Request with ID ${id} has already been handled in queue ${this.name ?? this.id}`);
- }
-
- const unlockTimestamp = Math.abs(internalRequest.orderNo!) + lockSecs * 1000;
- internalRequest.orderNo = forefront ? -unlockTimestamp : unlockTimestamp;
-
- await request?.update(internalRequest);
- if (forefront) this.forefrontRequestIds.push(id);
-
- return {
- lockExpiresAt: new Date(unlockTimestamp),
- };
+ const id = uniqueKeyToRequestId(uniqueKey);
+ const json = (await this.requests.get(id)?.get())?.json;
+ return this._jsonToRequest(json);
}
- async deleteRequestLock(id: string, options: storage.DeleteRequestLockOptions = {}): Promise<void> {
- s.string().parse(id);
- const { forefront } = s
- .object({
- forefront: s.boolean().optional().default(false),
- })
- .parse(options);
-
+ async markRequestAsHandled(request: storage.UpdateRequestSchema): Promise<storage.QueueOperationInfo | null> {
+ requestShape.parse(request);
this.updateTimestamps(false);
- const request = this.requests.get(id);
- const internalRequest = await request?.get();
+ // Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so the shared
+ // `requests` map, `inProgressRequestIds` set and request counts stay consistent across the
+ // `await` points below.
+ await this.queueStateMutex.wait();
- if (!internalRequest) {
- throw new Error(`Request with ID ${id} not found in queue ${this.name ?? this.id}`);
- }
+ try {
+ const id = uniqueKeyToRequestId(request.uniqueKey);
- const start = Date.now();
+ const existingEntry = this.requests.get(id);
+ const existingRequest = await existingEntry?.get();
- // If there is no `orderNo` -> request was marked as handled
- const isLocked = (r: InternalRequest) => r.orderNo && (r.orderNo > start || r.orderNo < -start);
- if (!isLocked(internalRequest)) {
- throw new Error(`Request with ID ${id} is not locked in queue ${this.name ?? this.id}`);
- }
+ // The request must exist to be marked as handled. We intentionally do NOT require it to still
+ // be locked: a consumer whose processing outlived the lock (slow handler, GC/event-loop pause,
+ // a low `setExpectedRequestProcessingTimeSecs`) must still be able to mark its request handled,
+ // otherwise the request would be handed out again forever and the queue would never finish.
+ if (!existingRequest) {
+ return null;
+ }
- internalRequest.orderNo = forefront ? -start : start;
- if (forefront) this.forefrontRequestIds.push(id);
+ // A handled request has `orderNo === null`. Marking it again is an idempotent no-op.
+ const wasAlreadyHandled = existingRequest.orderNo === null;
- await request?.update(internalRequest);
- }
+ const handledAt = request.handledAt ?? new Date().toISOString();
+ const requestModel = this._createInternalRequest({ ...request, handledAt }, false);
- async addRequest(
- request: storage.RequestSchema,
- options: storage.RequestOptions = {},
- ): Promise<storage.QueueOperationInfo> {
- requestShapeWithoutId.parse(request);
- requestOptionsShape.parse(options);
+ const newEntry = createRequestQueueStorageImplementation({
+ persistStorage: this.client.persistStorage,
+ requestId: id,
+ storeDirectory: this.requestQueueDirectory,
+ });
+ await newEntry.update(requestModel);
+ this.requests.set(id, newEntry);
- const requestModel = this._createInternalRequest(request, options.forefront);
+ // The request is no longer in progress for this client.
+ this.inProgressRequestIds.delete(id);
- const existingRequestWithIdEntry = this.requests.get(requestModel.id);
+ if (!wasAlreadyHandled) {
+ this.pendingRequestCount -= 1;
+ this.handledRequestCount += 1;
+ }
- // We already have the request present, so we return information about it
- if (existingRequestWithIdEntry) {
- const existingRequestWithId = await existingRequestWithIdEntry.get();
- this.updateTimestamps(false);
+ this.updateTimestamps(true);
return {
- requestId: existingRequestWithId.id,
- wasAlreadyHandled: existingRequestWithId.orderNo === null,
+ requestId: id,
+ wasAlreadyHandled,
wasAlreadyPresent: true,
};
+ } finally {
+ this.queueStateMutex.shift();
}
-
- const newEntry = createRequestQueueStorageImplementation({
- persistStorage: this.client.persistStorage,
- requestId: requestModel.id,
- storeDirectory: this.requestQueueDirectory,
- });
-
- await newEntry.update(requestModel);
-
- this.requests.set(requestModel.id, newEntry);
- this.updateTimestamps(true);
-
- if (requestModel.orderNo) {
- this.pendingRequestCount += 1;
- } else {
- this.handledRequestCount += 1;
- }
-
- if (options.forefront) {
- this.forefrontRequestIds.push(requestModel.id);
- }
-
- return {
- requestId: requestModel.id,
- // We return wasAlreadyHandled: false even though the request may
- // have been added as handled, because that's how API behaves.
- wasAlreadyHandled: false,
- wasAlreadyPresent: false,
- };
}
- async batchAddRequests(
- requests: storage.RequestSchema[],
+ async reclaimRequest(
+ request: storage.UpdateRequestSchema,
options: storage.RequestOptions = {},
- ): Promise<storage.BatchAddRequestsResult> {
- batchRequestShapeWithoutId.parse(requests);
+ ): Promise<storage.QueueOperationInfo | null> {
+ requestShape.parse(request);
requestOptionsShape.parse(options);
+ this.updateTimestamps(false);
- const result: storage.BatchAddRequestsResult = {
- processedRequests: [],
- unprocessedRequests: [],
- };
-
- for (const model of requests) {
- const requestModel = this._createInternalRequest(model, options.forefront);
-
- const existingRequestWithIdEntry = this.requests.get(requestModel.id);
+ // Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so the shared
+ // `requests` map, `forefrontRequestIds` array and `inProgressRequestIds` set stay consistent
+ // across the `await` points below.
+ await this.queueStateMutex.wait();
- if (existingRequestWithIdEntry) {
- const existingRequestWithId = await existingRequestWithIdEntry.get();
+ try {
+ const id = uniqueKeyToRequestId(request.uniqueKey);
- result.processedRequests.push({
- requestId: existingRequestWithId.id,
- uniqueKey: existingRequestWithId.uniqueKey,
- wasAlreadyHandled: existingRequestWithId.orderNo === null,
- wasAlreadyPresent: true,
- });
+ const existingEntry = this.requests.get(id);
+ const existingRequest = await existingEntry?.get();
- continue;
+ // The request must exist and not already be handled to be reclaimed. As with
+ // `markRequestAsHandled`, we do NOT require it to still be locked — a consumer that failed
+ // after its lock expired must still be able to return the request to the queue (e.g. to honor
+ // a `forefront` reorder), rather than have the reclaim silently dropped.
+ if (!existingRequest || existingRequest.orderNo === null) {
+ return null;
}
+ // Reclaiming resets the `orderNo` to a fresh timestamp, releasing the lock and restoring the
+ // request to the queue (at the front if `forefront`).
+ const requestModel = this._createInternalRequest(request, options.forefront);
+
const newEntry = createRequestQueueStorageImplementation({
persistStorage: this.client.persistStorage,
- requestId: requestModel.id,
+ requestId: id,
storeDirectory: this.requestQueueDirectory,
});
-
await newEntry.update(requestModel);
+ this.requests.set(id, newEntry);
- this.requests.set(requestModel.id, newEntry);
-
- if (requestModel.orderNo) {
- this.pendingRequestCount += 1;
- } else {
- this.handledRequestCount += 1;
- }
+ // The request is no longer in progress for this client.
+ this.inProgressRequestIds.delete(id);
if (options.forefront) {
- this.forefrontRequestIds.push(requestModel.id);
+ this.forefrontRequestIds.push(id);
}
- result.processedRequests.push({
- requestId: requestModel.id,
- uniqueKey: requestModel.uniqueKey,
- // We return wasAlreadyHandled: false even though the request may
- // have been added as handled, because that's how API behaves.
+ this.updateTimestamps(true);
+
+ return {
+ requestId: id,
wasAlreadyHandled: false,
- wasAlreadyPresent: false,
- });
+ wasAlreadyPresent: true,
+ };
+ } finally {
+ this.queueStateMutex.shift();
}
-
- this.updateTimestamps(true);
-
- return result;
}
- async getRequest(id: string): Promise<storage.RequestOptions | undefined> {
- s.string().parse(id);
+ async isEmpty(): Promise<boolean> {
this.updateTimestamps(false);
- const json = (await this.requests.get(id)?.get())?.json;
- return this._jsonToRequest(json);
- }
- async updateRequest(
- request: storage.UpdateRequestSchema,
- options: storage.RequestOptions = {},
- ): Promise<storage.QueueOperationInfo> {
- requestShape.parse(request);
- requestOptionsShape.parse(options);
+ // "Empty" means there is nothing left to fetch right now — i.e. the next `fetchNextRequest`
+ // would return `null`. Requests that are currently locked (in progress) are intentionally NOT
+ // counted here: they are not fetchable, so the queue is empty from a consumer's point of view.
+ // Whether those in-progress requests mean crawling is not yet done is a separate question,
+ // answered by `isFinished`.
+ //
+ // `listPendingHead` prunes `forefrontRequestIds` as it scans, so we must hold the queue-state mutex to avoid
+ // racing a concurrent mutator (e.g. `addBatchOfRequests`) at its `await` points.
+ await this.queueStateMutex.wait();
- const requestModel = this._createInternalRequest(request, options.forefront);
+ try {
+ const { items } = await this.listPendingHead(1);
+ return items.length === 0;
+ } finally {
+ this.queueStateMutex.shift();
+ }
+ }
- // First we need to check the existing request to be
- // able to return information about its handled state.
+ async isFinished(): Promise<boolean> {
+ this.updateTimestamps(false);
- const existingRequestEntry = this.requests.get(requestModel.id);
+ // The queue is finished only when there is nothing left to fetch AND nothing currently locked
+ // (in progress) by any consumer. Counting locked requests is what allows a crawler to keep
+ // waiting while another consumer (possibly another process sharing this on-disk queue) still
+ // holds the last requests, instead of finishing prematurely. This mirrors the Apify platform
+ // shared client's `queueHasLockedRequests` signal.
+ //
+ // Detecting locked requests requires a full scan, hence the `detectLockedRequests` flag — unlike
+ // `fetchNextRequest`/`isEmpty`, which only need the head and can stop early.
+ //
+ // `listPendingHead` prunes `forefrontRequestIds` as it scans, so we must hold the queue-state mutex to avoid
+ // racing a concurrent mutator (e.g. `addBatchOfRequests`) at its `await` points.
+ await this.queueStateMutex.wait();
- // Undefined means that the request is not present in the queue.
- // We need to insert it, to behave the same as API.
- if (!existingRequestEntry) {
- return this.addRequest(request, options);
+ try {
+ const { items, hasLockedRequests } = await this.listPendingHead(1, true);
+ return items.length === 0 && !hasLockedRequests;
+ } finally {
+ this.queueStateMutex.shift();
}
+ }
- const existingRequest = await existingRequestEntry.get();
-
- const newEntry = createRequestQueueStorageImplementation({
- persistStorage: this.client.persistStorage,
- requestId: requestModel.id,
- storeDirectory: this.requestQueueDirectory,
- });
-
- await newEntry.update(requestModel);
+ /**
+ * Release the locks of all requests this client currently has in progress, returning them to the
+ * queue so they can be fetched again immediately.
+ *
+ * On the Apify platform, a run's locks are released automatically when it migrates or aborts, and
+ * the file-system storage does not lock at all — so only this in-memory client, which persists
+ * fake locks via `orderNo`, needs to clean up after itself. `MemoryStorage.teardown()` calls this
+ * for every cached queue at the end of the process so that a fetched-but-unhandled request is not
+ * stuck (waiting for its lock to expire) for the next consumer of the same on-disk queue.
+ */
+ async releaseOwnLocks(): Promise<void> {
+ if (this.inProgressRequestIds.size === 0) {
+ return;
+ }
- // When updating the request, we need to make sure that
- // the handled counts are updated correctly in all cases.
- this.requests.set(requestModel.id, newEntry);
+ await this.queueStateMutex.wait();
- const isRequestHandledStateChanging = typeof existingRequest.orderNo !== typeof requestModel.orderNo;
- const requestWasHandledBeforeUpdate = existingRequest.orderNo === null;
- const requestIsHandledAfterUpdate = requestModel.orderNo === null;
+ try {
+ const now = Date.now();
- if (isRequestHandledStateChanging) {
- this.pendingRequestCount += requestWasHandledBeforeUpdate ? 1 : -1;
- }
+ for (const id of this.inProgressRequestIds) {
+ const entry = this.requests.get(id);
+ const request = await entry?.get(true);
- if (isRequestHandledStateChanging && requestIsHandledAfterUpdate) {
- this.handledRequestCount += 1;
- }
+ // Skip requests that were handled or whose lock already expired/changed — we only undo
+ // locks we still hold.
+ if (!request || !isRequestLocked(request.orderNo, now)) {
+ continue;
+ }
- this.updateTimestamps(true);
+ // Reset the lock to a fresh timestamp, preserving the sign so the request keeps its
+ // original (forefront / normal) ordering once unlocked.
+ request.orderNo = now * (request.orderNo! > 0 ? 1 : -1);
+ await entry!.update(request);
+ }
- if (options.forefront && !requestIsHandledAfterUpdate) {
- this.forefrontRequestIds.push(requestModel.id);
+ this.inProgressRequestIds.clear();
+ this.updateTimestamps(true);
+ } finally {
+ this.queueStateMutex.shift();
}
-
- return {
- requestId: requestModel.id,
- wasAlreadyHandled: requestWasHandledBeforeUpdate,
- wasAlreadyPresent: true,
- };
}
toRequestQueueInfo(): storage.RequestQueueInfo {
diff --git a/packages/memory-storage/test/request-queue/forefront.test.ts b/packages/memory-storage/test/request-queue/forefront.test.ts
index 7cb02e608..0553d87c4 100644
--- a/packages/memory-storage/test/request-queue/forefront.test.ts
+++ b/packages/memory-storage/test/request-queue/forefront.test.ts
@@ -1,9 +1,26 @@
+import { rm } from 'node:fs/promises';
+import { resolve } from 'node:path';
import { setTimeout as sleep } from 'node:timers/promises';
import { MemoryStorage } from '@crawlee/memory-storage';
import type { RequestQueueClient } from '@crawlee/types';
-describe('RequestQueueV1 respects `forefront` in `listHead`', () => {
+/**
+ * Drains the queue via `fetchNextRequest`, marking each request as handled, and returns the
+ * pathnames in the order they were served.
+ */
+async function fetchOrder(client: RequestQueueClient): Promise<string[]> {
+ const order: string[] = [];
+
+ for (let request = await client.fetchNextRequest(); request !== null; request = await client.fetchNextRequest()) {
+ order.push(new URL(request.url).pathname);
+ await client.markRequestAsHandled({ ...request, id: request.id! });
+ }
+
+ return order;
+}
+
+describe('RequestQueue respects `forefront` when fetching requests', () => {
const storage = new MemoryStorage({
persistStorage: false,
});
@@ -19,49 +36,39 @@ describe('RequestQueueV1 respects `forefront` in `listHead`', () => {
});
test('requests without `forefront` respect sequential order', async () => {
- await requestQueue.addRequest({ url: 'http://example.com/1', uniqueKey: '1' });
+ await requestQueue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
// Waiting a few ms is required since we use Date.now() to compute orderNo
await sleep(2);
- await requestQueue.addRequest({ url: 'http://example.com/2', uniqueKey: '2' });
+ await requestQueue.addBatchOfRequests([{ url: 'http://example.com/2', uniqueKey: '2' }]);
- const { items } = await requestQueue.listHead();
-
- expect(items).toHaveLength(2);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/1', '/2']);
+ expect(await fetchOrder(requestQueue)).toEqual(['/1', '/2']);
});
test('`forefront` requests are prioritized', async () => {
- await requestQueue.addRequest({ url: 'http://example.com/1', uniqueKey: '1' });
+ await requestQueue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
// Waiting a few ms is required since we use Date.now() to compute orderNo
await sleep(2);
- await requestQueue.addRequest({ url: 'http://example.com/2', uniqueKey: '2' }, { forefront: true });
-
- const { items } = await requestQueue.listHead();
+ await requestQueue.addBatchOfRequests([{ url: 'http://example.com/2', uniqueKey: '2' }], { forefront: true });
- expect(items).toHaveLength(2);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/2', '/1']);
+ expect(await fetchOrder(requestQueue)).toEqual(['/2', '/1']);
});
- test('`limit` retains the global `forefront` ordering', async () => {
- await requestQueue.addRequest({ url: 'http://example.com/1', uniqueKey: '1' });
+ test('global `forefront` ordering is preserved across several inserts', async () => {
+ await requestQueue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
await sleep(2);
- await requestQueue.addRequest({ url: 'http://example.com/2', uniqueKey: '2' }, { forefront: true });
+ await requestQueue.addBatchOfRequests([{ url: 'http://example.com/2', uniqueKey: '2' }], { forefront: true });
await sleep(2);
- await requestQueue.addRequest({ url: 'http://example.com/3', uniqueKey: '3' }, { forefront: true });
-
- // List only 2 items (smaller than the total queue size)
- const { items } = await requestQueue.listHead({ limit: 2 });
+ await requestQueue.addBatchOfRequests([{ url: 'http://example.com/3', uniqueKey: '3' }], { forefront: true });
- expect(items).toHaveLength(2);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/3', '/2']);
+ expect(await fetchOrder(requestQueue)).toEqual(['/3', '/2', '/1']);
});
- test('`batchAddRequests` respects `forefront`', async () => {
- await requestQueue.addRequest({ url: 'http://example.com/3', uniqueKey: '3' });
+ test('`addBatchOfRequests` respects `forefront`', async () => {
+ await requestQueue.addBatchOfRequests([{ url: 'http://example.com/3', uniqueKey: '3' }]);
await sleep(2);
- await requestQueue.batchAddRequests(
+ await requestQueue.addBatchOfRequests(
[
{ url: 'http://example.com/1', uniqueKey: '1' },
{ url: 'http://example.com/2', uniqueKey: '2' },
@@ -69,438 +76,193 @@ describe('RequestQueueV1 respects `forefront` in `listHead`', () => {
{ forefront: true },
);
- const { items } = await requestQueue.listHead();
-
- expect(items).toHaveLength(3);
+ const order = await fetchOrder(requestQueue);
+ expect(order).toHaveLength(3);
+ // Both forefront requests come before the original; their relative order is arbitrary.
+ expect(order[2]).toEqual('/3');
expect([
['/2', '/1', '/3'],
['/1', '/2', '/3'],
- ]).toContainEqual(items.map((x) => new URL(x.url).pathname));
+ ]).toContainEqual(order);
});
- test('`batchAddRequests` respects `forefront` (with `limit`)', async () => {
- await requestQueue.addRequest({ url: 'http://example.com/3', uniqueKey: '3' });
+ test('a reclaimed request is served again', async () => {
+ await requestQueue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
- await sleep(2);
+ const first = await requestQueue.fetchNextRequest();
+ expect(first!.url).toEqual('http://example.com/1');
- await requestQueue.batchAddRequests(
- [
- { url: 'http://example.com/1', uniqueKey: '1' },
- { url: 'http://example.com/2', uniqueKey: '2' },
- ],
- { forefront: true },
- );
+ // Reclaiming a fetched (in-progress) request returns it to the queue.
+ await requestQueue.reclaimRequest({ ...first!, id: first!.id! });
- const { items } = await requestQueue.listHead({ limit: 2 });
-
- expect(items).toHaveLength(2);
- expect([
- ['/2', '/1'],
- ['/1', '/2'],
- ]).toContainEqual(items.map((x) => new URL(x.url).pathname));
+ const second = await requestQueue.fetchNextRequest();
+ expect(second!.url).toEqual('http://example.com/1');
});
- test('`updateRequest` respects `forefront` (with `limit`)', async () => {
- const req1 = await requestQueue.addRequest({ url: 'http://example.com/1', uniqueKey: '1' });
- await sleep(2);
- const req2 = await requestQueue.addRequest({ url: 'http://example.com/2', uniqueKey: '2' });
- await sleep(2);
- const req3 = await requestQueue.addRequest(
- { url: 'http://example.com/3', uniqueKey: '3' },
- { forefront: true },
- );
-
- let { items } = await requestQueue.listHead();
-
- expect(items).toHaveLength(3);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/3', '/1', '/2']);
+ test('a reclaimed `forefront` request jumps to the front', async () => {
+ await requestQueue.addBatchOfRequests([
+ { url: 'http://example.com/1', uniqueKey: '1' },
+ { url: 'http://example.com/2', uniqueKey: '2' },
+ ]);
- await requestQueue.updateRequest(
- {
- id: req2.requestId,
- url: 'http://example.com/2',
- uniqueKey: '2',
- },
- { forefront: true },
- );
+ const first = await requestQueue.fetchNextRequest();
+ expect(first!.url).toEqual('http://example.com/1');
- ({ items } = await requestQueue.listHead());
+ await requestQueue.reclaimRequest({ ...first!, id: first!.id! }, { forefront: true });
- expect(items).toHaveLength(3);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/2', '/3', '/1']);
+ const next = await requestQueue.fetchNextRequest();
+ expect(next!.url).toEqual('http://example.com/1');
+ });
- await requestQueue.updateRequest(
- {
- id: req3.requestId,
- url: 'http://example.com/3',
- uniqueKey: '3',
- },
- { forefront: true },
- );
+ test('handling all requests empties the queue', async () => {
+ await requestQueue.addBatchOfRequests([
+ { url: 'http://example.com/1', uniqueKey: '1' },
+ { url: 'http://example.com/2', uniqueKey: '2' },
+ { url: 'http://example.com/3', uniqueKey: '3' },
+ ]);
- await requestQueue.updateRequest(
- {
- id: req1.requestId,
- url: 'http://example.com/1',
- uniqueKey: '1',
- },
- { forefront: true },
- );
+ expect(await requestQueue.isEmpty()).toBe(false);
- ({ items } = await requestQueue.listHead({ limit: 2 }));
+ await fetchOrder(requestQueue);
- expect(items).toHaveLength(2);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/1', '/3']);
+ expect(await requestQueue.isEmpty()).toBe(true);
+ expect(await requestQueue.fetchNextRequest()).toBeNull();
});
- test('handling `forefront` requests works as expected', async () => {
- await requestQueue.addRequest({ url: 'http://example.com/1', uniqueKey: '1' });
- await sleep(2);
- await requestQueue.addRequest({ url: 'http://example.com/2', uniqueKey: '2' }, { forefront: true });
- await sleep(2);
- await requestQueue.addRequest({ url: 'http://example.com/3', uniqueKey: '3' }, { forefront: true });
-
- let { items } = await requestQueue.listHead();
-
- expect(items).toHaveLength(3);
- for (const item of items.slice(0, 2)) {
- await requestQueue.updateRequest({
- id: item.id,
- url: item.url,
- uniqueKey: item.uniqueKey,
- handledAt: new Date().toISOString(),
- });
- }
+ test('a fetched (locked) request leaves the queue empty but unfinished until it is handled', async () => {
+ await requestQueue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
- await requestQueue.updateRequest(
- {
- id: items[2].id,
- url: items[2].url,
- uniqueKey: items[2].uniqueKey,
- handledAt: new Date().toISOString(),
- },
- {
- forefront: true,
- },
- );
+ const request = await requestQueue.fetchNextRequest();
+ expect(request).not.toBeNull();
- ({ items } = await requestQueue.listHead());
+ // The request is locked (in progress), not handled. There is nothing left to fetch, so the
+ // queue is empty — but it is not finished. The "not finished" signal is what stops a crawler
+ // from shutting down while a request is still being processed by some consumer.
+ expect(await requestQueue.isEmpty()).toBe(true);
+ expect(await requestQueue.isFinished()).toBe(false);
- expect(items).toHaveLength(0);
+ await requestQueue.markRequestAsHandled({ ...request!, id: request!.id! });
+ expect(await requestQueue.isEmpty()).toBe(true);
+ expect(await requestQueue.isFinished()).toBe(true);
});
});
-describe('RequestQueueV2 respects `forefront` in `listAndLockHead`', () => {
- const storage = new MemoryStorage({
- persistStorage: false,
- });
+describe('RequestQueue locks fetched requests', () => {
+ const storage = new MemoryStorage({ persistStorage: false });
let requestQueue: RequestQueueClient;
beforeEach(async () => {
- requestQueue = await storage.createRequestQueueClient({ name: 'forefront-v2' });
+ requestQueue = await storage.createRequestQueueClient({ name: 'locking' });
});
afterEach(async () => {
await requestQueue.drop();
});
- test('requests without `forefront` respect sequential order', async () => {
- await requestQueue.addRequest({ url: 'http://example.com/1', uniqueKey: '1' });
- // Waiting a few ms is required since we use Date.now() to compute orderNo
- await sleep(2);
- await requestQueue.addRequest({ url: 'http://example.com/2', uniqueKey: '2' });
-
- const { items } = await requestQueue.listAndLockHead({ lockSecs: 10 });
-
- expect(items).toHaveLength(2);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/1', '/2']);
- });
-
- test('`forefront` requests are prioritized', async () => {
- await requestQueue.addRequest({ url: 'http://example.com/1', uniqueKey: '1' });
- // Waiting a few ms is required since we use Date.now() to compute orderNo
- await sleep(2);
- await requestQueue.addRequest({ url: 'http://example.com/2', uniqueKey: '2' }, { forefront: true });
-
- const { items } = await requestQueue.listAndLockHead({ lockSecs: 10 });
-
- expect(items).toHaveLength(2);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/2', '/1']);
- });
-
- test('`limit` retains the global `forefront` ordering', async () => {
- await requestQueue.addRequest({ url: 'http://example.com/1', uniqueKey: '1' });
- await sleep(2);
- await requestQueue.addRequest({ url: 'http://example.com/2', uniqueKey: '2' }, { forefront: true });
- await sleep(2);
- await requestQueue.addRequest({ url: 'http://example.com/3', uniqueKey: '3' }, { forefront: true });
-
- // List only 2 items (smaller than the total queue size)
- const { items } = await requestQueue.listAndLockHead({ limit: 2, lockSecs: 10 });
-
- expect(items).toHaveLength(2);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/3', '/2']);
- });
-
- test('`batchAddRequests` respects `forefront`', async () => {
- await requestQueue.addRequest({ url: 'http://example.com/3', uniqueKey: '3' });
-
- await sleep(2);
-
- await requestQueue.batchAddRequests(
- [
- { url: 'http://example.com/1', uniqueKey: '1' },
- { url: 'http://example.com/2', uniqueKey: '2' },
- ],
- { forefront: true },
- );
-
- const { items } = await requestQueue.listAndLockHead({ lockSecs: 10 });
-
- expect(items).toHaveLength(3);
- expect([
- ['/2', '/1', '/3'],
- ['/1', '/2', '/3'],
- ]).toContainEqual(items.map((x) => new URL(x.url).pathname));
- });
-
- test('`batchAddRequests` respects `forefront` (with `limit`)', async () => {
- await requestQueue.addRequest({ url: 'http://example.com/3', uniqueKey: '3' });
-
- await sleep(2);
-
- await requestQueue.batchAddRequests(
- [
- { url: 'http://example.com/1', uniqueKey: '1' },
- { url: 'http://example.com/2', uniqueKey: '2' },
- ],
- { forefront: true },
- );
-
- const { items } = await requestQueue.listAndLockHead({ limit: 2, lockSecs: 10 });
-
- expect(items).toHaveLength(2);
- expect([
- ['/2', '/1'],
- ['/1', '/2'],
- ]).toContainEqual(items.map((x) => new URL(x.url).pathname));
- });
-
- test('requests with expired locks keep the original ordering', async () => {
+ test('a fetched request becomes available again after its lock expires', async () => {
vitest.useFakeTimers();
- await requestQueue.addRequest({ url: 'http://example.com/3', uniqueKey: '3' });
-
- await requestQueue.addRequest({ url: 'http://example.com/2', uniqueKey: '2' }, { forefront: true });
- await requestQueue.addRequest({ url: 'http://example.com/1', uniqueKey: '1' }, { forefront: true });
-
- await requestQueue.batchAddRequests([
- { url: 'http://example.com/4', uniqueKey: '4' },
- { url: 'http://example.com/5', uniqueKey: '5' },
- ]);
-
- let { items } = await requestQueue.listAndLockHead({ limit: 25, lockSecs: 10 });
-
- expect(items).toHaveLength(5);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/1', '/2', '/3', '/4', '/5']);
-
- ({ items } = await requestQueue.listAndLockHead({ limit: 25, lockSecs: 10 }));
- expect(items).toHaveLength(0);
-
- vitest.advanceTimersByTime(10001);
+ try {
+ await requestQueue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
- ({ items } = await requestQueue.listAndLockHead({ limit: 25, lockSecs: 10 }));
+ const first = await requestQueue.fetchNextRequest();
+ expect(first!.uniqueKey).toBe('1');
- expect(items).toHaveLength(5);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/1', '/2', '/3', '/4', '/5']);
+ // While locked, the request is not handed out again.
+ expect(await requestQueue.fetchNextRequest()).toBeNull();
- vitest.useRealTimers();
- });
-
- test('`deleteRequestLock` keeps the original ordering', async () => {
- await requestQueue.addRequest({ url: 'http://example.com/3', uniqueKey: '3' });
-
- await requestQueue.addRequest({ url: 'http://example.com/2', uniqueKey: '2' }, { forefront: true });
- await requestQueue.addRequest({ url: 'http://example.com/1', uniqueKey: '1' }, { forefront: true });
-
- await requestQueue.batchAddRequests([
- { url: 'http://example.com/4', uniqueKey: '4' },
- { url: 'http://example.com/5', uniqueKey: '5' },
- ]);
-
- let { items } = await requestQueue.listAndLockHead({ limit: 25, lockSecs: 10 });
-
- expect(items).toHaveLength(5);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/1', '/2', '/3', '/4', '/5']);
-
- await Promise.all([
- requestQueue.deleteRequestLock(items[0].id),
- requestQueue.deleteRequestLock(items[1].id),
- requestQueue.deleteRequestLock(items[2].id),
- ]);
-
- ({ items } = await requestQueue.listAndLockHead({ limit: 25, lockSecs: 10 }));
+ // After the lock expires (default 3 minutes), the request is fetchable again — this is what
+ // prevents a crashed consumer from blocking its requests forever.
+ vitest.advanceTimersByTime(3 * 60 * 1000 + 1000);
- expect(items).toHaveLength(3);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/1', '/2', '/3']);
+ const retried = await requestQueue.fetchNextRequest();
+ expect(retried!.uniqueKey).toBe('1');
+ } finally {
+ vitest.useRealTimers();
+ }
});
+});
- test('`prolongRequestLock` keeps the original ordering', async () => {
- vitest.useFakeTimers();
-
- await requestQueue.batchAddRequests([
- { url: 'http://example.com/3', uniqueKey: '3' },
- { url: 'http://example.com/4', uniqueKey: '4' },
- { url: 'http://example.com/5', uniqueKey: '5' },
- ]);
-
- await requestQueue.addRequest({ url: 'http://example.com/2', uniqueKey: '2' }, { forefront: true });
- await requestQueue.addRequest({ url: 'http://example.com/1', uniqueKey: '1' }, { forefront: true });
-
- let { items } = await requestQueue.listAndLockHead({ limit: 25, lockSecs: 10 });
-
- expect(items).toHaveLength(5);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/1', '/2', '/3', '/4', '/5']);
-
- vitest.advanceTimersByTime(9999);
-
- await requestQueue.prolongRequestLock(items[0].id, { lockSecs: 10 });
- await requestQueue.prolongRequestLock(items[3].id, { lockSecs: 10 });
-
- vitest.advanceTimersByTime(1001);
-
- ({ items } = await requestQueue.listAndLockHead({ limit: 25, lockSecs: 10 }));
- expect(items).toHaveLength(3);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/2', '/3', '/5']);
-
- vitest.advanceTimersByTime(10001);
-
- ({ items } = await requestQueue.listAndLockHead({ limit: 25, lockSecs: 10 }));
- expect(items).toHaveLength(5);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/1', '/2', '/3', '/4', '/5']);
+describe('RequestQueue locking is visible across clients sharing on-disk storage', () => {
+ const tmpLocation = resolve(import.meta.dirname, './tmp/req-queue-cross-process');
+ // Two independent storage instances over the same directory emulate two separate processes.
+ const storageA = new MemoryStorage({ localDataDirectory: tmpLocation, persistStorage: true });
+ const storageB = new MemoryStorage({ localDataDirectory: tmpLocation, persistStorage: true });
- vitest.useRealTimers();
+ afterAll(async () => {
+ await rm(tmpLocation, { force: true, recursive: true });
});
- test('`deleteRequestLock.forefront` works as expected', async () => {
- vitest.useFakeTimers();
-
- await requestQueue.batchAddRequests([
+ test('two clients on the same queue never fetch the same request', async () => {
+ const clientA = await storageA.createRequestQueueClient({ name: 'shared' });
+ await clientA.addBatchOfRequests([
{ url: 'http://example.com/1', uniqueKey: '1' },
{ url: 'http://example.com/2', uniqueKey: '2' },
- { url: 'http://example.com/3', uniqueKey: '3' },
]);
- let { items } = await requestQueue.listAndLockHead({ limit: 25, lockSecs: 10 });
-
- expect(items).toHaveLength(3);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/1', '/2', '/3']);
-
- await requestQueue.deleteRequestLock(items[2].id, { forefront: true });
- await requestQueue.deleteRequestLock(items[1].id, { forefront: true });
+ const clientB = await storageB.createRequestQueueClient({ name: 'shared' });
- vitest.advanceTimersByTime(10001);
+ const fromA = await clientA.fetchNextRequest();
+ const fromB = await clientB.fetchNextRequest();
- ({ items } = await requestQueue.listAndLockHead({ limit: 25, lockSecs: 10 }));
- expect(items).toHaveLength(3);
+ expect(fromA).not.toBeNull();
+ expect(fromB).not.toBeNull();
+ // The lock written by one client is observed by the other, so they get distinct requests.
+ expect(fromA!.uniqueKey).not.toBe(fromB!.uniqueKey);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/2', '/3', '/1']);
+ // Both requests are now locked, so neither client can fetch anything more.
+ expect(await clientA.fetchNextRequest()).toBeNull();
+ expect(await clientB.fetchNextRequest()).toBeNull();
- vitest.useRealTimers();
+ await clientA.drop();
});
- test('`prolongRequestLock.forefront` works as expected', async () => {
- vitest.useFakeTimers();
-
- await requestQueue.batchAddRequests([
- { url: 'http://example.com/1', uniqueKey: '1' },
- { url: 'http://example.com/2', uniqueKey: '2' },
- { url: 'http://example.com/3', uniqueKey: '3' },
- ]);
-
- let { items } = await requestQueue.listAndLockHead({ limit: 25, lockSecs: 10 });
-
- expect(items).toHaveLength(3);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/1', '/2', '/3']);
-
- vitest.advanceTimersByTime(1000);
-
- await requestQueue.prolongRequestLock(items[2].id, { lockSecs: 10, forefront: true });
+ test('a client does not report the queue finished while another client holds the last request', async () => {
+ const clientA = await storageA.createRequestQueueClient({ name: 'shared-is-empty' });
+ await clientA.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
- vitest.advanceTimersByTime(9001);
+ const clientB = await storageB.createRequestQueueClient({ name: 'shared-is-empty' });
- ({ items } = await requestQueue.listAndLockHead({ limit: 25, lockSecs: 10 }));
+ // Client A fetches (and thus locks) the only request.
+ const fromA = await clientA.fetchNextRequest();
+ expect(fromA).not.toBeNull();
- expect(items).toHaveLength(2);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/1', '/2']);
+ // Client B has nothing it can fetch right now, so from its point of view the queue is empty...
+ expect(await clientB.fetchNextRequest()).toBeNull();
+ expect(await clientB.isEmpty()).toBe(true);
+ // ...but the request still exists and is merely locked by A, so B must NOT consider the queue
+ // finished — otherwise the crawler driving B could shut down while A is still processing.
+ expect(await clientB.isFinished()).toBe(false);
- vitest.advanceTimersByTime(10001);
+ // Once A handles the request, it is gone for good and B sees a finished queue.
+ await clientA.markRequestAsHandled({ ...fromA!, id: fromA!.id! });
+ expect(await clientB.isEmpty()).toBe(true);
+ expect(await clientB.isFinished()).toBe(true);
- ({ items } = await requestQueue.listAndLockHead({ limit: 25, lockSecs: 10 }));
- expect(items).toHaveLength(3);
-
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/3', '/1', '/2']);
-
- vitest.useRealTimers();
+ await clientA.drop();
});
- test('`updateRequest` respects `forefront` (with `limit`)', async () => {
- vitest.useFakeTimers();
-
- const req1 = await requestQueue.addRequest({ url: 'http://example.com/1', uniqueKey: '1' });
- const req2 = await requestQueue.addRequest({ url: 'http://example.com/2', uniqueKey: '2' });
- const req3 = await requestQueue.addRequest(
- { url: 'http://example.com/3', uniqueKey: '3' },
- { forefront: true },
- );
-
- let { items } = await requestQueue.listAndLockHead({ lockSecs: 1 });
-
- expect(items).toHaveLength(3);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/3', '/1', '/2']);
-
- vitest.advanceTimersByTime(1001);
+ test('teardown releases this client locks so another client can fetch immediately', async () => {
+ const clientA = await storageA.createRequestQueueClient({ name: 'shared-teardown' });
+ await clientA.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
- await requestQueue.updateRequest(
- {
- id: req2.requestId,
- url: 'http://example.com/2',
- uniqueKey: '2',
- },
- { forefront: true },
- );
-
- ({ items } = await requestQueue.listAndLockHead({ lockSecs: 1 }));
-
- expect(items).toHaveLength(3);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/2', '/3', '/1']);
-
- vitest.advanceTimersByTime(1001);
+ // Client A fetches (locks) the request, then the process tears down without handling it.
+ const fromA = await clientA.fetchNextRequest();
+ expect(fromA).not.toBeNull();
- await requestQueue.updateRequest(
- {
- id: req3.requestId,
- url: 'http://example.com/3',
- uniqueKey: '3',
- },
- { forefront: true },
- );
-
- await requestQueue.updateRequest(
- {
- id: req1.requestId,
- url: 'http://example.com/1',
- uniqueKey: '1',
- },
- { forefront: true },
- );
+ const clientB = await storageB.createRequestQueueClient({ name: 'shared-teardown' });
+ // While A holds the lock, B cannot fetch the request.
+ expect(await clientB.fetchNextRequest()).toBeNull();
- ({ items } = await requestQueue.listAndLockHead({ lockSecs: 1, limit: 2 }));
+ // Tearing down A's storage releases its locks (instead of leaving them until the 3-minute
+ // expiry), so B can pick the request up right away.
+ await storageA.teardown();
- expect(items).toHaveLength(2);
- expect(items.map((x) => new URL(x.url).pathname)).toEqual(['/1', '/3']);
+ const fromB = await clientB.fetchNextRequest();
+ expect(fromB).not.toBeNull();
+ expect(fromB!.uniqueKey).toBe('1');
- vitest.useRealTimers();
+ await clientB.drop();
});
});
diff --git a/packages/memory-storage/test/request-queue/handledRequestCount-should-update.test.ts b/packages/memory-storage/test/request-queue/handledRequestCount-should-update.test.ts
index fd3987f7a..07578ffce 100644
--- a/packages/memory-storage/test/request-queue/handledRequestCount-should-update.test.ts
+++ b/packages/memory-storage/test/request-queue/handledRequestCount-should-update.test.ts
@@ -12,14 +12,16 @@ describe('RequestQueue handledRequestCount should update', () => {
requestQueue = await storage.createRequestQueueClient({ name: 'handledRequestCount' });
});
- test('after updating the request, it should increment the handledRequestCount', async () => {
- const { requestId } = await requestQueue.addRequest({ url: 'http://example.com/1', uniqueKey: '1' });
+ test('after marking a request as handled, it should increment the handledRequestCount', async () => {
+ await requestQueue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
- await requestQueue.updateRequest({
+ const request = await requestQueue.fetchNextRequest();
+ expect(request).not.toBeNull();
+
+ await requestQueue.markRequestAsHandled({
url: 'http://example.com/1',
uniqueKey: '1',
- id: requestId,
- handledAt: new Date().toISOString(),
+ id: request!.id!,
});
const updatedStatistics = await requestQueue.getMetadata();
@@ -27,11 +29,13 @@ describe('RequestQueue handledRequestCount should update', () => {
});
test('adding an already handled request should increment the handledRequestCount', async () => {
- await requestQueue.addRequest({
- url: 'http://example.com/2',
- uniqueKey: '2',
- handledAt: new Date().toISOString(),
- });
+ await requestQueue.addBatchOfRequests([
+ {
+ url: 'http://example.com/2',
+ uniqueKey: '2',
+ handledAt: new Date().toISOString(),
+ },
+ ]);
const updatedStatistics = await requestQueue.getMetadata();
expect(updatedStatistics.handledRequestCount).toEqual(2);
diff --git a/packages/memory-storage/test/request-queue/ignore-non-json-files.test.ts b/packages/memory-storage/test/request-queue/ignore-non-json-files.test.ts
index 24bf710fd..8b9f54692 100644
--- a/packages/memory-storage/test/request-queue/ignore-non-json-files.test.ts
+++ b/packages/memory-storage/test/request-queue/ignore-non-json-files.test.ts
@@ -58,7 +58,12 @@ describe('when falling back to fs, Request queue should ignore non-JSON files',
expect(defaultQueueInfo.name).toEqual('default');
- const requests = await defaultQueue.listHead();
- expect(requests.items).toHaveLength(1);
+ // Only the single valid JSON-backed request should be fetchable; the non-JSON files are ignored.
+ const first = await defaultQueue.fetchNextRequest();
+ expect(first).not.toBeNull();
+ expect(first!.url).toEqual('http://example.com');
+
+ const second = await defaultQueue.fetchNextRequest();
+ expect(second).toBeNull();
});
});
diff --git a/packages/memory-storage/test/request-queue/request-lock-secs.test.ts b/packages/memory-storage/test/request-queue/request-lock-secs.test.ts
new file mode 100644
index 000000000..4b9d55ea4
--- /dev/null
+++ b/packages/memory-storage/test/request-queue/request-lock-secs.test.ts
@@ -0,0 +1,102 @@
+import { MemoryStorage } from '@crawlee/memory-storage';
+import type { RequestQueueClient } from '@crawlee/types';
+
+describe('RequestQueue request lock duration', () => {
+ beforeEach(() => {
+ vitest.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vitest.useRealTimers();
+ });
+
+ test('a fetched request stays locked for the default 3 minutes, then becomes fetchable again', async () => {
+ const storage = new MemoryStorage({ persistStorage: false });
+ const queue: RequestQueueClient = await storage.createRequestQueueClient({ name: 'default-lock' });
+
+ await queue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
+
+ const fetched = await queue.fetchNextRequest();
+ expect(fetched).not.toBeNull();
+
+ // While the lock is held, the request must not be handed out again. There is nothing fetchable,
+ // so the queue is empty — but the locked request means it is not yet finished.
+ expect(await queue.fetchNextRequest()).toBeNull();
+ expect(await queue.isEmpty()).toBe(true);
+ expect(await queue.isFinished()).toBe(false);
+
+ // Just before the default lock expires, it is still locked.
+ vitest.advanceTimersByTime(3 * 60 * 1000 - 1000);
+ expect(await queue.fetchNextRequest()).toBeNull();
+
+ // Once the lock expires, the same request is fetchable again.
+ vitest.advanceTimersByTime(2 * 1000);
+ const refetched = await queue.fetchNextRequest();
+ expect(refetched).not.toBeNull();
+ expect(refetched!.uniqueKey).toBe('1');
+ });
+
+ test('setExpectedRequestProcessingTimeSecs changes how long a fetched request stays locked', async () => {
+ const storage = new MemoryStorage({ persistStorage: false });
+ const queue: RequestQueueClient = await storage.createRequestQueueClient({ name: 'set-lock-secs' });
+
+ // Raise the lock well above the 3-minute default — expect requests to stay locked for 10 minutes.
+ queue.setExpectedRequestProcessingTimeSecs!(600);
+
+ await queue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
+ expect(await queue.fetchNextRequest()).not.toBeNull();
+
+ // After the default 3-minute lock would have expired, the request is still locked.
+ vitest.advanceTimersByTime(4 * 60 * 1000);
+ expect(await queue.fetchNextRequest()).toBeNull();
+
+ // Only after the configured 10-minute lock expires is it fetchable again.
+ vitest.advanceTimersByTime(6 * 60 * 1000 + 1000);
+ expect((await queue.fetchNextRequest())?.uniqueKey).toBe('1');
+ });
+
+ test('a request can still be marked as handled after its lock has expired', async () => {
+ const storage = new MemoryStorage({ persistStorage: false });
+ const queue: RequestQueueClient = await storage.createRequestQueueClient({ name: 'handle-after-expiry' });
+
+ await queue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
+
+ const fetched = await queue.fetchNextRequest();
+ expect(fetched).not.toBeNull();
+
+ // The consumer takes longer than the lock duration to process the request.
+ vitest.advanceTimersByTime(3 * 60 * 1000 + 1000);
+
+ // Marking it handled must still succeed — a slow consumer should not be penalized.
+ const result = await queue.markRequestAsHandled({ ...fetched!, id: fetched!.id as string });
+ expect(result).not.toBeNull();
+
+ // The request must be counted as handled and never handed out again.
+ const metadata = await queue.getMetadata();
+ expect(metadata.handledRequestCount).toBe(1);
+ expect(metadata.pendingRequestCount).toBe(0);
+ expect(await queue.isEmpty()).toBe(true);
+ expect(await queue.isFinished()).toBe(true);
+ expect(await queue.fetchNextRequest()).toBeNull();
+ });
+
+ test('a request can still be reclaimed after its lock has expired', async () => {
+ const storage = new MemoryStorage({ persistStorage: false });
+ const queue: RequestQueueClient = await storage.createRequestQueueClient({ name: 'reclaim-after-expiry' });
+
+ await queue.addBatchOfRequests([{ url: 'http://example.com/1', uniqueKey: '1' }]);
+
+ const fetched = await queue.fetchNextRequest();
+ expect(fetched).not.toBeNull();
+
+ // The consumer fails after holding the request longer than the lock duration.
+ vitest.advanceTimersByTime(3 * 60 * 1000 + 1000);
+
+ const result = await queue.reclaimRequest({ ...fetched!, id: fetched!.id as string }, { forefront: true });
+ expect(result).not.toBeNull();
+
+ // The reclaimed request is still pending and fetchable again.
+ expect(await queue.isEmpty()).toBe(false);
+ expect((await queue.fetchNextRequest())?.uniqueKey).toBe('1');
+ });
+});
diff --git a/packages/types/src/storages.ts b/packages/types/src/storages.ts
index 948af016b..6c0da3cdf 100644
--- a/packages/types/src/storages.ts
+++ b/packages/types/src/storages.ts
@@ -179,50 +179,6 @@ export interface RequestQueueInfo {
stats?: RequestQueueStats;
}
-export interface RequestQueueHeadItem {
- id: string;
- retryCount: number;
- uniqueKey: string;
- url: string;
- method: AllowedHttpMethods;
-}
-
-export interface QueueHead {
- limit: number;
- queueModifiedAt: Date;
- hadMultipleClients?: boolean;
- items: RequestQueueHeadItem[];
-}
-
-export interface ListOptions {
- /**
- * @default 100
- */
- limit?: number;
-}
-
-export interface ListAndLockOptions extends ListOptions {
- lockSecs: number;
-}
-
-export interface ListAndLockHeadResult extends QueueHead {
- lockSecs: number;
- queueHasLockedRequests?: boolean;
-}
-
-export interface ProlongRequestLockOptions {
- lockSecs: number;
- forefront?: boolean;
-}
-
-export interface ProlongRequestLockResult {
- lockExpiresAt: Date;
-}
-
-export interface DeleteRequestLockOptions {
- forefront?: boolean;
-}
-
export interface RequestOptions {
forefront?: boolean;
[k: string]: unknown;
@@ -265,6 +221,14 @@ export interface BatchAddRequestsResult {
unprocessedRequests: UnprocessedRequest[];
}
+/**
+ * Operations on a single request queue.
+ *
+ * A backend implementation owns all request bookkeeping (pending, in-progress, handled). Any
+ * coordination required between multiple distributed clients accessing the same queue (e.g. request
+ * locking on the Apify platform) is an internal concern of the implementation and is not exposed on
+ * this interface.
+ */
export interface RequestQueueClient {
/**
* Returns metadata about the request queue (id, name, timestamps, request counts, etc.).
@@ -281,14 +245,92 @@ export interface RequestQueueClient {
/** Remove all requests from the queue but keep the queue itself. */
purge(): Promise<void>;
- listHead(options?: ListOptions): Promise<QueueHead>;
- addRequest(request: RequestSchema, options?: RequestOptions): Promise<QueueOperationInfo>;
- batchAddRequests(requests: RequestSchema[], options?: RequestOptions): Promise<BatchAddRequestsResult>;
- getRequest(id: string): Promise<RequestOptions | undefined>;
- updateRequest(request: UpdateRequestSchema, options?: RequestOptions): Promise<QueueOperationInfo>;
- listAndLockHead(options: ListAndLockOptions): Promise<ListAndLockHeadResult>;
- prolongRequestLock(id: string, options: ProlongRequestLockOptions): Promise<ProlongRequestLockResult>;
- deleteRequestLock(id: string, options?: DeleteRequestLockOptions): Promise<void>;
+ /**
+ * Add a batch of requests to the queue.
+ *
+ * Each request is deduplicated by its `uniqueKey`. Duplicates are reported in the result
+ * but not re-added. With `forefront`, requests are placed at the beginning of the queue so
+ * they are processed sooner.
+ */
+ addBatchOfRequests(requests: RequestSchema[], options?: RequestOptions): Promise<BatchAddRequestsResult>;
+
+ /**
+ * Retrieve a request from the queue by its `uniqueKey`, or `undefined` if it does not exist.
+ */
+ getRequest(uniqueKey: string): Promise<RequestOptions | undefined>;
+
+ /**
+ * Return the next request in the queue to be processed, or `null` if there are currently no
+ * pending requests.
+ *
+ * The returned request is marked as in-progress; it will not be returned again until it is
+ * either reclaimed via {@link reclaimRequest} or marked as handled via {@link markRequestAsHandled}.
+ *
+ * A `null` return value does not mean processing is finished — only that there are no pending
+ * requests right now. Use {@link isEmpty} (together with the frontend's knowledge of pending
+ * add operations) to determine whether the queue is truly finished.
+ */
+ fetchNextRequest(): Promise<RequestOptions | null>;
+
+ /**
+ * Mark a request previously returned by {@link fetchNextRequest} as handled.
+ *
+ * Handled requests are never returned again by {@link fetchNextRequest}. Returns information
+ * about the operation, or `null` if the request was not in progress.
+ *
+ * A `null` result is a no-op, not an error: the request is simply not something this client is
+ * currently processing, so nothing is changed and the request is never added to the queue as a side
+ * effect. (Marking an already-handled request is idempotent and still returns operation info with
+ * `wasAlreadyHandled: true` rather than `null`.)
+ */
+ markRequestAsHandled(request: UpdateRequestSchema): Promise<QueueOperationInfo | null>;
+
+ /**
+ * Reclaim a failed request back to the queue so it can be processed again by a later call to
+ * {@link fetchNextRequest}. With `forefront`, the request is returned to the beginning of the
+ * queue. Returns information about the operation, or `null` if the request was not in progress.
+ *
+ * The request is expected to already be present in the queue (it should have been obtained via
+ * {@link fetchNextRequest}); reclaiming releases its lock rather than inserting it. A `null` result
+ * is a no-op, not an error: the request is simply not something this client is currently processing,
+ * so nothing is changed and the request is never added to the queue as a side effect. Use
+ * {@link addRequest} to insert a new request.
+ */
+ reclaimRequest(request: UpdateRequestSchema, options?: RequestOptions): Promise<QueueOperationInfo | null>;
+
+ /**
+ * Resolves to `true` if the next call to {@link fetchNextRequest} would return `null` — i.e. there
+ * are no pending requests to fetch right now.
+ *
+ * Requests that are currently in progress (fetched but not yet handled or reclaimed, including
+ * requests locked by other clients sharing the same queue) are **not** counted. An empty queue
+ * therefore does not mean crawling is finished — those in-progress requests may still be reclaimed,
+ * and background tasks may still add more requests. Use {@link isFinished} to detect completion.
+ */
+ isEmpty(): Promise<boolean>;
+
+ /**
+ * Resolves to `true` only when there is no outstanding work left in the queue at all — i.e. there
+ * are no pending requests to fetch **and** no requests currently in progress (fetched but not yet
+ * handled or reclaimed, including requests locked by other clients sharing the same queue).
+ *
+ * This is the strong counterpart of {@link isEmpty}: a queue whose only remaining requests are in
+ * progress is empty (nothing to fetch) but not finished (that work might still be reclaimed). It is
+ * the building block for determining whether crawling is done — though a frontend may still need to
+ * account for its own pending background add operations on top of this.
+ */
+ isFinished(): Promise<boolean>;
+
+ /**
+ * Tells the client how long (in seconds) a consumer expects to hold a request fetched via
+ * {@link fetchNextRequest} before marking it handled or reclaiming it — typically the consumer's
+ * request-processing timeout plus some padding.
+ *
+ * A client that coordinates consumers via locking uses this to keep the request reserved for at least
+ * this long, so that a long-running consumer does not have its request handed out again while it is
+ * still being processed. Clients that do not lock may ignore it.
+ */
+ setExpectedRequestProcessingTimeSecs?(secs: number): void;
}
export interface SetStatusMessageOptions {
diff --git a/test/core/crawlers/basic_crawler.test.ts b/test/core/crawlers/basic_crawler.test.ts
index 6f1235cc6..5854a3ad7 100644
--- a/test/core/crawlers/basic_crawler.test.ts
+++ b/test/core/crawlers/basic_crawler.test.ts
@@ -1013,7 +1013,7 @@ describe('BasicCrawler', () => {
vitest.spyOn(requestQueue, 'fetchNextRequest').mockImplementation(async () => queueContent.shift() ?? null);
const markReqHandled = vitest
- .spyOn(requestQueue, 'markRequestHandled')
+ .spyOn(requestQueue, 'markRequestAsHandled')
.mockReturnValue(Promise.resolve() as any);
const reclaimReq = vitest.spyOn(requestQueue, 'reclaimRequest').mockReturnValue(Promise.resolve() as any);
@@ -1095,7 +1095,7 @@ describe('BasicCrawler', () => {
vitest.spyOn(requestQueue, 'getHandledCount').mockReturnValue(Promise.resolve() as any);
let handledCount = 0;
- const markRequestHandled = vitest.spyOn(requestQueue, 'markRequestHandled').mockImplementation(async () => {
+ const markRequestAsHandled = vitest.spyOn(requestQueue, 'markRequestAsHandled').mockImplementation(async () => {
handledCount++;
// Only set isFinished after both requests have been handled
if (handledCount >= 2) {
@@ -1119,8 +1119,8 @@ describe('BasicCrawler', () => {
await basicCrawler.run();
- expect(markRequestHandled).toBeCalledWith(request0);
- expect(markRequestHandled).toBeCalledWith(request1);
+ expect(markRequestAsHandled).toBeCalledWith(request0);
+ expect(markRequestAsHandled).toBeCalledWith(request1);
expect(isFinishedOrig).not.toBeCalled();
expect(isFinishedFunctionCalled).toBe(true);
expect(isTaskReadyFunctionCalled).toBe(true);
@@ -1153,8 +1153,8 @@ describe('BasicCrawler', () => {
const request1 = new Request({ url: 'http://example.com/1' });
vitest.spyOn(requestQueue, 'getHandledCount').mockReturnValue(Promise.resolve() as any);
- const markRequestHandled = vitest
- .spyOn(requestQueue, 'markRequestHandled')
+ const markRequestAsHandled = vitest
+ .spyOn(requestQueue, 'markRequestAsHandled')
.mockReturnValue(Promise.resolve() as any);
const isFinishedOrig = vitest.spyOn(requestQueue, 'isFinished');
@@ -1171,8 +1171,8 @@ describe('BasicCrawler', () => {
await basicCrawler.run();
- expect(markRequestHandled).toBeCalledWith(request0);
- expect(markRequestHandled).toBeCalledWith(request1);
+ expect(markRequestAsHandled).toBeCalledWith(request0);
+ expect(markRequestAsHandled).toBeCalledWith(request1);
expect(isFinishedOrig).not.toBeCalled();
// TODO: see why the request1 was passed as a second parameter to includes
@@ -1241,7 +1241,7 @@ describe('BasicCrawler', () => {
requestQueue.fetchNextRequest = async () => new Request({ id: 'id', url: 'http://example.com' });
// @ts-expect-error Overriding the method for testing purposes
- requestQueue.markRequestHandled = async () => {};
+ requestQueue.markRequestAsHandled = async () => {};
const requestQueueStub = vitest.spyOn(requestQueue, 'getHandledCount').mockResolvedValue(33);
diff --git a/test/core/request_list.test.ts b/test/core/request_list.test.ts
index 23cb8e892..c5cb7536f 100644
--- a/test/core/request_list.test.ts
+++ b/test/core/request_list.test.ts
@@ -79,7 +79,7 @@ describe('RequestList', () => {
expect(await requestList.isFinished()).toBe(false);
expect(await requestList.fetchNextRequest()).toBe(null);
- await requestList.markRequestHandled(req!);
+ await requestList.markRequestAsHandled(req!);
expect(await requestList.isEmpty()).toBe(true);
expect(await requestList.isFinished()).toBe(true);
@@ -93,7 +93,7 @@ describe('RequestList', () => {
await expect(requestList.isEmpty()).rejects.toThrow();
await expect(requestList.isFinished()).rejects.toThrow();
expect(() => requestList.getState()).toThrowError();
- await expect(requestList.markRequestHandled(requestObj)).rejects.toThrow();
+ await expect(requestList.markRequestAsHandled(requestObj)).rejects.toThrow();
await expect(requestList.fetchNextRequest()).rejects.toThrow();
await requestList.initialize();
@@ -102,7 +102,7 @@ describe('RequestList', () => {
await expect(requestList.isFinished()).resolves.not.toThrow();
expect(() => requestList.getState()).not.toThrowError();
await expect(requestList.fetchNextRequest()).resolves.not.toThrow();
- await expect(requestList.markRequestHandled(requestObj)).resolves.not.toThrow();
+ await expect(requestList.markRequestAsHandled(requestObj)).resolves.not.toThrow();
});
test('should correctly initialize itself', async () => {
@@ -127,9 +127,9 @@ describe('RequestList', () => {
await originalList.fetchNextRequest(); // 5 - left in progress
await originalList.fetchNextRequest(); // 6 - left in progress
- await originalList.markRequestHandled(r1!);
- await originalList.markRequestHandled(r2!);
- await originalList.markRequestHandled(r4!);
+ await originalList.markRequestAsHandled(r1!);
+ await originalList.markRequestAsHandled(r2!);
+ await originalList.markRequestAsHandled(r4!);
// Requests 3, 5 and 6 were in progress when the state was persisted, so they must be
// re-crawled (before the remaining, never-fetched requests 7 and 8).
@@ -307,8 +307,8 @@ describe('RequestList', () => {
expect(await requestList.isFinished()).toBe(false);
expect(requestList.inProgress.size).toBe(2);
- await requestList.markRequestHandled(request1!);
- await requestList.markRequestHandled(request2!);
+ await requestList.markRequestAsHandled(request1!);
+ await requestList.markRequestAsHandled(request2!);
expect(requestList.getState()).toEqual({
inProgress: [],
@@ -322,7 +322,7 @@ describe('RequestList', () => {
expect(await requestList.isEmpty()).toBe(true);
expect(await requestList.isFinished()).toBe(false);
- await requestList.markRequestHandled(request3!);
+ await requestList.markRequestAsHandled(request3!);
expect(await requestList.isFinished()).toBe(true);
});
@@ -359,7 +359,7 @@ describe('RequestList', () => {
// Do some other changes and persist it again.
const request2 = await requestList.fetchNextRequest();
expect(requestList.isStatePersisted).toBe(false);
- await requestList.markRequestHandled(request2!);
+ await requestList.markRequestAsHandled(request2!);
expect(requestList.isStatePersisted).toBe(false);
setValueSpy.mockResolvedValueOnce();
serviceLocator.getEventManager().emit(EventType.PERSIST_STATE);
@@ -494,7 +494,7 @@ describe('RequestList', () => {
reqs = shuffle(reqs) as typeof reqs;
for (let i = 0; i < reqs.length; i++) {
- await requestList.markRequestHandled(reqs[i]);
+ await requestList.markRequestAsHandled(reqs[i]);
}
});
@@ -532,10 +532,10 @@ describe('RequestList', () => {
const req3 = await requestList.fetchNextRequest();
expect(await requestList.getHandledCount()).toBe(0);
- await requestList.markRequestHandled(req2!);
+ await requestList.markRequestAsHandled(req2!);
expect(await requestList.getHandledCount()).toBe(1);
- await requestList.markRequestHandled(req3!);
+ await requestList.markRequestAsHandled(req3!);
expect(await requestList.getHandledCount()).toBe(2);
});
diff --git a/test/core/request_manager_tandem.test.ts b/test/core/request_manager_tandem.test.ts
index 658501853..5898fbc03 100644
--- a/test/core/request_manager_tandem.test.ts
+++ b/test/core/request_manager_tandem.test.ts
@@ -58,23 +58,23 @@ describe('RequestManagerTandem', () => {
expect(request4).toBeNull();
});
- test('markRequestHandled properly marks request as handled in the queue', async () => {
+ test('markRequestAsHandled properly marks request as handled in the queue', async () => {
const requestList = await RequestList.open(null, [{ url: 'https://example.com/1' }]);
const requestQueue = await RequestQueue.open();
const tandem = new RequestManagerTandem(requestList, requestQueue);
- // Mock markRequestHandled in requestQueue
- const markHandledSpy = vi.spyOn(requestQueue, 'markRequestHandled');
+ // Mock markRequestAsHandled in requestQueue
+ const markHandledSpy = vi.spyOn(requestQueue, 'markRequestAsHandled');
// First fetch a request
const request = await tandem.fetchNextRequest();
expect(request).not.toBeNull();
// Mark it as handled
- await tandem.markRequestHandled(request!);
+ await tandem.markRequestAsHandled(request!);
- // Verify the queue's markRequestHandled was called
+ // Verify the queue's markRequestAsHandled was called
expect(markHandledSpy).toHaveBeenCalledWith(request);
});
@@ -186,7 +186,7 @@ describe('RequestManagerTandem', () => {
// The loader is read-only and can no longer reclaim. The failed request must be marked as
// handled on the loader so it doesn't get stuck in the loader's in-progress state
// (matching crawlee-python behaviour).
- const markHandledSpy = vi.spyOn(requestList, 'markRequestHandled');
+ const markHandledSpy = vi.spyOn(requestList, 'markRequestAsHandled');
// The queue should never be fetched from on a failed transfer round.
const queueFetchSpy = vi.spyOn(requestQueue, 'fetchNextRequest');
@@ -269,4 +269,35 @@ describe('RequestManagerTandem', () => {
expect(persistSpy).toHaveBeenCalledTimes(1);
});
+
+ test('setExpectedRequestProcessingTimeSecs forwards to an already-resolved manager', async () => {
+ const requestList = await RequestList.open(null, [{ url: 'https://example.com/1' }]);
+ const requestQueue = await RequestQueue.open();
+ const hintSpy = vi.spyOn(requestQueue, 'setExpectedRequestProcessingTimeSecs');
+
+ const tandem = new RequestManagerTandem(requestList, requestQueue);
+
+ // Resolve the manager first (the queue was passed eagerly, but make the dependency explicit).
+ await tandem.fetchNextRequest();
+
+ tandem.setExpectedRequestProcessingTimeSecs(600);
+ expect(hintSpy).toHaveBeenCalledWith(600);
+ });
+
+ test('setExpectedRequestProcessingTimeSecs applies a hint set before the manager is lazily resolved', async () => {
+ const requestList = await RequestList.open(null, [{ url: 'https://example.com/1' }]);
+ const requestQueue = await RequestQueue.open();
+ const hintSpy = vi.spyOn(requestQueue, 'setExpectedRequestProcessingTimeSecs');
+
+ // Provide the manager lazily so it is not resolved at construction time.
+ const tandem = new RequestManagerTandem(requestList, () => requestQueue);
+
+ // Hint arrives before anything resolves the manager — nothing forwarded yet.
+ tandem.setExpectedRequestProcessingTimeSecs(600);
+ expect(hintSpy).not.toHaveBeenCalled();
+
+ // Resolving the manager (via any operation) applies the remembered hint.
+ await tandem.fetchNextRequest();
+ expect(hintSpy).toHaveBeenCalledWith(600);
+ });
});
diff --git a/test/core/sitemap_request_loader.test.ts b/test/core/sitemap_request_loader.test.ts
index a3e7cf708..06f3c0174 100644
--- a/test/core/sitemap_request_loader.test.ts
+++ b/test/core/sitemap_request_loader.test.ts
@@ -297,7 +297,7 @@ describe('SitemapRequestLoader', () => {
const list = await SitemapRequestLoader.open({ sitemapUrls: [`${url}/sitemap-unreliable.xml`], enqueueStrategy: 'all' });
for await (const request of list) {
- await list.markRequestHandled(request);
+ await list.markRequestAsHandled(request);
}
expect(await list.getHandledCount()).toBe(5);
@@ -309,7 +309,7 @@ describe('SitemapRequestLoader', () => {
const urls = new Set<string>();
for await (const request of list) {
- await list.markRequestHandled(request);
+ await list.markRequestAsHandled(request);
urls.add(request.url);
}
@@ -329,7 +329,7 @@ describe('SitemapRequestLoader', () => {
const list = await SitemapRequestLoader.open({ sitemapUrls: [`${url}/sitemap-index.xml`], enqueueStrategy: 'all' });
for await (const request of list) {
- await list.markRequestHandled(request);
+ await list.markRequestAsHandled(request);
if ((await list.getHandledCount()) >= 2) {
await list.teardown();
@@ -349,7 +349,7 @@ describe('SitemapRequestLoader', () => {
});
for await (const request of list) {
- await list.markRequestHandled(request);
+ await list.markRequestAsHandled(request);
}
expect(await list.getHandledCount()).toBe(4);
@@ -363,7 +363,7 @@ describe('SitemapRequestLoader', () => {
});
for await (const request of list) {
- await list.markRequestHandled(request);
+ await list.markRequestAsHandled(request);
}
expect(await list.getHandledCount()).toBe(2);
@@ -377,7 +377,7 @@ describe('SitemapRequestLoader', () => {
});
for await (const request of list) {
- await list.markRequestHandled(request);
+ await list.markRequestAsHandled(request);
}
expect(await list.getHandledCount()).toBe(3);
@@ -395,7 +395,7 @@ describe('SitemapRequestLoader', () => {
while (!(await list.isEmpty())) {
const request = await list.fetchNextRequest();
firstBatch.push(request!);
- await list.markRequestHandled(request!);
+ await list.markRequestAsHandled(request!);
}
expect(firstBatch).toHaveLength(2);
@@ -409,7 +409,7 @@ describe('SitemapRequestLoader', () => {
while (!(await list.isEmpty())) {
const request = await list.fetchNextRequest();
secondBatch.push(request!);
- await list.markRequestHandled(request!);
+ await list.markRequestAsHandled(request!);
}
expect(secondBatch).toHaveLength(5);
@@ -422,7 +422,7 @@ describe('SitemapRequestLoader', () => {
const list = await SitemapRequestLoader.open({ sitemapUrls: [`${url}/sitemap-index.xml`], enqueueStrategy: 'all' });
for await (const request of list) {
- await list.markRequestHandled(request);
+ await list.markRequestAsHandled(request);
}
await expect(list.isFinished()).resolves.toBe(true);
@@ -442,7 +442,7 @@ describe('SitemapRequestLoader', () => {
controller.abort();
for await (const request of list) {
- await list.markRequestHandled(request);
+ await list.markRequestAsHandled(request);
}
await expect(list.isFinished()).resolves.toBe(true);
@@ -458,7 +458,7 @@ describe('SitemapRequestLoader', () => {
});
for await (const request of list) {
- await list.markRequestHandled(request);
+ await list.markRequestAsHandled(request);
}
await expect(list.isFinished()).resolves.toBe(true);
@@ -485,7 +485,7 @@ describe('SitemapRequestLoader', () => {
const newList = await SitemapRequestLoader.open(options);
for await (const request of newList) {
- await newList.markRequestHandled(request);
+ await newList.markRequestAsHandled(request);
}
expect(await newList.getHandledCount()).toBe(2);
@@ -500,7 +500,7 @@ describe('SitemapRequestLoader', () => {
while (!(await list.isFinished())) {
const request = await list.fetchNextRequest();
if (!request) break;
- await list.markRequestHandled(request);
+ await list.markRequestAsHandled(request);
requests.push(request);
}
@@ -521,7 +521,7 @@ describe('SitemapRequestLoader', () => {
const list = await SitemapRequestLoader.open(options);
const firstRequest = await list.fetchNextRequest();
- await list.markRequestHandled(firstRequest!);
+ await list.markRequestAsHandled(firstRequest!);
await list.persistState();
@@ -531,7 +531,7 @@ describe('SitemapRequestLoader', () => {
while (!(await newList.isFinished())) {
const request = await newList.fetchNextRequest();
if (!request) break;
- await newList.markRequestHandled(request);
+ await newList.markRequestAsHandled(request);
}
expect(await list.getHandledCount()).toBe(1);
@@ -542,7 +542,7 @@ describe('SitemapRequestLoader', () => {
const list = await SitemapRequestLoader.open({ sitemapUrls: [`${url}/sitemap.xml`], enqueueStrategy: 'all' });
for await (const request of list) {
- await list.markRequestHandled(request);
+ await list.markRequestAsHandled(request);
if ((await list.getHandledCount()) >= 2) break;
}
diff --git a/test/core/storages/request_queue.test.ts b/test/core/storages/request_queue.test.ts
index 04d665949..86b1a1bc0 100644
--- a/test/core/storages/request_queue.test.ts
+++ b/test/core/storages/request_queue.test.ts
@@ -1,15 +1,6 @@
/* eslint-disable dot-notation */
-import {
- API_PROCESSED_REQUESTS_DELAY_MILLIS,
- ProxyConfiguration,
- QUERY_HEAD_MIN_LENGTH,
- Request,
- RequestQueueV1 as RequestQueue,
- RequestQueueV2,
- serviceLocator,
- STORAGE_CONSISTENCY_DELAY_MILLIS,
-} from '@crawlee/core';
+import { ProxyConfiguration, Request, RequestQueue, serviceLocator } from '@crawlee/core';
import { sleep } from '@crawlee/utils';
import { MemoryStorageEmulator } from '../../shared/MemoryStorageEmulator.js';
@@ -35,254 +26,126 @@ beforeEach(async () => {
});
describe('RequestQueue remote', () => {
- async function createRequestQueue(id = 'some-id', name?: string) {
- const client = await serviceLocator.getStorageClient().createRequestQueueClient(name ? { name } : { id });
- return new RequestQueue({ id, name, client }, serviceLocator.getConfiguration());
- }
+ const emulator = new MemoryStorageEmulator();
- beforeEach(() => {
+ beforeEach(async () => {
+ await emulator.init();
vitest.clearAllMocks();
});
- test('should work', async () => {
- const queue = await createRequestQueue();
- const firstResolveValue = {
- requestId: 'a',
- wasAlreadyHandled: false,
- wasAlreadyPresent: false,
- };
- const mockAddRequest = vitest.spyOn(queue.client, 'addRequest').mockResolvedValueOnce(firstResolveValue);
-
- const requestOptions = { url: 'http://example.com/a' };
- const queueOperationInfo1 = await queue.addRequest(requestOptions);
- const requestA = new Request(requestOptions);
- expect(queueOperationInfo1).toMatchObject({
- ...firstResolveValue,
- });
+ afterEach(async () => {
+ await emulator.destroy();
+ });
- expect(queue['queueHeadIds'].length()).toBe(1);
- expect(mockAddRequest).toHaveBeenCalledTimes(1);
- expect(mockAddRequest).toHaveBeenCalledWith(requestA, { forefront: false });
+ async function createRequestQueue(id = 'some-id', name?: string) {
+ const client = await serviceLocator.getStorageClient().createRequestQueueClient(name ? { name } : { id });
+ return new RequestQueue({ id, name, client }, serviceLocator.getConfiguration());
+ }
- // Try to add again a request with the same URL
- const queueOperationInfo2 = await queue.addRequest(requestOptions);
- expect(queueOperationInfo2).toMatchObject({
- wasAlreadyPresent: true,
- wasAlreadyHandled: false,
- requestId: 'a',
- });
+ test('adding a request makes it fetchable; fetching again returns null while in progress', async () => {
+ const queue = await createRequestQueue();
- expect(queue['queueHeadIds'].length()).toBe(1);
+ const info = await queue.addRequest({ url: 'http://example.com/a' });
+ expect(info.wasAlreadyPresent).toBe(false);
+ expect(info.wasAlreadyHandled).toBe(false);
- const requestB = new Request({ url: 'http://example.com/b' });
- const secondResolveValue = {
- requestId: 'b',
- wasAlreadyHandled: false,
- wasAlreadyPresent: false,
- };
- mockAddRequest.mockResolvedValueOnce(secondResolveValue);
-
- await queue.addRequest(requestB, { forefront: true });
- expect(mockAddRequest).toHaveBeenCalledTimes(2);
- expect(mockAddRequest).toHaveBeenLastCalledWith(requestB, { forefront: true });
-
- expect(queue['queueHeadIds'].length()).toBe(2);
- expect(queue.inProgressCount()).toBe(0);
-
- // Forefronted request was added to the queue.
- const mockGetRequest = vitest.spyOn(queue.client, 'getRequest');
- mockGetRequest.mockResolvedValueOnce({ ...requestB, id: 'b' });
-
- const requestBFromQueue = await queue.fetchNextRequest();
- expect(mockGetRequest).toHaveBeenCalledTimes(1);
- expect(mockGetRequest).toHaveBeenLastCalledWith('b');
- expect(requestBFromQueue).toEqual({ ...requestB, id: 'b' });
-
- expect(queue['queueHeadIds'].length()).toBe(1);
- expect(queue.inProgressCount()).toBe(1);
-
- // Test validations
- await queue
- .addRequest(new Request({ id: 'id-already-set', url: 'https://example.com' }))
- .catch((err) =>
- expect(err.message).toMatch(
- 'Expected property `id` to be of type `undefined` but received type `string` in object',
- ),
- );
-
- // getRequest() returns undefined if object was not found.
- mockGetRequest.mockResolvedValueOnce(undefined);
-
- const requestXFromQueue = await queue.getRequest('non-existent');
- expect(mockGetRequest).toHaveBeenCalledTimes(2);
- expect(mockGetRequest).toHaveBeenLastCalledWith('non-existent');
- expect(requestXFromQueue).toBe(null);
-
- // Reclaim it.
- const mockUpdateRequest = vitest.spyOn(queue.client, 'updateRequest');
- mockUpdateRequest.mockResolvedValueOnce({
- requestId: 'b',
- wasAlreadyHandled: false,
- wasAlreadyPresent: true,
- // TODO: request is not defined in the types
- // @ts-expect-error
- request: requestBFromQueue,
- });
+ const fetched = await queue.fetchNextRequest();
+ expect(fetched).not.toBeNull();
+ expect(fetched!.url).toBe('http://example.com/a');
+ expect(fetched!.uniqueKey).toBe(info.uniqueKey);
- await queue.reclaimRequest(requestBFromQueue!, { forefront: true });
- expect(mockUpdateRequest).toHaveBeenCalledTimes(1);
- expect(mockUpdateRequest).toHaveBeenLastCalledWith(requestBFromQueue, { forefront: true });
-
- expect(queue['queueHeadIds'].length()).toBe(1);
- expect(queue.inProgressCount()).toBe(1);
- await sleep(STORAGE_CONSISTENCY_DELAY_MILLIS + 10);
+ // The request is now in progress, so there is nothing more to fetch.
+ expect(await queue.fetchNextRequest()).toBeNull();
+ });
- expect(queue['queueHeadIds'].length()).toBe(2);
- expect(queue.inProgressCount()).toBe(0);
+ test('adding the same uniqueKey twice does not duplicate and is served from the local cache', async () => {
+ const queue = await createRequestQueue();
- // Fetch again.
- mockGetRequest.mockResolvedValueOnce(requestBFromQueue as never);
+ const requestA = new Request({ url: 'http://example.com/a' });
+ const requestB = new Request({ url: 'http://example.com/a' }); // Has the same uniqueKey as A.
- const requestBFromQueue2 = await queue.fetchNextRequest();
- expect(mockGetRequest).toHaveBeenCalledTimes(3);
- expect(mockGetRequest).toHaveBeenLastCalledWith('b');
- expect(requestBFromQueue2).toEqual(requestBFromQueue);
+ const first = await queue.addRequest(requestA);
+ expect(first.wasAlreadyPresent).toBe(false);
- expect(queue['queueHeadIds'].length()).toBe(1);
- expect(queue.inProgressCount()).toBe(1);
+ // Spy on the client only AFTER the first add so we can assert the cache prevents a second call.
+ const addBatchSpy = vitest.spyOn(queue.client, 'addBatchOfRequests');
- // Mark handled.
- mockUpdateRequest.mockResolvedValueOnce({
- requestId: 'b',
- wasAlreadyHandled: false,
+ const second = await queue.addRequest(requestB);
+ expect(second).toEqual({
+ requestId: first.requestId,
+ uniqueKey: requestA.uniqueKey,
wasAlreadyPresent: true,
- // TODO: request is not defined in the types
- // @ts-expect-error
- request: requestBFromQueue,
+ wasAlreadyHandled: false,
+ forefront: false,
});
- await queue.markRequestHandled(requestBFromQueue!);
- expect(mockUpdateRequest).toHaveBeenCalledTimes(2);
- expect(mockUpdateRequest).toHaveBeenLastCalledWith(requestBFromQueue);
-
- expect(queue['queueHeadIds'].length()).toBe(1);
- expect(queue.inProgressCount()).toBe(0);
-
- // Emulate there are no cached items in queue
+ // The local cache should have prevented a second client call.
+ expect(addBatchSpy).not.toHaveBeenCalled();
- queue['queueHeadIds'].clear();
+ // And there is still only a single request in the queue.
+ const fetched = await queue.fetchNextRequest();
+ expect(fetched!.uniqueKey).toBe(requestA.uniqueKey);
+ expect(await queue.fetchNextRequest()).toBeNull();
+ });
- // Query queue head.
- const mockListHead = vitest.spyOn(queue.client, 'listHead');
- mockListHead.mockResolvedValueOnce({
- items: [
- { id: 'a', uniqueKey: 'aaa' },
- { id: 'c', uniqueKey: 'ccc' },
- ],
- } as never);
- mockGetRequest.mockResolvedValueOnce({ ...requestA, id: 'a' });
+ test('a handled request is not fetched again and isFinished() becomes true', async () => {
+ const queue = await createRequestQueue();
- const requestAFromQueue = await queue.fetchNextRequest();
- expect(mockGetRequest).toHaveBeenCalledTimes(4);
- expect(mockGetRequest).toHaveBeenLastCalledWith('a');
- expect(mockListHead).toHaveBeenCalledTimes(1);
- expect(mockListHead).toHaveBeenLastCalledWith({ limit: QUERY_HEAD_MIN_LENGTH });
- expect(requestAFromQueue).toEqual({ ...requestA, id: 'a' });
+ await queue.addRequest({ url: 'http://example.com/a' });
- expect(queue['queueHeadIds'].length()).toBe(1);
- expect(queue.inProgressCount()).toBe(1);
+ const fetched = await queue.fetchNextRequest();
+ expect(fetched).not.toBeNull();
- // Drop queue.
- const mockDrop = vitest.spyOn(queue.client, 'drop');
- mockDrop.mockResolvedValueOnce(undefined);
+ await queue.markRequestAsHandled(fetched!);
- await queue.drop();
- expect(mockDrop).toHaveBeenCalledTimes(1);
- expect(mockDrop).toHaveBeenLastCalledWith();
+ expect(await queue.fetchNextRequest()).toBeNull();
+ expect(await queue.isFinished()).toBe(true);
});
- test('addRequests', async () => {
- const queue = await createRequestQueue('batch-requests');
- const mockAddRequests = vitest.spyOn(queue.client, 'batchAddRequests');
+ test('a reclaimed request is fetched again; reclaim with forefront returns it to the front', async () => {
+ const queue = await createRequestQueue();
- const requestOptions = { url: 'http://example.com/a' };
- const requestA = new Request(requestOptions);
+ await queue.addRequest({ url: 'http://example.com/a' });
+ await sleep(5);
+ await queue.addRequest({ url: 'http://example.com/b' });
- // Test adding 1 request
- const firstRequestAdded = {
- requestId: 'a',
- wasAlreadyHandled: false,
- wasAlreadyPresent: false,
- uniqueKey: requestA.uniqueKey,
- };
- mockAddRequests.mockResolvedValueOnce({
- processedRequests: [firstRequestAdded],
- unprocessedRequests: [],
- });
+ // Fetch the first pending request (a) and reclaim it to the front.
+ const first = await queue.fetchNextRequest();
+ expect(first!.url).toBe('http://example.com/a');
- const addRequestsResult1 = await queue.addRequests([requestOptions]);
+ await queue.reclaimRequest(first!, { forefront: true });
- expect(addRequestsResult1.processedRequests).toHaveLength(1);
- expect(addRequestsResult1.processedRequests[0]).toEqual({
- ...firstRequestAdded,
- });
+ // The reclaimed request should now be served before the older pending request (b).
+ const afterReclaim = await queue.fetchNextRequest();
+ expect(afterReclaim!.url).toBe('http://example.com/a');
+ expect(afterReclaim!.uniqueKey).toBe(first!.uniqueKey);
+ });
- // Ensure the client method was actually called, and added
+ test('addRequests processes requests and reports processed/unprocessed', async () => {
+ const queue = await createRequestQueue('batch-requests');
- expect(queue['queueHeadIds'].length()).toBe(1);
- expect(mockAddRequests).toHaveBeenCalledTimes(1);
- expect(mockAddRequests).toHaveBeenCalledWith([requestA], { forefront: false });
+ const result = await queue.addRequests([{ url: 'http://example.com/a' }, { url: 'http://example.com/b' }]);
- // Try to add a request with the same URL again, expecting cached
- const addRequestsResult2 = await queue.addRequests([requestOptions]);
- expect(addRequestsResult2.processedRequests).toHaveLength(1);
- expect(addRequestsResult2.processedRequests[0]).toEqual({
- ...firstRequestAdded,
- wasAlreadyPresent: true,
- });
+ expect(result.processedRequests).toHaveLength(2);
+ expect(result.unprocessedRequests).toHaveLength(0);
+ expect(result.processedRequests.every((r) => !r.wasAlreadyPresent)).toBe(true);
+ expect(result.processedRequests.map((r) => r.uniqueKey)).toEqual([
+ 'http://example.com/a',
+ 'http://example.com/b',
+ ]);
- expect(queue['queueHeadIds'].length()).toBe(1);
-
- // Adding more requests, forefront
- const requestB = new Request({ url: 'http://example.com/b' });
- const requestC = new Request({ url: 'http://example.com/c' });
-
- mockAddRequests.mockResolvedValueOnce({
- processedRequests: [
- {
- requestId: 'b',
- uniqueKey: requestB.uniqueKey,
- wasAlreadyHandled: false,
- wasAlreadyPresent: false,
- },
- {
- requestId: 'c',
- uniqueKey: requestC.uniqueKey,
- wasAlreadyHandled: false,
- wasAlreadyPresent: false,
- },
- ],
- unprocessedRequests: [],
- });
+ // Re-adding the same requests reports them as already present.
+ const result2 = await queue.addRequests([{ url: 'http://example.com/a' }, { url: 'http://example.com/b' }]);
+ expect(result2.processedRequests).toHaveLength(2);
+ expect(result2.processedRequests.every((r) => r.wasAlreadyPresent)).toBe(true);
- const addRequestsResult3 = await queue.addRequests([requestB, requestC], { forefront: true });
- expect(addRequestsResult3.processedRequests).toHaveLength(2);
- expect(addRequestsResult3.processedRequests[0]).toEqual({
- requestId: 'b',
- uniqueKey: requestB.uniqueKey,
- wasAlreadyHandled: false,
- wasAlreadyPresent: false,
- });
- expect(addRequestsResult3.processedRequests[1]).toEqual({
- requestId: 'c',
- uniqueKey: requestC.uniqueKey,
- wasAlreadyHandled: false,
- wasAlreadyPresent: false,
- });
-
- expect(queue['queueHeadIds'].length()).toBe(3);
- expect(mockAddRequests).toHaveBeenCalled();
- expect(mockAddRequests).toHaveBeenCalledWith([requestB, requestC], { forefront: true });
+ // The queue still contains exactly the two distinct requests.
+ const fetchedUrls: string[] = [];
+ for (let req = await queue.fetchNextRequest(); req !== null; req = await queue.fetchNextRequest()) {
+ fetchedUrls.push(req.url);
+ await queue.markRequestAsHandled(req);
+ }
+ expect(fetchedUrls.sort()).toEqual(['http://example.com/a', 'http://example.com/b']);
});
test('addRequestsBatched does not retry permanently unprocessed requests forever', async () => {
@@ -350,190 +213,77 @@ describe('RequestQueue remote', () => {
expect(submittedCount).toBe(5);
});
- test('should cache new requests locally', async () => {
- const queue = await createRequestQueue();
-
- const requestA = new Request({ url: 'http://example.com/a' });
- const requestB = new Request({ url: 'http://example.com/a' }); // Has same uniqueKey as A
-
- // Add request A
- const addRequestMock = vitest.spyOn(queue.client, 'addRequest');
- addRequestMock.mockResolvedValueOnce({
- requestId: 'a',
- wasAlreadyHandled: false,
- wasAlreadyPresent: false,
- });
+ test('fetchNextRequest order respects forefront enqueues', async () => {
+ const queue = await createRequestQueue('forefront-order');
- await queue.addRequest(requestA);
- expect(addRequestMock).toHaveBeenCalledTimes(1);
- expect(addRequestMock).toHaveBeenLastCalledWith(requestA, { forefront: false });
+ // Add some non-forefront requests (sleep between adds to keep orderNo deterministic).
+ await queue.addRequest({ url: 'http://example.com/1' });
+ await sleep(5);
+ await queue.addRequest({ url: 'http://example.com/5' });
+ await sleep(5);
+ await queue.addRequest({ url: 'http://example.com/6' });
- // Add request B that has same unique so that addRequest() is not called because it's already cached.
- // mock.expects('addRequest').never();
- const queueOperationInfo = await queue.addRequest(requestB);
- expect(addRequestMock).toHaveBeenCalledTimes(1);
- expect(queueOperationInfo).toEqual({
- requestId: 'a',
- uniqueKey: requestA.uniqueKey,
- wasAlreadyPresent: true,
- wasAlreadyHandled: false,
- forefront: false,
- });
- });
+ const retrievedUrls: string[] = [];
- test('should cache requests locally with info if request was already handled', async () => {
- const queue = await createRequestQueue();
+ // Fetch and handle the first request so it is removed from the queue.
+ const first = await queue.fetchNextRequest();
+ retrievedUrls.push(first!.url);
+ await queue.markRequestAsHandled(first!);
- const requestX = new Request({ url: 'http://example.com/x' });
- const requestY = new Request({ url: 'http://example.com/x' }); // Has same uniqueKey as X
+ // Add more requests at the forefront.
+ await queue.addRequest({ url: 'http://example.com/4' }, { forefront: true });
+ await sleep(5);
+ await queue.addRequest({ url: 'http://example.com/3' }, { forefront: true });
+ await sleep(5);
+ await queue.addRequest({ url: 'http://example.com/2' }, { forefront: true });
- // Add request X.
- const addRequestMock = vitest.spyOn(queue.client, 'addRequest');
- addRequestMock.mockResolvedValueOnce({
- requestId: 'x',
- wasAlreadyHandled: true,
- wasAlreadyPresent: true,
- });
+ // Drain the queue, marking each request handled before fetching the next so the
+ // ordering is deterministic and no request is fetched twice.
+ for (let req = await queue.fetchNextRequest(); req !== null; req = await queue.fetchNextRequest()) {
+ retrievedUrls.push(req.url);
+ await queue.markRequestAsHandled(req);
+ }
- await queue.addRequest(requestX);
- expect(addRequestMock).toHaveBeenCalledTimes(1);
- expect(addRequestMock).toHaveBeenLastCalledWith(requestX, { forefront: false });
-
- // Add request Y that has same unique so that addRequest() is not called because it's already cached.
- // mock.expects('addRequest').never();
- const queueOperationInfo = await queue.addRequest(requestY);
- expect(addRequestMock).toHaveBeenCalledTimes(1);
- expect(queueOperationInfo).toEqual({
- requestId: 'x',
- uniqueKey: requestX.uniqueKey,
- wasAlreadyPresent: true,
- wasAlreadyHandled: true,
- forefront: false,
- });
+ // Forefront requests (2, 3, 4) are served before the older pending ones (5, 6).
+ expect(retrievedUrls.map((x) => new URL(x).pathname)).toEqual(['/1', '/2', '/3', '/4', '/5', '/6']);
});
- test('should cache requests from queue head', async () => {
+ test('isEmpty() reflects fetchable requests while isFinished() accounts for in-progress ones', async () => {
const queue = await createRequestQueue();
- // Query queue head with request A
- const listHeadMock = vitest.spyOn(queue.client, 'listHead');
- listHeadMock.mockResolvedValueOnce({
- items: [{ id: 'a', uniqueKey: 'aaa' }],
- } as never);
-
+ await queue.addRequest({ url: 'http://example.com/a' });
+ // There is a pending request, so the queue is neither empty nor finished.
expect(await queue.isEmpty()).toBe(false);
- expect(listHeadMock).toHaveBeenCalledTimes(1);
- expect(listHeadMock).toHaveBeenLastCalledWith({ limit: QUERY_HEAD_MIN_LENGTH });
-
- // Add request A and addRequest is not called because was already cached.
- const requestA = new Request({ url: 'http://example.com/a', uniqueKey: 'aaa' });
- const addRequestMock = vitest.spyOn(queue.client, 'addRequest');
-
- const queueOperationInfo = await queue.addRequest(requestA);
- expect(addRequestMock).toHaveBeenCalledTimes(0);
- expect(queueOperationInfo).toEqual({
- requestId: 'a',
- uniqueKey: 'aaa',
- wasAlreadyPresent: true,
- wasAlreadyHandled: false,
- forefront: false,
- });
- });
-
- test('should handle situation when newly created request is not available yet', async () => {
- const queue = await createRequestQueue('some-id', 'some-queue');
- const listHeadMock = vitest.spyOn(queue.client, 'listHead');
-
- const requestA = new Request({ url: 'http://example.com/a' });
-
- // Add request A
- const addRequestMock = vitest.spyOn(queue.client, 'addRequest');
- addRequestMock.mockResolvedValueOnce({
- requestId: 'a',
- wasAlreadyHandled: false,
- wasAlreadyPresent: false,
- });
-
- await queue.addRequest(requestA, { forefront: true });
- expect(addRequestMock).toHaveBeenCalledTimes(1);
- expect(addRequestMock).toHaveBeenLastCalledWith(requestA, { forefront: true });
-
- expect(queue['queueHeadIds'].length()).toBe(1);
-
- // Try to get requestA which is not available yet.
- const getRequestMock = vitest.spyOn(queue.client, 'getRequest');
- getRequestMock.mockResolvedValueOnce(undefined);
-
- const fetchedRequest = await queue.fetchNextRequest();
- expect(getRequestMock).toHaveBeenCalledTimes(1);
- expect(getRequestMock).toHaveBeenLastCalledWith('a');
- expect(fetchedRequest).toBe(null);
-
- // Give queue time to mark request 'a' as not in progress
- await sleep(STORAGE_CONSISTENCY_DELAY_MILLIS + 10);
- expect(listHeadMock).not.toHaveBeenCalled();
-
- // Should try it once again (the queue head is queried again)
- getRequestMock.mockResolvedValueOnce({
- ...requestA,
- id: 'a',
- });
-
- listHeadMock.mockResolvedValueOnce({
- items: [{ id: 'a', uniqueKey: 'aaa' }],
- } as never);
-
- const fetchedRequest2 = await queue.fetchNextRequest();
- expect(getRequestMock).toHaveBeenCalledTimes(2);
- expect(getRequestMock).toHaveBeenLastCalledWith('a');
- expect(listHeadMock).toHaveBeenCalledTimes(1);
- expect(listHeadMock).toHaveBeenLastCalledWith({ limit: QUERY_HEAD_MIN_LENGTH });
- expect(fetchedRequest2).toEqual({ ...requestA, id: 'a' });
- });
-
- test('should not add handled request to queue head dict', async () => {
- const queue = await createRequestQueue();
-
- const requestA = new Request({ url: 'http://example.com/a' });
-
- const addRequestMock = vitest.spyOn(queue.client, 'addRequest');
- addRequestMock.mockResolvedValueOnce({
- requestId: 'a',
- wasAlreadyHandled: true,
- wasAlreadyPresent: true,
- });
-
- const getRequestMock = vitest.spyOn(queue.client, 'getRequest');
-
- const listHeadMock = vitest.spyOn(queue.client, 'listHead');
- listHeadMock.mockResolvedValueOnce({
- items: [],
- } as never);
+ expect(await queue.isFinished()).toBe(false);
- await queue.addRequest(requestA, { forefront: true });
- expect(addRequestMock).toHaveBeenCalledTimes(1);
- expect(addRequestMock).toHaveBeenLastCalledWith(requestA, { forefront: true });
+ const fetched = await queue.fetchNextRequest();
+ // The request is now in progress (locked), not handled. There is nothing left to fetch, so the
+ // queue is empty — but it is not finished, since the in-progress request might still be
+ // reclaimed. That "not finished" signal keeps a crawler running while the request is processed.
+ expect(await queue.isEmpty()).toBe(true);
+ expect(await queue.isFinished()).toBe(false);
- const fetchedRequest = await queue.fetchNextRequest();
- expect(getRequestMock).not.toHaveBeenCalled();
- expect(listHeadMock).toHaveBeenCalledTimes(1);
- expect(listHeadMock).toHaveBeenLastCalledWith({ limit: QUERY_HEAD_MIN_LENGTH });
- expect(fetchedRequest).toBe(null);
+ await queue.markRequestAsHandled(fetched!);
+ // Now the request is handled and gone, so the queue is both empty and finished.
+ expect(await queue.isEmpty()).toBe(true);
+ expect(await queue.isFinished()).toBe(true);
});
test('should accept plain object in addRequest()', async () => {
const queue = await createRequestQueue();
- const addRequestMock = vitest.spyOn(queue.client, 'addRequest');
- addRequestMock.mockResolvedValueOnce({
- requestId: 'xxx',
- wasAlreadyHandled: false,
- wasAlreadyPresent: false,
- });
const requestOpts = { url: 'http://example.com/a' };
- await queue.addRequest(requestOpts);
- expect(addRequestMock).toHaveBeenCalledTimes(1);
- expect(addRequestMock).toHaveBeenLastCalledWith(new Request(requestOpts), { forefront: false });
+ const info = await queue.addRequest(requestOpts);
+
+ const expectedUniqueKey = new Request(requestOpts).uniqueKey;
+ expect(info.uniqueKey).toBe(expectedUniqueKey);
+ expect(info.wasAlreadyPresent).toBe(false);
+
+ // The request can be fetched back by its uniqueKey.
+ const stored = await queue.getRequest(info.uniqueKey);
+ expect(stored).not.toBeNull();
+ expect(stored!.url).toBe('http://example.com/a');
+ expect(stored!.uniqueKey).toBe(expectedUniqueKey);
});
test('should return correct handledCount', async () => {
@@ -548,198 +298,6 @@ describe('RequestQueue remote', () => {
expect(getMock).toHaveBeenLastCalledWith();
});
- test('should always wait for a queue head to become consistent before marking queue as finished (hadMultipleClients = true)', async () => {
- const queue = await createRequestQueue('some-id', 'some-name');
-
- // Return head with modifiedAt = now so it will retry the call.
- const listHeadMock = vitest.spyOn(queue.client, 'listHead');
- listHeadMock.mockResolvedValueOnce({
- limit: 5,
- queueModifiedAt: new Date(Date.now() - API_PROCESSED_REQUESTS_DELAY_MILLIS * 0.75),
- items: [],
- hadMultipleClients: true,
- });
- listHeadMock.mockResolvedValueOnce({
- limit: 5,
- queueModifiedAt: new Date(Date.now() - API_PROCESSED_REQUESTS_DELAY_MILLIS),
- items: [],
- hadMultipleClients: true,
- });
-
- const isFinished = await queue.isFinished();
- expect(isFinished).toBe(true);
- expect(listHeadMock).toHaveBeenCalledTimes(2);
- expect(listHeadMock).toHaveBeenNthCalledWith(1, { limit: QUERY_HEAD_MIN_LENGTH });
- expect(listHeadMock).toHaveBeenNthCalledWith(2, { limit: QUERY_HEAD_MIN_LENGTH });
- });
-
- test('should always wait for a queue head to become consistent before marking queue as finished (hadMultipleClients = false)', async () => {
- const queueId = 'some-id';
- const queue = await createRequestQueue(queueId, 'some-name');
-
- expect(queue.assumedTotalCount).toBe(0);
- expect(queue.assumedHandledCount).toBe(0);
-
- // Add some requests.
- const requestA = new Request({ url: 'http://example.com/a' });
- const requestAWithId = { ...requestA, id: 'a' } as Request;
- const requestB = new Request({ url: 'http://example.com/b' });
- const requestBWithId = { ...requestB, id: 'b' } as Request;
- const addRequestMock = vitest.spyOn(queue.client, 'addRequest');
- addRequestMock.mockResolvedValueOnce({ requestId: 'a', wasAlreadyHandled: false, wasAlreadyPresent: false });
- addRequestMock.mockResolvedValueOnce({ requestId: 'b', wasAlreadyHandled: false, wasAlreadyPresent: false });
-
- await queue.addRequest(requestA, { forefront: true });
- await queue.addRequest(requestB, { forefront: true });
-
- expect(queue['queueHeadIds'].length()).toBe(2);
- expect(queue.inProgressCount()).toBe(0);
- expect(queue.assumedTotalCount).toBe(2);
- expect(queue.assumedHandledCount).toBe(0);
- expect(addRequestMock).toHaveBeenCalledTimes(2);
- expect(addRequestMock).toHaveBeenNthCalledWith(1, requestA, { forefront: true });
- expect(addRequestMock).toHaveBeenNthCalledWith(2, requestB, { forefront: true });
-
- // It won't query the head as there is something in progress or pending.
- const listHeadMock = vitest.spyOn(queue.client, 'listHead');
-
- const isFinished = await queue.isFinished();
- expect(isFinished).toBe(false);
- expect(listHeadMock).not.toHaveBeenCalled();
-
- // Fetch them from queue.
- const getRequestMock = vitest.spyOn(queue.client, 'getRequest');
- getRequestMock.mockResolvedValueOnce({ ...requestB, id: 'b' });
- getRequestMock.mockResolvedValueOnce({ ...requestA, id: 'a' });
-
- const requestBFromQueue = await queue.fetchNextRequest();
- expect(requestBFromQueue).toEqual(requestBWithId);
- expect(getRequestMock).toHaveBeenCalledTimes(1);
- expect(getRequestMock).toHaveBeenLastCalledWith('b');
- const requestAFromQueue = await queue.fetchNextRequest();
- expect(requestAFromQueue).toEqual(requestAWithId);
- expect(getRequestMock).toHaveBeenCalledTimes(2);
- expect(getRequestMock).toHaveBeenLastCalledWith('a');
-
- expect(queue['queueHeadIds'].length()).toBe(0);
- expect(queue.inProgressCount()).toBe(2);
- expect(queue.assumedTotalCount).toBe(2);
- expect(queue.assumedHandledCount).toBe(0);
-
- // It won't query the head as there is something in progress or pending.
- expect(await queue.isFinished()).toBe(false);
- expect(listHeadMock).not.toHaveBeenCalled();
-
- // Reclaim one and mark another one handled.
- const updateRequestMock = vitest.spyOn(queue.client, 'updateRequest');
- updateRequestMock.mockResolvedValueOnce({ requestId: 'b', wasAlreadyHandled: false, wasAlreadyPresent: true });
-
- await queue.markRequestHandled(requestBWithId);
- expect(updateRequestMock).toHaveBeenCalledTimes(1);
- expect(updateRequestMock).toHaveBeenLastCalledWith(requestBWithId);
-
- updateRequestMock.mockResolvedValueOnce({ requestId: 'a', wasAlreadyHandled: false, wasAlreadyPresent: true });
-
- await queue.reclaimRequest(requestAWithId, { forefront: true });
- expect(updateRequestMock).toHaveBeenCalledTimes(2);
- expect(updateRequestMock).toHaveBeenLastCalledWith(requestAWithId, { forefront: true });
-
- expect(queue['queueHeadIds'].length()).toBe(0);
- expect(queue.inProgressCount()).toBe(1);
- expect(queue.assumedTotalCount).toBe(2);
- expect(queue.assumedHandledCount).toBe(1);
- await sleep(STORAGE_CONSISTENCY_DELAY_MILLIS + 10);
-
- expect(queue['queueHeadIds'].length()).toBe(1);
- expect(queue.inProgressCount()).toBe(0);
- expect(queue.assumedTotalCount).toBe(2);
- expect(queue.assumedHandledCount).toBe(1);
-
- // It won't query the head as there is something in progress or pending.
- expect(await queue.isFinished()).toBe(false);
- expect(listHeadMock).not.toHaveBeenCalled();
-
- // Fetch again.
- // @ts-expect-error Argument of type 'Request' is not assignable to parameter of type
- // 'RequestQueueClientGetRequestResult | Promise<RequestQueueClientGetRequestResult>'.
- getRequestMock.mockResolvedValueOnce(requestAWithId);
-
- const requestAFromQueue2 = await queue.fetchNextRequest();
- expect(requestAFromQueue2).toEqual(requestAWithId);
- expect(getRequestMock).toHaveBeenCalledTimes(3);
- expect(getRequestMock).toHaveBeenLastCalledWith('a');
-
- expect(queue['queueHeadIds'].length()).toBe(0);
- expect(queue.inProgressCount()).toBe(1);
- expect(queue.assumedTotalCount).toBe(2);
- expect(queue.assumedHandledCount).toBe(1);
-
- // It won't query the head as there is something in progress or pending.
- expect(await queue.isFinished()).toBe(false);
- expect(listHeadMock).not.toHaveBeenCalled();
-
- // Mark handled.
- updateRequestMock.mockResolvedValueOnce({ requestId: 'a', wasAlreadyHandled: false, wasAlreadyPresent: true });
-
- await queue.markRequestHandled(requestAWithId);
- expect(updateRequestMock).toHaveBeenCalledTimes(3);
- expect(updateRequestMock).toHaveBeenLastCalledWith(requestAWithId);
-
- expect(queue['queueHeadIds'].length()).toBe(0);
- expect(queue.inProgressCount()).toBe(0);
- expect(queue.assumedTotalCount).toBe(2);
- expect(queue.assumedHandledCount).toBe(2);
-
- // Return head with modifiedAt = now so it would retry the query for queue to become consistent but because hadMultipleClients=true
- // it will finish immediately.
- listHeadMock.mockResolvedValueOnce({
- limit: 5,
- queueModifiedAt: new Date(),
- items: [],
- hadMultipleClients: false,
- });
-
- expect(await queue.isFinished()).toBe(true);
- expect(listHeadMock).toHaveBeenCalledTimes(1);
- expect(listHeadMock).toHaveBeenLastCalledWith({ limit: QUERY_HEAD_MIN_LENGTH });
- });
-
- test('`fetchNextRequest` order respects `forefront` enqueues', async () => {
- const emulator = new MemoryStorageEmulator();
-
- await emulator.init();
- const queue = await RequestQueue.open();
-
- const retrievedUrls: string[] = [];
-
- await queue.addRequests([
- { url: 'http://example.com/1' },
- { url: 'http://example.com/5' },
- { url: 'http://example.com/6' },
- ]);
-
- retrievedUrls.push((await queue.fetchNextRequest())!.url);
-
- await queue.addRequest({ url: 'http://example.com/4' }, { forefront: true });
- await queue.addRequest({ url: 'http://example.com/3' }, { forefront: true });
-
- await queue.addRequest({ url: 'http://example.com/2' }, { forefront: true });
-
- let req = await queue.fetchNextRequest();
-
- expect(req!.url).toBe('http://example.com/2');
-
- await queue.reclaimRequest(req!, { forefront: true });
-
- while (req) {
- retrievedUrls.push(req!.url);
- req = await queue.fetchNextRequest();
- }
-
- expect(retrievedUrls.map((x) => new URL(x).pathname)).toEqual(['/1', '/2', '/3', '/4', '/5', '/6']);
- await emulator.destroy();
- });
-
test('getInfo() should work', async () => {
const queue = await createRequestQueue('some-id', 'some-name');
@@ -815,6 +373,26 @@ describe('RequestQueue remote', () => {
r3.maxRetries = 2;
expect(r3.userData.__crawlee).toEqual({ maxRetries: 2 });
});
+
+ describe('setExpectedRequestProcessingTimeSecs', () => {
+ test('forwards the value to the client, but only ever raises it', async () => {
+ const queue = await createRequestQueue();
+ const spy = vitest.spyOn(queue.client, 'setExpectedRequestProcessingTimeSecs');
+
+ // First hint is forwarded.
+ queue.setExpectedRequestProcessingTimeSecs(60);
+ expect(spy).toHaveBeenLastCalledWith(60);
+
+ // A larger hint is forwarded.
+ queue.setExpectedRequestProcessingTimeSecs(120);
+ expect(spy).toHaveBeenLastCalledWith(120);
+
+ // A smaller (or equal) hint must not shorten the reservation, so it is not forwarded.
+ queue.setExpectedRequestProcessingTimeSecs(30);
+ queue.setExpectedRequestProcessingTimeSecs(120);
+ expect(spy).toHaveBeenCalledTimes(2);
+ });
+ });
});
describe('RequestQueue with requestsFromUrl', () => {
@@ -942,7 +520,7 @@ describe('RequestQueue with requestsFromUrl', () => {
});
});
-describe('RequestQueue v2', () => {
+describe('RequestQueue (request lifecycle)', () => {
const totalRequestsPerTest = 50;
function calculateHistogram(requests: { uniqueKey: string }[]): number[] {
@@ -957,9 +535,9 @@ describe('RequestQueue v2', () => {
}
async function getEmptyQueue(name: string) {
- const queue = await RequestQueueV2.open({ name });
+ const queue = await RequestQueue.open({ name });
await queue.drop();
- return RequestQueueV2.open({ name });
+ return RequestQueue.open({ name });
}
function getUniqueRequests(count: number) {
@@ -968,71 +546,45 @@ describe('RequestQueue v2', () => {
.map((_, i) => new Request({ url: `http://example.com/${i}`, uniqueKey: String(i) }));
}
- test('listAndLockHead works as expected', async () => {
- const queue = await getEmptyQueue('list-and-lock-head');
+ test('each request is fetched for processing exactly once', async () => {
+ const queue = await getEmptyQueue('fetch-each-once');
await queue.addRequests(getUniqueRequests(totalRequestsPerTest));
- const [{ items: firstFetch }, { items: secondFetch }] = await Promise.all([
- queue.client.listAndLockHead({ limit: totalRequestsPerTest / 2, lockSecs: 60 }),
- queue.client.listAndLockHead({ limit: totalRequestsPerTest / 2, lockSecs: 60 }),
- ]);
+ const fetched: { uniqueKey: string }[] = [];
+ for (let req = await queue.fetchNextRequest(); req !== null; req = await queue.fetchNextRequest()) {
+ fetched.push(req);
+ }
- const histogram = calculateHistogram([...firstFetch, ...secondFetch]);
+ const histogram = calculateHistogram(fetched);
expect(histogram).toEqual(Array(totalRequestsPerTest).fill(1));
});
- test('lock timers work as expected (timeout unlocks)', async () => {
- vitest.useFakeTimers();
- const queue = await getEmptyQueue('lock-timers');
- await queue.addRequests(getUniqueRequests(totalRequestsPerTest));
-
- const { items: firstFetch } = await queue.client.listAndLockHead({
- limit: totalRequestsPerTest / 2,
- lockSecs: 60,
- });
-
- vitest.advanceTimersByTime(65000);
-
- const { items: secondFetch } = await queue.client.listAndLockHead({
- limit: totalRequestsPerTest / 2,
- lockSecs: 60,
- });
-
- const histogram = calculateHistogram([...firstFetch, ...secondFetch]);
- expect(histogram).toEqual(Array(totalRequestsPerTest / 2).fill(2));
- vitest.useRealTimers();
- });
-
- test('prolongRequestLock works as expected', async () => {
- vitest.useFakeTimers();
- const queue = await getEmptyQueue('prolong-request-lock');
+ test('a fetched request is not served again until it is reclaimed', async () => {
+ const queue = await getEmptyQueue('fetch-in-progress');
await queue.addRequests(getUniqueRequests(1));
- const { items: firstFetch } = await queue.client.listAndLockHead({ limit: 1, lockSecs: 60 });
- await queue.client.prolongRequestLock(firstFetch[0].id, { lockSecs: 60 });
- expect(firstFetch).toHaveLength(1);
+ const first = await queue.fetchNextRequest();
+ expect(first).not.toBeNull();
- vitest.advanceTimersByTime(65000);
- const { items: secondFetch } = await queue.client.listAndLockHead({ limit: 1, lockSecs: 60 });
- expect(secondFetch).toHaveLength(0);
+ // The only request is now in progress, so there is nothing more to fetch.
+ expect(await queue.fetchNextRequest()).toBeNull();
- vitest.advanceTimersByTime(65000);
- const { items: thirdFetch } = await queue.client.listAndLockHead({ limit: 1, lockSecs: 60 });
+ // Reclaiming returns it to the queue so it can be fetched again.
+ await queue.reclaimRequest(first!);
- expect(thirdFetch).toHaveLength(1);
- vitest.useRealTimers();
+ const second = await queue.fetchNextRequest();
+ expect(second!.uniqueKey).toBe(first!.uniqueKey);
});
- test('deleteRequestLock works as expected', async () => {
- const queue = await getEmptyQueue('delete-request-lock');
+ test('a handled request is never served again', async () => {
+ const queue = await getEmptyQueue('handled-not-served');
await queue.addRequests(getUniqueRequests(1));
- const { items: firstFetch } = await queue.client.listAndLockHead({ limit: 1, lockSecs: 60 });
- await queue.client.deleteRequestLock(firstFetch[0].id);
-
- const { items: secondFetch } = await queue.client.listAndLockHead({ limit: 1, lockSecs: 60 });
+ const first = await queue.fetchNextRequest();
+ await queue.markRequestAsHandled(first!);
- expect(secondFetch[0]).toEqual(firstFetch[0]);
+ expect(await queue.fetchNextRequest()).toBeNull();
+ expect(await queue.isFinished()).toBe(true);
});
test('`fetchNextRequest` order respects `forefront` enqueues', async () => {
diff --git a/test/e2e/cheerio-request-queue-v2/actor/main.js b/test/e2e/cheerio-request-queue-v2/actor/main.js
index 60e9c81b5..6f4f77220 100644
--- a/test/e2e/cheerio-request-queue-v2/actor/main.js
+++ b/test/e2e/cheerio-request-queue-v2/actor/main.js
@@ -22,9 +22,6 @@ await Actor.main(async () => {
await Dataset.pushData({ url, pageTitle });
},
- experiments: {
- requestLocking: true,
- },
log: Logger.child({
prefix: 'CheerioCrawler',
// level: LogLevel.DEBUG,
diff --git a/test/e2e/request-queue-zero-concurrency/actor/main.js b/test/e2e/request-queue-zero-concurrency/actor/main.js
index 13a8aa8cd..845612c9d 100644
--- a/test/e2e/request-queue-zero-concurrency/actor/main.js
+++ b/test/e2e/request-queue-zero-concurrency/actor/main.js
@@ -1,4 +1,4 @@
-import { CheerioCrawler, log, RequestQueueV1 } from '@crawlee/cheerio';
+import { CheerioCrawler, log, RequestQueue } from '@crawlee/cheerio';
import { Actor } from 'apify';
log.setLevel(log.LEVELS.DEBUG);
@@ -15,7 +15,7 @@ const mainOptions = {
// RequestQueue auto-reset when stuck with requests in progress
await Actor.main(async () => {
- const requestQueue = await RequestQueueV1.open();
+ const requestQueue = await RequestQueue.open();
await requestQueue.addRequest({ url: 'https://crawlee.dev/?q=1' });
await requestQueue.addRequest({ url: 'https://crawlee.dev/?q=2' });
const r3 = await requestQueue.addRequest({ url: 'https://crawlee.dev/?q=3' });
diff --git a/test/shared/MemoryStorageEmulator.ts b/test/shared/MemoryStorageEmulator.ts
index c48a826c9..d244ec672 100644
--- a/test/shared/MemoryStorageEmulator.ts
+++ b/test/shared/MemoryStorageEmulator.ts
@@ -43,10 +43,30 @@ export class MemoryStorageEmulator extends StorageEmulator {
return this.storage.createRequestQueueClient(id ? { id } : { alias: '__default__' });
}
+ /**
+ * Returns the pending (not yet handled) requests currently in the queue.
+ *
+ * The slim {@link RequestQueueClient} interface has no `listHead`, so we drain the pending
+ * requests via `fetchNextRequest` and immediately reclaim them, leaving the queue unchanged.
+ */
async getRequestQueueItems(id?: string) {
const requestQueue = await this.getRequestQueue(id);
- const { items: heads } = await requestQueue.listHead();
- return heads;
+
+ const items = [];
+ for (
+ let request = await requestQueue.fetchNextRequest();
+ request !== null;
+ request = await requestQueue.fetchNextRequest()
+ ) {
+ items.push(request);
+ }
+
+ // Reclaim everything we fetched so the queue is left in its original state.
+ for (const request of items) {
+ await requestQueue.reclaimRequest({ ...request, id: String(request.id) } as any);
+ }
+
+ return items;
}
getKeyValueStore(id?: string) {
diff --git a/website/sidebars.js b/website/sidebars.js
index 96a9759a2..85e39e5a6 100644
--- a/website/sidebars.js
+++ b/website/sidebars.js
@@ -103,22 +103,6 @@ module.exports = {
},
],
},
- {
- type: 'category',
- label: 'Experiments',
- link: {
- type: 'generated-index',
- title: 'Experiments',
- slug: '/experiments',
- keywords: ['experiments', 'experimental-features'],
- },
- items: [
- {
- type: 'autogenerated',
- dirName: 'experiments',
- },
- ],
- },
{
type: 'category',
label: 'Upgrading',