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.

fix: Prevent accidental request dropping with `maxRequestsPerCrawl` (#3531)

Jan Bucharb23319bbe8c1
diff --git a/packages/basic-crawler/src/internals/basic-crawler.ts b/packages/basic-crawler/src/internals/basic-crawler.ts
index 3ff8e2c63..850dda046 100644
--- a/packages/basic-crawler/src/internals/basic-crawler.ts
+++ b/packages/basic-crawler/src/internals/basic-crawler.ts
@@ -1202,7 +1202,6 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContext
const requestLimit = this.calculateEnqueuedRequestLimit();
const skippedBecauseOfRobots = new Set<string>();
- const skippedBecauseOfLimit = new Set<string>();
const skippedBecauseOfMaxCrawlDepth = new Set<string>();
const isAllowedBasedOnRobotsTxtFile = this.isAllowedBasedOnRobotsTxtFile.bind(this);
@@ -1216,16 +1215,9 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContext
);
async function* filteredRequests() {
- let yieldedRequestCount = 0;
-
for await (const request of requests) {
const url = typeof request === 'string' ? request : request.url!;
- if (requestLimit !== undefined && yieldedRequestCount >= requestLimit) {
- skippedBecauseOfLimit.add(url);
- continue;
- }
-
if (maxCrawlDepth !== undefined && (request as any).crawlDepth > maxCrawlDepth) {
skippedBecauseOfMaxCrawlDepth.add(url);
continue;
@@ -1233,14 +1225,19 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContext
if (await isAllowedBasedOnRobotsTxtFile(url)) {
yield request;
- yieldedRequestCount += 1;
} else {
skippedBecauseOfRobots.add(url);
}
}
}
- const result = await this.requestManager!.addRequestsBatched(filteredRequests(), options);
+ const result = await this.requestManager!.addRequestsBatched(filteredRequests(), {
+ ...options,
+ maxNewRequests: requestLimit,
+ });
+
+ // Report requests skipped due to the maxNewRequests budget (i.e. maxRequestsPerCrawl limit)
+ const skippedBecauseOfLimit = result.requestsOverLimit ?? [];
if (skippedBecauseOfRobots.size > 0) {
this.log.warning(`Some requests were skipped because they were disallowed based on the robots.txt file`, {
@@ -1250,7 +1247,7 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContext
if (
skippedBecauseOfRobots.size > 0 ||
- skippedBecauseOfLimit.size > 0 ||
+ skippedBecauseOfLimit.length > 0 ||
skippedBecauseOfMaxCrawlDepth.size > 0
) {
await Promise.all(
@@ -1259,7 +1256,8 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContext
return this.handleSkippedRequest({ url, reason: 'robotsTxt' });
})
.concat(
- [...skippedBecauseOfLimit].map((url) => {
+ skippedBecauseOfLimit.map((request) => {
+ const url = typeof request === 'string' ? request : request.url!;
return this.handleSkippedRequest({ url, reason: 'limit' });
}),
[...skippedBecauseOfMaxCrawlDepth].map((url) => {
diff --git a/packages/core/src/enqueue_links/enqueue_links.ts b/packages/core/src/enqueue_links/enqueue_links.ts
index 5d6d2fce0..5668e9353 100644
--- a/packages/core/src/enqueue_links/enqueue_links.ts
+++ b/packages/core/src/enqueue_links/enqueue_links.ts
@@ -488,17 +488,19 @@ export async function enqueueLinks(
return filtered;
}
- let requests = await createFilteredRequests();
- if (typeof limit === 'number' && limit < requests.length) {
- await reportSkippedRequests(requests.slice(limit), 'enqueueLimit');
- requests = requests.slice(0, limit);
- }
-
- const { addedRequests } = await requestQueue.addRequestsBatched(requests, {
+ const { addedRequests, requestsOverLimit } = await requestQueue.addRequestsBatched(await createFilteredRequests(), {
forefront,
waitForAllRequestsToBeAdded,
+ maxNewRequests: limit,
});
+ if (requestsOverLimit?.length !== undefined && requestsOverLimit.length > 0) {
+ await reportSkippedRequests(
+ requestsOverLimit.map((r) => ({ url: typeof r === 'string' ? r : r.url! })),
+ 'enqueueLimit',
+ );
+ }
+
return { processedRequests: addedRequests, unprocessedRequests: [] };
}
diff --git a/packages/core/src/storages/request_provider.ts b/packages/core/src/storages/request_provider.ts
index dc1204abf..e4105e856 100644
--- a/packages/core/src/storages/request_provider.ts
+++ b/packages/core/src/storages/request_provider.ts
@@ -413,6 +413,7 @@ export abstract class RequestProvider implements IStorage, IRequestManager {
waitForAllRequestsToBeAdded: ow.optional.boolean,
batchSize: ow.optional.number,
waitBetweenBatchesMillis: ow.optional.number,
+ maxNewRequests: ow.optional.number,
}),
);
@@ -454,9 +455,21 @@ export abstract class RequestProvider implements IStorage, IRequestManager {
}
}
- const { batchSize = 1000, waitBetweenBatchesMillis = 1000 } = options;
+ const { batchSize = 1000, waitBetweenBatchesMillis = 1000, maxNewRequests } = options;
- const chunks = peekableAsyncIterable(chunkedAsyncIterable(generateRequests(), batchSize));
+ 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) => {
@@ -480,21 +493,55 @@ export abstract class RequestProvider implements IStorage, IRequestManager {
return resultsToReturn;
};
- // Add initial batch of `batchSize` to process them right away
+ /**
+ * 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 { addedRequests: [], waitForAllRequestsToBeAdded: Promise.resolve([]) };
+ return buildResult([], Promise.resolve([]), requestIterator);
}
- const addedRequests = await attemptToAddToQueueAndAddAnyUnprocessed(initialChunk);
+ const addedRequests = await processChunk(initialChunk);
await chunksIterator.next();
- // If we have no more requests to add, return immediately
+ // If we have no more requests to add (either exhausted or budget hit), return immediately
if ((await chunksIterator.peek()) === undefined) {
- return {
- addedRequests,
- waitForAllRequestsToBeAdded: Promise.resolve([]),
- };
+ return buildResult(addedRequests, Promise.resolve([]), requestIterator);
}
// eslint-disable-next-line no-async-promise-executor
@@ -502,8 +549,7 @@ export abstract class RequestProvider implements IStorage, IRequestManager {
const finalAddedRequests: ProcessedRequest[] = [];
for await (const requestChunk of chunks) {
- finalAddedRequests.push(...(await attemptToAddToQueueAndAddAnyUnprocessed(requestChunk, false)));
-
+ finalAddedRequests.push(...(await processChunk(requestChunk, false)));
await sleep(waitBetweenBatchesMillis);
}
@@ -515,15 +561,12 @@ export abstract class RequestProvider implements IStorage, IRequestManager {
this.inProgressRequestBatchCount -= 1;
});
- // If the user wants to wait for all the requests to be added, we wait for the promise to resolve for them
- if (options.waitForAllRequestsToBeAdded) {
+ // 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 {
- addedRequests,
- waitForAllRequestsToBeAdded: promise,
- };
+ return buildResult(addedRequests, promise, requestIterator);
}
/**
@@ -980,6 +1023,18 @@ export interface AddRequestsBatchedOptions extends RequestQueueOperationOptions
* @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 {
@@ -1001,4 +1056,11 @@ export interface AddRequestsBatchedResult {
* ```
*/
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/playwright-crawler/src/internals/adaptive-playwright-crawler.ts b/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts
index 2e6d5c91f..1766ac47d 100644
--- a/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts
+++ b/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts
@@ -708,6 +708,7 @@ export class AdaptivePlaywrightCrawler extends PlaywrightCrawler {
wasAlreadyHandled: false,
})),
waitForAllRequestsToBeAdded: Promise.resolve([]),
+ requestsOverLimit: [],
};
};
// We need to use a mock request queue implementation, in order to add the requests into our result object
diff --git a/packages/utils/src/internals/iterables.ts b/packages/utils/src/internals/iterables.ts
index ed55bde56..36f6d0f24 100644
--- a/packages/utils/src/internals/iterables.ts
+++ b/packages/utils/src/internals/iterables.ts
@@ -85,24 +85,34 @@ export async function* asyncifyIterable<T>(iterable: Iterable<T> | AsyncIterable
*/
export async function* chunkedAsyncIterable<T>(
iterable: AsyncIterable<T> | Iterable<T>,
- chunkSize: number,
+ chunkSize: number | (() => number),
): AsyncIterable<T[]> {
- if (typeof chunkSize !== 'number' || chunkSize < 1) {
+ const getChunkSize = typeof chunkSize === 'function' ? chunkSize : () => chunkSize;
+
+ if (typeof chunkSize === 'number' && chunkSize < 1) {
throw new Error(`Chunk size must be a positive number (${inspect(chunkSize)}) received`);
}
- let chunk: T[] = [];
+ const iterator =
+ Symbol.asyncIterator in iterable
+ ? (iterable as AsyncIterable<T>)[Symbol.asyncIterator]()
+ : (iterable as Iterable<T>)[Symbol.iterator]();
+
+ while (true) {
+ const currentSize = getChunkSize();
+ if (currentSize < 1) break;
- for await (const item of iterable) {
- chunk.push(item);
+ const chunk: T[] = [];
- if (chunk.length >= chunkSize) {
- yield chunk;
- chunk = [];
+ for (let i = 0; i < currentSize; i++) {
+ const next = await iterator.next();
+ if (next.done) {
+ break;
+ }
+ chunk.push(next.value);
}
- }
- if (chunk.length) {
+ if (chunk.length === 0) break;
yield chunk;
}
}
diff --git a/test/core/crawlers/basic_crawler.test.ts b/test/core/crawlers/basic_crawler.test.ts
index c455fbf4f..16410e298 100644
--- a/test/core/crawlers/basic_crawler.test.ts
+++ b/test/core/crawlers/basic_crawler.test.ts
@@ -250,7 +250,11 @@ describe('BasicCrawler', () => {
const crawler = new TestCrawler({ maxCrawlDepth: 3 });
beforeEach(() => {
- addRequestsBatchedMock = vi.fn().mockImplementation(async () => ({}));
+ addRequestsBatchedMock = vi.fn().mockImplementation(async () => ({
+ addedRequests: [],
+ waitForAllRequestsToBeAdded: Promise.resolve([]),
+ requestsOverLimit: [],
+ }));
onSkippedRequestMock = vi.fn();
options = {
@@ -1885,6 +1889,102 @@ describe('BasicCrawler', () => {
);
expect(maxCrawlDepthMessages).toHaveLength(1);
});
+
+ test('should not count duplicate URLs toward maxRequestsPerCrawl limit (addRequests)', async () => {
+ const requestQueue = await RequestQueue.open();
+
+ const crawler = new BasicCrawler({
+ requestQueue,
+ maxRequestsPerCrawl: 5,
+ requestHandler: async () => {},
+ });
+
+ // 10 duplicate links to the same URL + 1 unique link at the end
+ const requestsToAdd = [
+ ...Array.from({ length: 10 }, () => 'http://example.com/same'),
+ 'http://example.com/new',
+ ];
+
+ await crawler.addRequests(requestsToAdd);
+
+ // Both unique URLs should have been enqueued — duplicates should not consume the budget
+ await expect(localStorageEmulator.getRequestQueueItems()).resolves.toMatchObject([
+ { url: 'http://example.com/same' },
+ { url: 'http://example.com/new' },
+ ]);
+ });
+
+ test('addRequestsBatched with maxNewRequests should correctly report requestsOverLimit for array input', async () => {
+ const queue = await RequestQueue.open();
+
+ const result = await queue.addRequestsBatched(
+ [
+ { url: 'http://example.com/a' },
+ { url: 'http://example.com/b' },
+ { url: 'http://example.com/c' },
+ { url: 'http://example.com/d' },
+ { url: 'http://example.com/e' },
+ ],
+ { maxNewRequests: 2 },
+ );
+
+ const addedUrls = result.addedRequests.filter((r) => !r.wasAlreadyPresent).map((r) => r.uniqueKey);
+
+ const overLimitUrls = (result.requestsOverLimit ?? []).map((r) => (typeof r === 'string' ? r : r.url));
+
+ expect(addedUrls).toHaveLength(2);
+ expect(overLimitUrls).toHaveLength(3);
+ });
+
+ test('addRequestsBatched with maxNewRequests should correctly report requestsOverLimit for generator input', async () => {
+ const queue = await RequestQueue.open();
+
+ async function* urls() {
+ yield { url: 'http://example.com/a' };
+ yield { url: 'http://example.com/b' };
+ yield { url: 'http://example.com/c' };
+ yield { url: 'http://example.com/d' };
+ yield { url: 'http://example.com/e' };
+ }
+
+ const result = await queue.addRequestsBatched(urls(), { maxNewRequests: 2 });
+
+ const addedUrls = result.addedRequests.filter((r) => !r.wasAlreadyPresent).map((r) => r.uniqueKey);
+
+ const overLimitUrls = (result.requestsOverLimit ?? []).map((r) => (typeof r === 'string' ? r : r.url));
+
+ expect(addedUrls).toHaveLength(2);
+ expect(overLimitUrls).toHaveLength(3);
+ });
+
+ test('should not count duplicate URLs toward maxRequestsPerCrawl limit (enqueueLinks)', async () => {
+ const requestQueue = await RequestQueue.open();
+
+ const visitedUrls: string[] = [];
+
+ const crawler = new BasicCrawler({
+ requestQueue,
+ maxRequestsPerCrawl: 5,
+ requestHandler: async (context) => {
+ visitedUrls.push(context.request.url);
+
+ if (context.request.label) {
+ return;
+ }
+
+ // Enqueue 10 duplicate links + 1 new unique link
+ const urls = [...Array.from({ length: 10 }, () => 'http://example.com/'), 'http://example.com/new'];
+
+ await context.enqueueLinks({ urls, label: 'child' });
+ },
+ });
+
+ await crawler.run(['http://example.com/']);
+
+ // Both the start URL and the new URL should have been visited
+ expect(visitedUrls).toContain('http://example.com/');
+ expect(visitedUrls).toContain('http://example.com/new');
+ });
});
describe('addRequests input validation', () => {
diff --git a/test/core/enqueue_links/enqueue_links.test.ts b/test/core/enqueue_links/enqueue_links.test.ts
index fbf34c604..cede47fec 100644
--- a/test/core/enqueue_links/enqueue_links.test.ts
+++ b/test/core/enqueue_links/enqueue_links.test.ts
@@ -1008,7 +1008,7 @@ describe('enqueueLinks()', () => {
for await (const request of requests) {
enqueued.push({ request: typeof request === 'string' ? { url: request } : request, options });
}
- return { addedRequests: [], waitForAllRequestsToBeAdded: Promise.resolve([]) };
+ return { addedRequests: [], waitForAllRequestsToBeAdded: Promise.resolve([]), requestsOverLimit: [] };
};
await cheerioCrawlerEnqueueLinks({
diff --git a/test/utils/iterables.test.ts b/test/utils/iterables.test.ts
index f571277c2..0a77ead0e 100644
--- a/test/utils/iterables.test.ts
+++ b/test/utils/iterables.test.ts
@@ -92,6 +92,54 @@ describe('chunkedAsyncIterable', () => {
expect(result).toEqual([]);
});
+ it('should accept a callback for dynamic chunk size', async () => {
+ let size = 3;
+ const result = [];
+ for await (const chunk of chunkedAsyncIterable([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], () => size)) {
+ result.push(chunk);
+ size = 2; // shrink after first chunk
+ }
+
+ expect(result).toEqual([[1, 2, 3], [4, 5], [6, 7], [8, 9], [10]]);
+ });
+
+ it('should stop iterating when dynamic chunk size drops to zero', async () => {
+ let size = 2;
+ const result = [];
+ for await (const chunk of chunkedAsyncIterable([1, 2, 3, 4, 5, 6], () => size)) {
+ result.push(chunk);
+ size = 0; // signal stop after first chunk
+ }
+
+ expect(result).toEqual([[1, 2]]);
+ });
+
+ it('should leave the underlying iterator drainable after partial consumption', async () => {
+ async function* source() {
+ yield 1;
+ yield 2;
+ yield 3;
+ yield 4;
+ yield 5;
+ }
+
+ const iterator = source();
+
+ // Consume only the first chunk via chunkedAsyncIterable
+ let size = 2;
+ for await (const _ of chunkedAsyncIterable(iterator, () => size)) {
+ size = 0; // stop after first chunk
+ }
+
+ // The underlying iterator should still be drainable
+ const remaining: number[] = [];
+ for await (const value of iterator) {
+ remaining.push(value);
+ }
+
+ expect(remaining).toEqual([3, 4, 5]);
+ });
+
it('should throw error for invalid chunk size', async () => {
await expect(
(async () => {