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(browser-pool): preserve caller's AbortContext across p-limit queue (#3673)

Jindřich Bärc4d58d96a538
diff --git a/packages/browser-pool/src/browser-pool.ts b/packages/browser-pool/src/browser-pool.ts
index 8c26ee8b8..53a27c3df 100644
--- a/packages/browser-pool/src/browser-pool.ts
+++ b/packages/browser-pool/src/browser-pool.ts
@@ -1,3 +1,5 @@
+import { AsyncResource } from 'node:async_hooks';
+
import type { TieredProxy } from '@crawlee/core';
import type { BrowserFingerprintWithHeaders } from 'fingerprint-generator';
import { FingerprintGenerator } from 'fingerprint-generator';
@@ -445,16 +447,25 @@ export class BrowserPool<
throw new Error('Provided browserPlugin is not one of the plugins used by BrowserPool.');
}
+ // Bind the limiter callback to the current async-hooks context. p-limit
+ // otherwise resumes queued callbacks in the previous task's
+ // AsyncLocalStorage context, leaking aborted cancelTasks across unrelated
+ // requests (https://github.com/apify/crawlee/issues/3670). Mirrors the
+ // fix p-limit landed upstream in v5 (sindresorhus/p-limit#71); v5 is an
+ // ESM-only rewrite, so we can't bump it in Crawlee v3.
+ // TODO(crawlee@v4): bump p-limit to v5 and drop this AsyncResource.bind wrapper.
// Limiter is necessary - https://github.com/apify/crawlee/issues/1126
- return this.limiter(async () => {
- let browserController = this._pickBrowserWithFreeCapacity(browserPlugin, { proxyTier, proxyUrl });
+ return this.limiter(
+ AsyncResource.bind(async () => {
+ let browserController = this._pickBrowserWithFreeCapacity(browserPlugin, { proxyTier, proxyUrl });
- if (!browserController)
- browserController = await this._launchBrowser(id, { browserPlugin, proxyTier, proxyUrl });
- tryCancel();
+ if (!browserController)
+ browserController = await this._launchBrowser(id, { browserPlugin, proxyTier, proxyUrl });
+ tryCancel();
- return await this._createPageForBrowser(id, browserController, pageOptions, proxyUrl);
- });
+ return await this._createPageForBrowser(id, browserController, pageOptions, proxyUrl);
+ }),
+ );
}
/**
diff --git a/test/browser-pool/browser-pool.test.ts b/test/browser-pool/browser-pool.test.ts
index c20cf65bd..4a004d53a 100644
--- a/test/browser-pool/browser-pool.test.ts
+++ b/test/browser-pool/browser-pool.test.ts
@@ -123,6 +123,38 @@ describe.each([
expect(page.close).toBeDefined();
});
+ // https://github.com/apify/crawlee/issues/3670
+ test('should not leak aborted cancelTask between concurrent newPage calls', async () => {
+ const previousTimeout = browserPool.operationTimeoutMillis;
+ browserPool.operationTimeoutMillis = 1;
+
+ // Each newPage call is wrapped in its own outer addTimeoutToPromise,
+ // matching how BasicCrawler wraps _runRequestHandler. Without the fix,
+ // queued limiter callbacks inherit the previous task's aborted
+ // cancelTask via AsyncLocalStorage propagation through p-limit, causing
+ // their first tryCancel() to throw InternalTimeoutError pre-emptively;
+ // that error then gets silently swallowed by the outer wrap.
+ const results = await Promise.allSettled(
+ Array.from({ length: 5 }, () =>
+ addTimeoutToPromise(async () => browserPool.newPage(), 60_000, 'outer timed out'),
+ ),
+ );
+
+ browserPool.operationTimeoutMillis = previousTimeout;
+ browserPool.retireAllBrowsers();
+
+ // All calls must reject — none should silently resolve with undefined.
+ expect(results.every((r) => r.status === 'rejected')).toBe(true);
+
+ // Each rejection should reflect this call's own newPage timeout, not
+ // a leaked "canceled due to a timeout" from a sibling's aborted context.
+ for (const r of results) {
+ expect(r.status === 'rejected' && (r.reason as Error).message).toMatch(
+ /browserController\.newPage\(\) (failed|timed out)/,
+ );
+ }
+ });
+
// TODO: this test is very flaky in the CI
test.skip('should allow early aborting in case of outer timeout', async () => {
const timeout = browserPool.operationTimeoutMillis;
diff --git a/test/core/crawlers/playwright_crawler.test.ts b/test/core/crawlers/playwright_crawler.test.ts
index 2acf7a91c..f6ce30186 100644
--- a/test/core/crawlers/playwright_crawler.test.ts
+++ b/test/core/crawlers/playwright_crawler.test.ts
@@ -141,6 +141,41 @@ describe('PlaywrightCrawler', () => {
});
});
+ // https://github.com/apify/crawlee/issues/3670
+ test('should not silently drop requests when BrowserPool.newPage() times out', async () => {
+ const success: string[] = [];
+ const failure: string[] = [];
+
+ const crawler = new PlaywrightCrawler({
+ maxRequestRetries: 0,
+ browserPoolOptions: {
+ operationTimeoutSecs: 0.001,
+ },
+ requestHandler: async ({ request }) => {
+ success.push(request.url);
+ },
+ failedRequestHandler: async ({ request }) => {
+ failure.push(request.url);
+ },
+ });
+
+ const urls = [
+ `http://${HOSTNAME}:${port}/?q=1`,
+ `http://${HOSTNAME}:${port}/?q=2`,
+ `http://${HOSTNAME}:${port}/?q=3`,
+ `http://${HOSTNAME}:${port}/?q=4`,
+ `http://${HOSTNAME}:${port}/?q=5`,
+ ];
+
+ const stats = await crawler.run(urls);
+
+ // Every request must be accounted for by either requestHandler or failedRequestHandler.
+ expect(success.length + failure.length).toBe(urls.length);
+ // With operationTimeoutSecs=0.001, no request can actually succeed, so every one must fail.
+ expect(stats.requestsFinished).toBe(0);
+ expect(stats.requestsFailed).toBe(urls.length);
+ });
+
test('should override goto timeout with navigationTimeoutSecs', async () => {
const timeoutSecs = 10;
let options: PlaywrightGotoOptions;