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.
TypeScript apifyautomationcrawlercrawlingheadlessheadless-chromejavascriptnodejsnpmplaywrightpuppeteerscraperscrapingtypescriptweb-crawlerweb-crawlingweb-scraping
fix: keep the impit client from timing out before the crawler's deadline (#4215)
Muhammad Haadhee Sheeraz Mian6655629d7a65
diff --git a/docs/package.json b/docs/package.jsonindex a891455fe..0391b76ff 100644--- a/docs/package.json+++ b/docs/package.json@@ -24,7 +24,7 @@"@opentelemetry/semantic-conventions": "^1.39.0","apify": "*","crawlee": "workspace:*",- "impit": "^0.14.2",+ "impit": "^0.14.6","pino": "^10.0.0","playwright-extra": "^4.3.6","puppeteer-extra": "^3.3.6",diff --git a/packages/http-crawler/src/internals/http-crawler.ts b/packages/http-crawler/src/internals/http-crawler.tsindex 183df4b71..500b4c5a0 100644--- a/packages/http-crawler/src/internals/http-crawler.ts+++ b/packages/http-crawler/src/internals/http-crawler.ts@@ -377,6 +377,7 @@ export class HttpCrawler<#suggestResponseEncoding?: string;#forceResponseEncoding?: string;readonly #supportedMimeTypes: Set<string>;+ readonly #downloadAbortControllers = new WeakMap<CrawlingRequest, AbortController>();/*** @internal@@ -546,11 +547,14 @@ export class HttpCrawler<const { request, session } = crawlingContext;const proxyUrl = crawlingContext.proxyInfo?.url;+ const downloadAbortController = new AbortController();+ this.#downloadAbortControllers.set(request, downloadAbortController);+// Bound the request by whatever is left of the shared navigation window (the pre-navigation hooks may// have already spent part of it), so it produces a clean navigation-timeout error rather than the raw// client abort.const httpResponse = await addTimeoutToPromise(- async () => this.#requestFunction({ request, session, proxyUrl }),+ async () => this.#requestFunction({ request, session, proxyUrl, signal: downloadAbortController.signal }),Math.max(1, remainingNavigationWindowMillis(crawlingContext, this.#navigationTimeoutMillis)),`Navigation timed out after ${this.#navigationTimeoutMillis / 1000} seconds.`,);@@ -632,7 +636,11 @@ export class HttpCrawler<async () => this.#parseResponse(crawlingContext.request, crawlingContext.response),remaining,`Navigation timed out after ${this.#navigationTimeoutMillis / 1000} seconds.`,- );+ ).catch((error) => {+ // Stop the download along with the read, so a body that never ends doesn't outlive the request.+ this.#downloadAbortControllers.get(crawlingContext.request)?.abort();+ throw error;+ });tryCancel();const response = parsed.response!;const contentType = parsed.contentType!;@@ -731,11 +739,11 @@ export class HttpCrawler<* on the request such as only downloading the request body if the* received content type matches text/html, application/xml, application/xhtml+xml.*/- async #requestFunction({ request, session, proxyUrl }: RequestFunctionOptions): Promise<Response> {+ async #requestFunction({ request, session, proxyUrl, signal }: RequestFunctionOptions): Promise<Response> {const opts = this.#getRequestOptions(request, proxyUrl);try {- return await this.#requestAsBrowser(opts, session);+ return await this.#requestAsBrowser(opts, session, signal);} catch (e) {if (e instanceof Error && e.constructor.name === 'TimeoutError') {this.#handleRequestTimeout(session);@@ -923,7 +931,7 @@ export class HttpCrawler</*** @internal wraps public utility for mocking purposes*/- #requestAsBrowser = async (options: Dictionary<any>, session: ISession) => {+ #requestAsBrowser = async (options: Dictionary<any>, session: ISession, signal: AbortSignal) => {const opts = processHttpRequestOptions({...(options as any),responseType: 'text',@@ -936,10 +944,11 @@ export class HttpCrawler<// Bind the request to the shared navigation window instead of a fixed per-request timeout, so// `extendTimeout()` can push the deadline and a fixed `AbortSignal.timeout` won't fire on its own and- // kill a lazily-read body mid-extension. This aborts the socket only during the header phase; the body- // read is bounded separately at the promise level (see `processHttpResponse`), so a slow-streaming body- // still fails cleanly with a navigation timeout, though the socket is left to close on its own.+ // kill a lazily-read body mid-extension. The window's signal only covers the header phase; the body read is+ // bounded separately (see `processHttpResponse`), which aborts `signal` when it fails, so a slow-streaming+ // body still fails cleanly with a navigation timeout and its download stops too.const cancelSignal = storage.getStore()?.cancelTask.signal;+ const requestSignal = cancelSignal ? AbortSignal.any([cancelSignal, signal]) : signal;const response = await this.httpClient.sendRequest(new Request(opts.url, {@@ -953,7 +962,7 @@ export class HttpCrawler<session,cookieJar,proxyUrl: opts.proxyUrl,- signal: cancelSignal,+ signal: requestSignal,timeoutMillis: cancelSignal ? undefined : opts.timeout,ignoreTlsErrors: this.#ignoreTlsErrors,},@@ -967,6 +976,7 @@ interface RequestFunctionOptions {request: CrawlingRequest;session: ISession;proxyUrl?: string;+ signal: AbortSignal;}/**diff --git a/packages/impit-client/package.json b/packages/impit-client/package.jsonindex ee1ab61f4..3b7a21e93 100644--- a/packages/impit-client/package.json+++ b/packages/impit-client/package.json@@ -51,7 +51,7 @@"@crawlee/core": "workspace:*","@crawlee/http-client": "workspace:*","@crawlee/types": "workspace:*",- "impit": "^0.14.2",+ "impit": "^0.14.6","tough-cookie": "^6.0.0"}}diff --git a/packages/impit-client/src/index.ts b/packages/impit-client/src/index.tsindex ec2cea26a..a265ae060 100644--- a/packages/impit-client/src/index.ts+++ b/packages/impit-client/src/index.ts@@ -113,10 +113,20 @@ export class ImpitHttpClient extends BaseHttpClient {followRedirects: redirect === 'follow',});- const response = await impit.fetch(request, { signal: signal ?? undefined });+ // The caller's signal carries the deadline (for crawlers, the navigation window that `extendTimeout()` can+ // push out), so impit's 30 s default must not cut the request short. Without a signal, the default stays.+ const response = await impit.fetch(request, {+ signal: signal ?? undefined,+ ...(signal ? { timeout: null } : {}),+ });++ // Once the headers are in, an aborted signal only stops impit's body reads, while the download itself keeps+ // going. Piping the body through the signal cancels the download too.+ const body =+ signal && response.body ? response.body.pipeThrough(new TransformStream(), { signal }) : response.body;// todo - cast shouldn't be needed here, impit returns `Uint8Array`- return new ResponseWithUrl(response.body, response);+ return new ResponseWithUrl(body, response);}#resolveImpitBrowser(fingerprint?: SessionFingerprint): ImpitBrowser | undefined {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 6697a616d..ccd7043a1 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -441,8 +441,8 @@ importers:specifier: workspace:*version: link:../packages/crawleeimpit:- specifier: ^0.14.2- version: 0.14.5+ specifier: ^0.14.6+ version: 0.14.6pino:specifier: ^10.0.0version: 10.4.0@@ -842,8 +842,8 @@ importers:specifier: workspace:*version: link:../typesimpit:- specifier: ^0.14.2- version: 0.14.5+ specifier: ^0.14.6+ version: 0.14.6tough-cookie:specifier: ^6.0.0version: 6.0.2@@ -8284,12 +8284,24 @@ packages:cpu: [arm64]os: [darwin]+ resolution: {integrity: sha512-QhEENTXA727SlgIIIfPg4Ij2FEgwX/3rKCBpR84JxZZfQVVNO/KB2cVvt9aupokY1NZIo6oBFYJXF5PKyRVKbQ==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [darwin]+resolution: {integrity: sha512-EBH6H6SSRuMpw85/n+luT0EcbNbp6vQpUaEywH4bM2bk/xy8y6JN25O/Mzxa4YGUauoytmMqXs0kDzU5lxEjaA==}engines: {node: '>= 10'}cpu: [x64]os: [darwin]+ resolution: {integrity: sha512-BYcBdG7+smXHrhwLGqtWWw1jTsQSWwJO7ZyfkVPMUGRcbPFJAXXKRUjdFWcp2AdMWyI5JufNF3IZzAJ6B++8mw==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [darwin]+resolution: {integrity: sha512-K7gB/KiekPZ+rDoFZqbBf1jROOHibZneGmM0lt/5xcn2lO+7e9GgArdPFj6sh4fvhtOckXxEc1ExpZP+lDy3Cg==}engines: {node: '>= 10'}@@ -8297,6 +8309,13 @@ packages:os: [linux]libc: [glibc]+ resolution: {integrity: sha512-yoUxNCBDsQ72H7uTtaLp7hUQJxr1/OtIZ7KnaerFeJwPpuK2KCeAIXa/9ajoa0GZ6BErm9ZwkggOENhAXu0xxw==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [linux]+ libc: [glibc]+resolution: {integrity: sha512-QvjBwjYu1LXP+ota94z9fThRZjH75/Bai36eHvXUTiiFyesRRsmClc72ReyyaarnNNjcsl2RActqFMDrx77DXg==}engines: {node: '>= 10'}@@ -8304,6 +8323,13 @@ packages:os: [linux]libc: [musl]+ resolution: {integrity: sha512-2UL2ya3uRCdcZwkTL4Oe0RVyhvsONJHhbtD+0VZZkDKyCxyyjtZ6Rc1QQNKh2q/xKa3vNnzj/9qcu0mj/zCk8w==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [linux]+ libc: [musl]+resolution: {integrity: sha512-+8hErR5H3+4N9r4vf5Cz6cSe57n/0zh5ksHBu2H9i5pENcM/VBRJ5qU5a3YjQwN4Ohtw/ROHBLF6V99eXUzThA==}engines: {node: '>= 10'}@@ -8311,6 +8337,13 @@ packages:os: [linux]libc: [glibc]+ resolution: {integrity: sha512-6TJxs/iUQbxQuznb0gz5MQ15WIT4/IxHdwNG9II8kEKUEzVMLCun8IXiT5AGdYzwlmPYSIuxDjtY2ZALhC1FlA==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [linux]+ libc: [glibc]+resolution: {integrity: sha512-e6526hjfX8BV3XNhB1V7Xd3dJIEbLEwudZagwt4XdLqKcxHsU0iYnUyTJCogSQeEtZFepCSKUnGeg/r2lzxHow==}engines: {node: '>= 10'}@@ -8318,22 +8351,45 @@ packages:os: [linux]libc: [musl]+ resolution: {integrity: sha512-AoneCmxaKKCx2wJZGLtFB6LrkTZUEViZ9XEsocpyMsm5IvV3mhj64AGIZI7zHlW7AFXq4MW0DPZkHiL/KxTB1A==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [linux]+ libc: [musl]+resolution: {integrity: sha512-cABSwp3T1kNNp7++nyE8OlRuq8q9Cis3bWRHJjnTncfJ+NQlY0z1z3aLrI9ii1vvinCurCEWASuTptVSor5U1g==}engines: {node: '>= 10'}cpu: [arm64]os: [win32]+ resolution: {integrity: sha512-DRsyV3vNPeUTaRjtFiRqHb8FVFmLDR3NB47cvb+AKKuo+KUbRJdJR1zbDQMD2SOKhYRHf1PTxzamRIkl3yWqWQ==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [win32]+resolution: {integrity: sha512-JvjNkJ3mSB9nf74Ftdlr+KNxCC0EOAH6KUfEUqWRrGEnniIaUOMknxQw56Gbk7Zr1/e5eAOwxS/EBlASp6Yj4w==}engines: {node: '>= 10'}cpu: [x64]os: [win32]+ resolution: {integrity: sha512-0j7OHcgX8ui9ObSelx5v7OEEIfe00EgHcljq9RFR7oFzkD2ABS/6+fSyrXgu2LcC277vJ9oSfKjEacgGoCHOpQ==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [win32]+resolution: {integrity: sha512-MzoDiPBL5+QI5IEro4VDgZdm0BPY0LIf8tUykEFDjEI8NrjRL/qiiCqg4GDlIg5UbJzrKwCdvIgpRRArbbu7Dg==}engines: {node: '>= 20'}+ resolution: {integrity: sha512-1i5DxW0eRIUCtX9x+ZCSzD+FlRiEdrDOXazg0DYNMKUgnVwRWEwRhbA23Lpo2WOC674wZpwTQUubBi5z7m04Ng==}+ engines: {node: '>= 20'}+resolution: {integrity: sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==}engines: {node: '>=6'}@@ -21822,27 +21878,51 @@ snapshots:optional: true+ optional: true+optional: true+ optional: true+optional: true+ optional: true+optional: true+ optional: true+optional: true+ optional: true+optional: true+ optional: true+optional: true+ optional: true+optional: true+ optional: true+optionalDependencies:impit-darwin-arm64: 0.14.5@@ -21854,6 +21934,17 @@ snapshots:impit-win32-arm64-msvc: 0.14.5impit-win32-x64-msvc: 0.14.5+ optionalDependencies:+ impit-darwin-arm64: 0.14.6+ impit-darwin-x64: 0.14.6+ impit-linux-arm64-gnu: 0.14.6+ impit-linux-arm64-musl: 0.14.6+ impit-linux-x64-gnu: 0.14.6+ impit-linux-x64-musl: 0.14.6+ impit-win32-arm64-msvc: 0.14.6+ impit-win32-x64-msvc: 0.14.6+dependencies:parent-module: 1.0.1diff --git a/test/core/crawlers/cheerio-crawler.test.ts b/test/core/crawlers/cheerio-crawler.test.tsindex 903dabe54..7a4a73ef9 100644--- a/test/core/crawlers/cheerio-crawler.test.ts+++ b/test/core/crawlers/cheerio-crawler.test.ts@@ -610,6 +610,41 @@ describe('CheerioCrawler', () => {slowServer.close();}});++ test('stops downloading a response body that outlives the navigation window', async () => {+ let closed = false;+ const endlessServer = createServer((_req, res) => {+ res.writeHead(200, { 'content-type': 'text/html' });+ const interval = setInterval(() => res.write('x'.repeat(1024)), 10);+ res.on('close', () => {+ clearInterval(interval);+ closed = true;+ });+ });+ await new Promise<void>((resolve) => endlessServer.listen(0, resolve));+ const { port: endlessPort } = endlessServer.address() as AddressInfo;++ try {+ const failed: Request[] = [];+ const cheerioCrawler = new CheerioCrawler({+ navigationTimeoutSecs: 1,+ maxRequestRetries: 0,+ httpClient: new ImpitHttpClient(),+ requestHandler: () => {},+ failedRequestHandler: ({ request }) => {+ failed.push(request);+ },+ });++ await cheerioCrawler.run([`http://localhost:${endlessPort}/`]);++ expect(failed).toHaveLength(1);+ await vi.waitFor(() => expect(closed).toBe(true), { timeout: 2000 });+ } finally {+ endlessServer.closeAllConnections();+ endlessServer.close();+ }+ });});describe('should not timeout by the default httpRequest timeoutSecs', () => {diff --git a/test/core/impit-http-client.test.ts b/test/core/impit-http-client.test.tsindex 02c32b0f1..5bf3e5eb2 100644--- a/test/core/impit-http-client.test.ts+++ b/test/core/impit-http-client.test.ts@@ -50,6 +50,49 @@ describe('ImpitHttpClient', () => {expect(Impit).toHaveBeenCalledWith(expect.objectContaining({ ignoreTlsErrors: true }));});+ test('lets the abort signal decide when a request times out, not the 30 s impit default', async () => {+ const httpClient = new ImpitHttpClient();+ const { signal } = new AbortController();++ await httpClient.sendRequest(new Request('http://example.com'), { signal });++ const { fetch } = vi.mocked(Impit).mock.instances[0];+ const [, init] = vi.mocked(fetch).mock.calls[0];+ expect(init).toMatchObject({ signal });+ expect(init?.timeout).toBeNull();+ });++ test('cancels the download when the abort signal fires after the response headers', async () => {+ const cancel = vi.fn();+ const body = new ReadableStream({ pull: async () => new Promise(() => {}), cancel });+ vi.mocked(Impit).mockImplementationOnce(+ class {+ fetch = vi.fn(async () => new Response(body));+ } as any,+ );+ const httpClient = new ImpitHttpClient();+ const controller = new AbortController();++ const response = await httpClient.sendRequest(new Request('http://example.com'), {+ signal: controller.signal,+ });+ const reading = response.text();+ controller.abort();++ await expect(reading).rejects.toThrow();+ await vi.waitFor(() => expect(cancel).toHaveBeenCalled());+ });++ test('keeps the impit default timeout when there is no abort signal', async () => {+ const httpClient = new ImpitHttpClient();++ await httpClient.sendRequest(new Request('http://example.com'));++ const { fetch } = vi.mocked(Impit).mock.instances[0];+ const [, init] = vi.mocked(fetch).mock.calls[0];+ expect(init?.timeout).toBeUndefined();+ });+test('constructor-level browser takes precedence over the session fingerprint', async () => {const httpClient = new ImpitHttpClient({ browser: 'firefox144' });const session = { fingerprint: { browser: 'chrome' } } as ISession;