@crawlee/http 4.0.0-beta.1 → 4.0.0-beta.100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,28 +1,38 @@
1
- import { extname } from 'node:path';
1
+ import { Readable } from 'node:stream';
2
2
  import util from 'node:util';
3
- import { BASIC_CRAWLER_TIMEOUT_BUFFER_SECS, BasicCrawler, Configuration, CrawlerExtension, mergeCookies, processHttpRequestOptions, RequestState, Router, SessionError, validators, } from '@crawlee/basic';
3
+ import { BasicCrawler, ContextPipeline, NavigationSkippedError, remainingNavigationWindowMillis, RequestState, Router, SessionError, } from '@crawlee/basic';
4
+ import { getCookiesFromResponse } from '@crawlee/core';
5
+ import { ResponseWithUrl } from '@crawlee/http-client';
4
6
  import { RETRY_CSS_SELECTORS } from '@crawlee/utils';
5
- import * as cheerio from 'cheerio';
6
7
  import contentTypeParser from 'content-type';
7
8
  import iconv from 'iconv-lite';
8
- import mime from 'mime-types';
9
- import ow, { ObjectPredicate } from 'ow';
10
- import { addTimeoutToPromise, tryCancel } from '@apify/timeout';
11
- import { concatStreamToBuffer, readStreamToString } from '@apify/utilities';
12
- let TimeoutError;
9
+ import ow from 'ow';
10
+ import { addTimeoutToPromise, storage, TimeoutError, tryCancel } from '@apify/timeout';
11
+ import { extractCharsetFromHtmlBytes, parseContentTypeFromResponse, processHttpRequestOptions } from './utils.js';
13
12
  /**
14
13
  * Default mime types, which HttpScraper supports.
15
14
  */
16
15
  const HTML_AND_XML_MIME_TYPES = ['text/html', 'text/xml', 'application/xhtml+xml', 'application/xml'];
17
16
  const APPLICATION_JSON_MIME_TYPE = 'application/json';
18
- const HTTP_OPTIMIZED_AUTOSCALED_POOL_OPTIONS = {
17
+ /**
18
+ * A higher starting concurrency and a relaxed event loop signal, since HTTP-only crawling barely touches the event
19
+ * loop. {@link HttpCrawler} folds these into the {@link ConcurrencySystem} it builds by default.
20
+ *
21
+ * A {@link BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} you supply yourself replaces that default
22
+ * wholesale, tuning included, so spread these options in if you want to keep it:
23
+ *
24
+ * ```typescript
25
+ * new ConcurrencySystem({ ...HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS, maxConcurrency: 50 });
26
+ * ```
27
+ */
28
+ export const HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS = {
19
29
  desiredConcurrency: 10,
20
- snapshotterOptions: {
21
- eventLoopSnapshotIntervalSecs: 2,
22
- maxBlockedMillis: 100,
23
- },
24
- systemStatusOptions: {
25
- maxEventLoopOverloadedRatio: 0.7,
30
+ loadSignals: {
31
+ eventLoop: {
32
+ snapshotIntervalSecs: 2,
33
+ maxBlockedMillis: 100,
34
+ overloadedRatio: 0.7,
35
+ },
26
36
  },
27
37
  };
28
38
  /**
@@ -36,38 +46,40 @@ const HTTP_OPTIMIZED_AUTOSCALED_POOL_OPTIONS = {
36
46
  *
37
47
  * This crawler downloads each URL using a plain HTTP request and doesn't do any HTML parsing.
38
48
  *
39
- * The source URLs are represented using {@link Request} objects that are fed from
40
- * {@link RequestList} or {@link RequestQueue} instances provided by the {@link HttpCrawlerOptions.requestList}
41
- * or {@link HttpCrawlerOptions.requestQueue} constructor options, respectively.
49
+ * The source URLs are represented using {@link Request} objects that are fed from the
50
+ * {@link IRequestManager|request manager} provided via the {@link HttpCrawlerOptions.requestManager|`requestManager`}
51
+ * constructor option (a {@link RequestQueue} is itself a request manager). To read from a read-only source such
52
+ * as a {@link RequestList} while still being able to enqueue new requests, combine it with a queue into a
53
+ * {@link RequestManagerTandem} via {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the
54
+ * result as `requestManager`.
42
55
  *
43
- * If both {@link HttpCrawlerOptions.requestList} and {@link HttpCrawlerOptions.requestQueue} are used,
44
- * the instance first processes URLs from the {@link RequestList} and automatically enqueues all of them
45
- * to {@link RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
56
+ * > The {@link HttpCrawlerOptions.requestList|`requestList`} and {@link HttpCrawlerOptions.requestQueue|`requestQueue`}
57
+ * > options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
46
58
  *
47
59
  * The crawler finishes when there are no more {@link Request} objects to crawl.
48
60
  *
49
- * We can use the `preNavigationHooks` to adjust `gotOptions`:
61
+ * We can use the `preNavigationHooks` to adjust the crawling context before the request is made:
50
62
  *
51
63
  * ```javascript
52
64
  * preNavigationHooks: [
53
- * (crawlingContext, gotOptions) => {
65
+ * (crawlingContext) => {
54
66
  * // ...
55
67
  * },
56
68
  * ]
57
69
  * ```
58
70
  *
59
- * By default, this crawler only processes web pages with the `text/html`
60
- * and `application/xhtml+xml` MIME content types (as reported by the `Content-Type` HTTP header),
71
+ * By default, this crawler only processes web pages with the `text/html`, `application/xhtml+xml`, `text/xml`, `application/xml`,
72
+ * and `application/json` MIME content types (as reported by the `Content-Type` HTTP header),
61
73
  * and skips pages with other content types. If you want the crawler to process other content types,
62
74
  * use the {@link HttpCrawlerOptions.additionalMimeTypes} constructor option.
63
75
  * Beware that the parsing behavior differs for HTML, XML, JSON and other types of content.
64
76
  * For details, see {@link HttpCrawlerOptions.requestHandler}.
65
77
  *
66
- * New requests are only dispatched when there is enough free CPU and memory available,
67
- * using the functionality provided by the {@link AutoscaledPool} class.
68
- * All {@link AutoscaledPool} configuration options can be passed to the `autoscaledPoolOptions`
69
- * parameter of the constructor. For user convenience, the `minConcurrency` and `maxConcurrency`
70
- * {@link AutoscaledPool} options are available directly in the constructor.
78
+ * New requests are only dispatched when there is enough free CPU and memory available, as judged by the crawler's
79
+ * {@link ConcurrencySystem}.
80
+ * Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the
81
+ * constructor, or, for finer control, by injecting a pre-configured
82
+ * {@link ConcurrencySystem|`concurrencySystem`}.
71
83
  *
72
84
  * **Example usage:**
73
85
  *
@@ -93,22 +105,17 @@ const HTTP_OPTIMIZED_AUTOSCALED_POOL_OPTIONS = {
93
105
  * @category Crawlers
94
106
  */
95
107
  export class HttpCrawler extends BasicCrawler {
96
- config;
97
- /**
98
- * A reference to the underlying {@link ProxyConfiguration} class that manages the crawler's proxies.
99
- * Only available if used by the crawler.
100
- */
101
- proxyConfiguration;
102
- userRequestHandlerTimeoutMillis;
108
+ // Internal storage uses the base (non-extended) context types. The public option types are
109
+ // extension-aware for consumer DX, but internally the pipeline composes hooks against the
110
+ // concrete crawling context, which does not statically carry `ContextExtension`. The members
111
+ // added by `extendContext` are present at runtime regardless.
103
112
  preNavigationHooks;
104
113
  postNavigationHooks;
105
- persistCookiesPerSession;
114
+ saveResponseCookies;
106
115
  navigationTimeoutMillis;
107
116
  ignoreSslErrors;
108
117
  suggestResponseEncoding;
109
118
  forceResponseEncoding;
110
- additionalHttpErrorStatusCodes;
111
- ignoreHttpErrorStatusCodes;
112
119
  supportedMimeTypes;
113
120
  static optionsShape = {
114
121
  ...BasicCrawler.optionsShape,
@@ -117,158 +124,207 @@ export class HttpCrawler extends BasicCrawler {
117
124
  additionalMimeTypes: ow.optional.array.ofType(ow.string),
118
125
  suggestResponseEncoding: ow.optional.string,
119
126
  forceResponseEncoding: ow.optional.string,
120
- proxyConfiguration: ow.optional.object.validate(validators.proxyConfiguration),
121
- persistCookiesPerSession: ow.optional.boolean,
122
- additionalHttpErrorStatusCodes: ow.optional.array.ofType(ow.number),
123
- ignoreHttpErrorStatusCodes: ow.optional.array.ofType(ow.number),
127
+ saveResponseCookies: ow.optional.boolean,
124
128
  preNavigationHooks: ow.optional.array,
125
129
  postNavigationHooks: ow.optional.array,
126
130
  };
127
131
  /**
128
132
  * All `HttpCrawlerOptions` parameters are passed via an options object.
129
133
  */
130
- constructor(options = {}, config = Configuration.getGlobalConfig()) {
134
+ constructor(options = {}) {
131
135
  ow(options, 'HttpCrawlerOptions', ow.object.exactShape(HttpCrawler.optionsShape));
132
- const { requestHandler, requestHandlerTimeoutSecs = 60, navigationTimeoutSecs = 30, ignoreSslErrors = true, additionalMimeTypes = [], suggestResponseEncoding, forceResponseEncoding, proxyConfiguration, persistCookiesPerSession, preNavigationHooks = [], postNavigationHooks = [], additionalHttpErrorStatusCodes = [], ignoreHttpErrorStatusCodes = [],
136
+ const { navigationTimeoutSecs = 30, ignoreSslErrors = true, additionalMimeTypes = [], suggestResponseEncoding, forceResponseEncoding, saveResponseCookies = true, preNavigationHooks = [], postNavigationHooks = [],
133
137
  // BasicCrawler
134
- autoscaledPoolOptions = HTTP_OPTIMIZED_AUTOSCALED_POOL_OPTIONS, ...basicCrawlerOptions } = options;
138
+ contextPipelineBuilder, ...basicCrawlerOptions } = options;
135
139
  super({
136
140
  ...basicCrawlerOptions,
137
- requestHandler,
138
- autoscaledPoolOptions,
139
- // We need to add some time for internal functions to finish,
140
- // but not too much so that we would stall the crawler.
141
- requestHandlerTimeoutSecs: navigationTimeoutSecs + requestHandlerTimeoutSecs + BASIC_CRAWLER_TIMEOUT_BUFFER_SECS,
142
- }, config);
143
- this.config = config;
144
- // FIXME any
145
- this.requestHandler = requestHandler ?? this.router;
146
- // Cookies should be persisted per session only if session pool is used
147
- if (!this.useSessionPool && persistCookiesPerSession) {
148
- throw new Error('You cannot use "persistCookiesPerSession" without "useSessionPool" set to true.');
149
- }
141
+ contextPipelineBuilder: contextPipelineBuilder ??
142
+ (() => this.buildContextPipeline()),
143
+ });
150
144
  this.supportedMimeTypes = new Set([...HTML_AND_XML_MIME_TYPES, APPLICATION_JSON_MIME_TYPE]);
151
145
  if (additionalMimeTypes.length)
152
- this._extendSupportedMimeTypes(additionalMimeTypes);
146
+ this.extendSupportedMimeTypes(additionalMimeTypes);
153
147
  if (suggestResponseEncoding && forceResponseEncoding) {
154
148
  this.log.warning('Both forceResponseEncoding and suggestResponseEncoding options are set. Using forceResponseEncoding.');
155
149
  }
156
- this.userRequestHandlerTimeoutMillis = requestHandlerTimeoutSecs * 1000;
157
150
  this.navigationTimeoutMillis = navigationTimeoutSecs * 1000;
158
151
  this.ignoreSslErrors = ignoreSslErrors;
159
152
  this.suggestResponseEncoding = suggestResponseEncoding;
160
153
  this.forceResponseEncoding = forceResponseEncoding;
161
- this.additionalHttpErrorStatusCodes = new Set([...additionalHttpErrorStatusCodes]);
162
- this.ignoreHttpErrorStatusCodes = new Set([...ignoreHttpErrorStatusCodes]);
163
- this.proxyConfiguration = proxyConfiguration;
154
+ // Cast away the extension-aware option types to the base internal storage types (see the field
155
+ // declarations above). This is sound - the hooks only ever receive the base context plus the
156
+ // members `extendContext` added at runtime.
164
157
  this.preNavigationHooks = preNavigationHooks;
165
158
  this.postNavigationHooks = [
166
159
  ({ request, response }) => this._abortDownloadOfBody(request, response),
167
160
  ...postNavigationHooks,
168
161
  ];
169
- if (this.useSessionPool) {
170
- this.persistCookiesPerSession = persistCookiesPerSession ?? true;
171
- }
172
- else {
173
- this.persistCookiesPerSession = false;
174
- }
162
+ this.saveResponseCookies = saveResponseCookies;
163
+ }
164
+ getNavigationTimeoutMillis() {
165
+ return this.navigationTimeoutMillis;
175
166
  }
176
167
  /**
177
- * **EXPERIMENTAL**
178
- * Function for attaching CrawlerExtensions such as the Unblockers.
179
- * @param extension Crawler extension that overrides the crawler configuration.
168
+ * Folds {@link HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS} into the default system, keeping the user's
169
+ * concurrency shortcuts on top. Not called for a supplied
170
+ * {@link BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} spread the constant into it yourself to
171
+ * keep the tuning.
180
172
  */
181
- use(extension) {
182
- ow(extension, ow.object.instanceOf(CrawlerExtension));
183
- const className = this.constructor.name;
184
- const extensionOptions = extension.getCrawlerOptions();
185
- for (const [key, value] of Object.entries(extensionOptions)) {
186
- const isConfigurable = Object.hasOwn(this, key);
187
- const originalType = typeof this[key];
188
- const extensionType = typeof value; // What if we want to null something? It is really needed?
189
- const isSameType = originalType === extensionType || value == null; // fast track for deleting keys
190
- const exists = this[key] != null;
191
- if (!isConfigurable) {
192
- // Test if the property can be configured on the crawler
193
- throw new Error(`${extension.name} tries to set property "${key}" that is not configurable on ${className} instance.`);
194
- }
195
- if (!isSameType && exists) {
196
- // Assuming that extensions will only add up configuration
197
- throw new Error(`${extension.name} tries to set property of different type "${extensionType}". "${className}.${key}: ${originalType}".`);
173
+ createDefaultConcurrencySystem(options) {
174
+ return super.createDefaultConcurrencySystem({
175
+ ...HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS,
176
+ ...options,
177
+ });
178
+ }
179
+ buildContextPipeline() {
180
+ // When navigation is skipped, `prepareHttpRequest` has already installed throwing getters for
181
+ // the response-derived members, so the guarded action is bypassed and the context left untouched.
182
+ const skipGuard = (action) => ({
183
+ action: async (ctx) => (ctx.request.skipNavigation ? {} : ((await action(ctx)) ?? {})),
184
+ });
185
+ // A single navigation window covers the pre-navigation hooks, the navigation, and the post-navigation
186
+ // hooks: the whole phase shares one `navigationTimeoutSecs` budget, so a slow hook eats into the same
187
+ // window the navigation uses instead of each step being timed on its own.
188
+ const navigationTimedOut = `Navigation timed out after ${this.navigationTimeoutMillis / 1000} seconds.`;
189
+ const windowGuard = (step) => skipGuard(async (ctx) => {
190
+ const remaining = remainingNavigationWindowMillis(ctx, this.navigationTimeoutMillis);
191
+ if (remaining <= 0) {
192
+ throw new TimeoutError(navigationTimedOut);
198
193
  }
199
- this.log.warning(`${extension.name} is overriding "${className}.${key}: ${originalType}" with ${value}.`);
200
- this[key] = value;
194
+ return addTimeoutToPromise(async () => step(ctx), remaining, navigationTimedOut);
195
+ });
196
+ let pipeline = ContextPipeline.create().compose({
197
+ action: this.prepareHttpRequest.bind(this),
198
+ });
199
+ for (const hook of this.preNavigationHooks) {
200
+ pipeline = pipeline.compose(windowGuard(hook));
201
201
  }
202
- }
203
- /**
204
- * Wrapper around requestHandler that opens and closes pages etc.
205
- */
206
- async _runRequestHandler(crawlingContext) {
207
- const { request, session } = crawlingContext;
208
- if (this.proxyConfiguration) {
209
- const sessionId = session ? session.id : undefined;
210
- crawlingContext.proxyInfo = await this.proxyConfiguration.newProxyInfo(sessionId, { request });
202
+ let pipelineWithNavigation = pipeline.compose(skipGuard(this.makeHttpRequest.bind(this)));
203
+ for (const hook of this.postNavigationHooks) {
204
+ pipelineWithNavigation = pipelineWithNavigation.compose(windowGuard(hook));
211
205
  }
212
- if (!request.skipNavigation) {
213
- await this._handleNavigation(crawlingContext);
214
- tryCancel();
215
- const parsed = await this._parseResponse(request, crawlingContext.response, crawlingContext);
216
- const response = parsed.response;
217
- const contentType = parsed.contentType;
218
- tryCancel();
219
- // `??=` because descendant classes may already set optimized version
220
- crawlingContext.waitForSelector ??= async (selector, _timeoutMs) => {
221
- const $ = cheerio.load(parsed.body.toString());
222
- if ($(selector).get().length === 0) {
223
- throw new Error(`Selector '${selector}' not found.`);
224
- }
206
+ return pipelineWithNavigation
207
+ .compose({ action: this.processHttpResponse.bind(this) })
208
+ .compose({ action: this.handleBlockedRequestByContent.bind(this) });
209
+ }
210
+ async prepareHttpRequest(crawlingContext) {
211
+ const { request } = crawlingContext;
212
+ if (request.skipNavigation) {
213
+ return {
214
+ request: new Proxy(request, {
215
+ get(target, propertyName, receiver) {
216
+ if (propertyName === 'loadedUrl') {
217
+ throw new NavigationSkippedError('The `request.loadedUrl` property is not available - `skipNavigation` was used');
218
+ }
219
+ return Reflect.get(target, propertyName, receiver);
220
+ },
221
+ }),
222
+ get response() {
223
+ throw new NavigationSkippedError('The `response` property is not available - `skipNavigation` was used');
224
+ },
225
225
  };
226
- crawlingContext.parseWithCheerio ??= async (selector, timeoutMs) => {
227
- const $ = cheerio.load(parsed.body.toString());
228
- if (selector) {
229
- await crawlingContext.waitForSelector(selector, timeoutMs);
230
- }
231
- return $;
226
+ }
227
+ request.state = RequestState.BEFORE_NAV;
228
+ return {};
229
+ }
230
+ async makeHttpRequest(crawlingContext) {
231
+ tryCancel();
232
+ const { request, session } = crawlingContext;
233
+ const proxyUrl = crawlingContext.proxyInfo?.url;
234
+ // Bound the request by whatever is left of the shared navigation window (the pre-navigation hooks may
235
+ // have already spent part of it), so it produces a clean navigation-timeout error rather than the raw
236
+ // client abort.
237
+ const httpResponse = await addTimeoutToPromise(async () => this.requestFunction({ request, session, proxyUrl }), Math.max(1, remainingNavigationWindowMillis(crawlingContext, this.navigationTimeoutMillis)), `Navigation timed out after ${this.navigationTimeoutMillis / 1000} seconds.`);
238
+ tryCancel();
239
+ request.loadedUrl = httpResponse?.url;
240
+ request.state = RequestState.AFTER_NAV;
241
+ return { request: request, response: httpResponse };
242
+ }
243
+ async processHttpResponse(crawlingContext) {
244
+ if (crawlingContext.request.skipNavigation) {
245
+ return {
246
+ get contentType() {
247
+ throw new NavigationSkippedError('The `contentType` property is not available - `skipNavigation` was used');
248
+ },
249
+ get body() {
250
+ throw new NavigationSkippedError('The `body` property is not available - `skipNavigation` was used');
251
+ },
252
+ get json() {
253
+ throw new NavigationSkippedError('The `json` property is not available - `skipNavigation` was used');
254
+ },
255
+ get waitForSelector() {
256
+ throw new NavigationSkippedError('The `waitForSelector` method is not available - `skipNavigation` was used');
257
+ },
258
+ get parseWithCheerio() {
259
+ throw new NavigationSkippedError('The `parseWithCheerio` method is not available - `skipNavigation` was used');
260
+ },
232
261
  };
233
- if (this.useSessionPool) {
234
- this._throwOnBlockedRequest(crawlingContext.session, response.statusCode);
262
+ }
263
+ tryCancel();
264
+ // Reading the body is still part of the navigation, so it draws from the same shared window: on a server
265
+ // that streams the body slowly the request completes (headers arrive) but the body read would otherwise
266
+ // run unbounded. `extendTimeout` from a post-navigation hook has already pushed this deadline out if asked.
267
+ const remaining = remainingNavigationWindowMillis(crawlingContext, this.navigationTimeoutMillis);
268
+ if (remaining <= 0) {
269
+ throw new TimeoutError(`Navigation timed out after ${this.navigationTimeoutMillis / 1000} seconds.`);
270
+ }
271
+ const parsed = await addTimeoutToPromise(async () => this.parseResponse(crawlingContext.request, crawlingContext.response), remaining, `Navigation timed out after ${this.navigationTimeoutMillis / 1000} seconds.`);
272
+ tryCancel();
273
+ const response = parsed.response;
274
+ const contentType = parsed.contentType;
275
+ const waitForSelector = async (selector, _timeoutMs) => {
276
+ const cheerio = await import('cheerio');
277
+ const $ = cheerio.load(parsed.body.toString());
278
+ if ($(selector).get().length === 0) {
279
+ throw new Error(`Selector '${selector}' not found.`);
235
280
  }
236
- if (this.persistCookiesPerSession) {
237
- crawlingContext.session.setCookiesFromResponse(response);
281
+ };
282
+ const parseWithCheerio = async (selector, timeoutMs) => {
283
+ const cheerio = await import('cheerio');
284
+ const $ = cheerio.load(parsed.body.toString());
285
+ if (selector) {
286
+ await crawlingContext.waitForSelector(selector, timeoutMs);
238
287
  }
239
- request.loadedUrl = response.url;
240
- if (!this.requestMatchesEnqueueStrategy(request)) {
241
- this.log.debug(
242
- // eslint-disable-next-line dot-notation
243
- `Skipping request ${request.id} (starting url: ${request.url} -> loaded url: ${request.loadedUrl}) because it does not match the enqueue strategy (${request['enqueueStrategy']}).`);
244
- request.noRetry = true;
245
- request.state = RequestState.SKIPPED;
246
- return;
288
+ return $;
289
+ };
290
+ this._throwOnBlockedRequest(response.status);
291
+ if (this.saveResponseCookies) {
292
+ try {
293
+ for (const cookie of getCookiesFromResponse(response)) {
294
+ if (!cookie)
295
+ continue;
296
+ try {
297
+ crawlingContext.session.cookieJar.setCookieSync(cookie, response.url, { ignoreError: false });
298
+ }
299
+ catch (e) {
300
+ this.log.debug(`Could not set cookie: ${e.message}`);
301
+ }
302
+ }
303
+ }
304
+ catch (e) {
305
+ this.log.exception(e, 'Could not get cookies from response');
247
306
  }
248
- Object.assign(crawlingContext, parsed);
249
- Object.defineProperty(crawlingContext, 'json', {
250
- get() {
251
- if (contentType.type !== APPLICATION_JSON_MIME_TYPE)
252
- return null;
253
- const jsonString = parsed.body.toString(contentType.encoding);
254
- return JSON.parse(jsonString);
255
- },
256
- });
257
307
  }
308
+ return {
309
+ get json() {
310
+ if (contentType.type !== APPLICATION_JSON_MIME_TYPE)
311
+ return null;
312
+ const jsonString = parsed.body.toString(contentType.encoding);
313
+ return JSON.parse(jsonString);
314
+ },
315
+ waitForSelector,
316
+ parseWithCheerio,
317
+ contentType,
318
+ body: parsed.body,
319
+ };
320
+ }
321
+ async handleBlockedRequestByContent(crawlingContext) {
258
322
  if (this.retryOnBlocked) {
259
323
  const error = await this.isRequestBlocked(crawlingContext);
260
324
  if (error)
261
325
  throw new SessionError(error);
262
326
  }
263
- request.state = RequestState.REQUEST_HANDLER;
264
- try {
265
- await addTimeoutToPromise(async () => Promise.resolve(this.requestHandler(crawlingContext)), this.userRequestHandlerTimeoutMillis, `requestHandler timed out after ${this.userRequestHandlerTimeoutMillis / 1000} seconds.`);
266
- request.state = RequestState.DONE;
267
- }
268
- catch (e) {
269
- request.state = RequestState.ERROR;
270
- throw e;
271
- }
327
+ return {};
272
328
  }
273
329
  async isRequestBlocked(crawlingContext) {
274
330
  if (HTML_AND_XML_MIME_TYPES.includes(crawlingContext.contentType.type)) {
@@ -278,84 +334,25 @@ export class HttpCrawler extends BasicCrawler {
278
334
  return `Found selectors: ${foundSelectors.join(', ')}`;
279
335
  }
280
336
  }
281
- return false;
282
- }
283
- async _handleNavigation(crawlingContext) {
284
- const gotOptions = {};
285
- const { request, session } = crawlingContext;
286
- const preNavigationHooksCookies = this._getCookieHeaderFromRequest(request);
287
- request.state = RequestState.BEFORE_NAV;
288
- // Execute pre navigation hooks before applying session pool cookies,
289
- // as they may also set cookies in the session
290
- await this._executeHooks(this.preNavigationHooks, crawlingContext, gotOptions);
291
- tryCancel();
292
- const postNavigationHooksCookies = this._getCookieHeaderFromRequest(request);
293
- this._applyCookies(crawlingContext, gotOptions, preNavigationHooksCookies, postNavigationHooksCookies);
294
- const proxyUrl = crawlingContext.proxyInfo?.url;
295
- crawlingContext.response = await addTimeoutToPromise(async () => this._requestFunction({ request, session, proxyUrl, gotOptions }), this.navigationTimeoutMillis, `request timed out after ${this.navigationTimeoutMillis / 1000} seconds.`);
296
- tryCancel();
297
- request.state = RequestState.AFTER_NAV;
298
- await this._executeHooks(this.postNavigationHooks, crawlingContext, gotOptions);
299
- tryCancel();
300
- }
301
- /**
302
- * Sets the cookie header to `gotOptions` based on the provided request and session headers, as well as any changes that occurred due to hooks.
303
- */
304
- _applyCookies({ session, request }, gotOptions, preHookCookies, postHookCookies) {
305
- const sessionCookie = session?.getCookieString(request.url) ?? '';
306
- let alteredGotOptionsCookies = gotOptions.headers?.Cookie || gotOptions.headers?.cookie || '';
307
- if (gotOptions.headers?.Cookie && gotOptions.headers?.cookie) {
308
- const { Cookie: upperCaseHeader, cookie: lowerCaseHeader } = gotOptions.headers;
309
- this.log.warning(`Encountered mixed casing for the cookie headers in the got options for request ${request.url} (${request.id}). Their values will be merged`);
310
- const sourceCookies = [];
311
- if (Array.isArray(lowerCaseHeader)) {
312
- sourceCookies.push(...lowerCaseHeader);
313
- }
314
- else {
315
- sourceCookies.push(lowerCaseHeader);
316
- }
317
- if (Array.isArray(upperCaseHeader)) {
318
- sourceCookies.push(...upperCaseHeader);
319
- }
320
- else {
321
- sourceCookies.push(upperCaseHeader);
322
- }
323
- alteredGotOptionsCookies = mergeCookies(request.url, sourceCookies);
324
- }
325
- const sourceCookies = [sessionCookie, preHookCookies];
326
- if (Array.isArray(alteredGotOptionsCookies)) {
327
- sourceCookies.push(...alteredGotOptionsCookies);
328
- }
329
- else {
330
- sourceCookies.push(alteredGotOptionsCookies);
331
- }
332
- sourceCookies.push(postHookCookies);
333
- const mergedCookie = mergeCookies(request.url, sourceCookies);
334
- gotOptions.headers ??= {};
335
- Reflect.deleteProperty(gotOptions.headers, 'Cookie');
336
- Reflect.deleteProperty(gotOptions.headers, 'cookie');
337
- if (mergedCookie !== '') {
338
- gotOptions.headers.Cookie = mergedCookie;
337
+ if (this.blockedStatusCodes.has(crawlingContext.response.status)) {
338
+ return `Blocked by status code ${crawlingContext.response.status}`;
339
339
  }
340
+ return false;
340
341
  }
341
342
  /**
342
343
  * Function to make the HTTP request. It performs optimizations
343
344
  * on the request such as only downloading the request body if the
344
345
  * received content type matches text/html, application/xml, application/xhtml+xml.
345
346
  */
346
- async _requestFunction({ request, session, proxyUrl, gotOptions, }) {
347
- if (!TimeoutError) {
348
- // @ts-ignore
349
- ({ TimeoutError } = await import('got-scraping'));
350
- }
351
- const opts = this._getRequestOptions(request, session, proxyUrl, gotOptions);
347
+ async requestFunction({ request, session, proxyUrl }) {
348
+ const opts = this.getRequestOptions(request, session, proxyUrl);
352
349
  try {
353
350
  return await this._requestAsBrowser(opts, session);
354
351
  }
355
352
  catch (e) {
356
- if (e instanceof TimeoutError) {
357
- this._handleRequestTimeout(session);
358
- return undefined;
353
+ if (e instanceof Error && e.constructor.name === 'TimeoutError') {
354
+ this.handleRequestTimeout(session);
355
+ return new Response(); // this will never happen, as handleRequestTimeout always throws
359
356
  }
360
357
  if (this.isProxyError(e)) {
361
358
  throw new SessionError(this._getMessageFromError(e));
@@ -368,18 +365,16 @@ export class HttpCrawler extends BasicCrawler {
368
365
  /**
369
366
  * Encodes and parses response according to the provided content type
370
367
  */
371
- async _parseResponse(request, responseStream, crawlingContext) {
372
- const { statusCode } = responseStream;
373
- const { type, charset } = parseContentTypeFromResponse(responseStream);
374
- const { response, encoding } = this._encodeResponse(request, responseStream, charset);
368
+ async parseResponse(request, response) {
369
+ const { status } = response;
370
+ const { type, charset } = parseContentTypeFromResponse(response);
371
+ const { response: reencodedResponse, encoding } = this.encodeResponse(request, response, charset);
375
372
  const contentType = { type, encoding };
376
- if (statusCode >= 400 && statusCode <= 599) {
377
- this.stats.registerStatusCode(statusCode);
373
+ if (status >= 400 && status <= 599) {
374
+ this.stats.registerStatusCode(status);
378
375
  }
379
- const excludeError = this.ignoreHttpErrorStatusCodes.has(statusCode);
380
- const includeError = this.additionalHttpErrorStatusCodes.has(statusCode);
381
- if ((statusCode >= 500 && !excludeError) || includeError) {
382
- const body = await readStreamToString(response, encoding);
376
+ if (this.isErrorStatusCode(status)) {
377
+ const body = await reencodedResponse.text(); // TODO - this always uses UTF-8 (see https://developer.mozilla.org/en-US/docs/Web/API/Request/text)
383
378
  // Errors are often sent as JSON, so attempt to parse them,
384
379
  // despite Accept header being set to text/html.
385
380
  if (type === APPLICATION_JSON_MIME_TYPE) {
@@ -387,59 +382,57 @@ export class HttpCrawler extends BasicCrawler {
387
382
  let { message } = errorResponse;
388
383
  if (!message)
389
384
  message = util.inspect(errorResponse, { depth: 1, maxArrayLength: 10 });
390
- throw new Error(`${statusCode} - ${message}`);
385
+ throw new Error(`${status} - ${message}`);
391
386
  }
392
- if (includeError) {
393
- throw new Error(`${statusCode} - Error status code was set by user.`);
387
+ if (this.additionalHttpErrorStatusCodes.has(status)) {
388
+ throw new Error(`${status} - Error status code was set by user.`);
394
389
  }
395
390
  // It's not a JSON, so it's probably some text. Get the first 100 chars of it.
396
- throw new Error(`${statusCode} - Internal Server Error: ${body.slice(0, 100)}`);
391
+ throw new Error(`${status} - Internal Server Error: ${body.slice(0, 100)}`);
397
392
  }
398
393
  else if (HTML_AND_XML_MIME_TYPES.includes(type)) {
399
- const isXml = type.includes('xml');
400
- const parsed = await this._parseHTML(response, isXml, crawlingContext);
401
- return { ...parsed, isXml, response, contentType };
394
+ if (!charset && !this.forceResponseEncoding) {
395
+ const rawBytes = Buffer.from(await response.arrayBuffer());
396
+ const metaCharset = extractCharsetFromHtmlBytes(rawBytes);
397
+ const charsetToUse = metaCharset ?? this.suggestResponseEncoding ?? 'utf-8';
398
+ const body = iconv.encodingExists(charsetToUse)
399
+ ? iconv.decode(rawBytes, charsetToUse)
400
+ : rawBytes.toString('utf8');
401
+ return { response, contentType: { type, encoding: 'utf-8' }, body };
402
+ }
403
+ return { response, contentType, body: await reencodedResponse.text() };
402
404
  }
403
405
  else {
404
- const body = await concatStreamToBuffer(response);
406
+ const body = Buffer.from(await reencodedResponse.bytes());
405
407
  return {
406
408
  body,
407
409
  response,
408
410
  contentType,
409
- enqueueLinks: async () => Promise.resolve({ processedRequests: [], unprocessedRequests: [] }),
410
411
  };
411
412
  }
412
413
  }
413
- async _parseHTML(response, _isXml, _crawlingContext) {
414
- return {
415
- body: await concatStreamToBuffer(response),
416
- };
417
- }
418
414
  /**
419
415
  * Combines the provided `requestOptions` with mandatory (non-overridable) values.
420
416
  */
421
- _getRequestOptions(request, session, proxyUrl, gotOptions) {
417
+ getRequestOptions(request, session, proxyUrl) {
422
418
  const requestOptions = {
423
419
  url: request.url,
424
420
  method: request.method,
425
421
  proxyUrl,
426
- timeout: { request: this.navigationTimeoutMillis },
422
+ timeout: this.navigationTimeoutMillis,
427
423
  sessionToken: session,
428
- ...gotOptions,
429
- headers: { ...request.headers, ...gotOptions?.headers },
424
+ headers: request.headers,
430
425
  https: {
431
- ...gotOptions?.https,
432
426
  rejectUnauthorized: !this.ignoreSslErrors,
433
427
  },
434
- isStream: true,
428
+ body: undefined,
435
429
  };
436
- // Delete any possible lowercased header for cookie as they are merged in _applyCookies under the uppercase Cookie header
437
- Reflect.deleteProperty(requestOptions.headers, 'cookie');
438
- // TODO this is incorrect, the check for man in the middle needs to be done
439
- // on individual proxy level, not on the `proxyConfiguration` level,
440
- // because users can use normal + MITM proxies in a single configuration.
430
+ if (requestOptions.headers?.cookie || requestOptions.headers?.Cookie) {
431
+ requestOptions.headers.Cookie = this._getCookieHeaderFromRequest(request);
432
+ delete requestOptions.headers.cookie;
433
+ }
441
434
  // Disable SSL verification for MITM proxies
442
- if (this.proxyConfiguration && this.proxyConfiguration.isManInTheMiddle) {
435
+ if (session.proxyInfo?.ignoreTlsErrors) {
443
436
  requestOptions.https = {
444
437
  ...requestOptions.https,
445
438
  rejectUnauthorized: false,
@@ -449,7 +442,7 @@ export class HttpCrawler extends BasicCrawler {
449
442
  requestOptions.body = request.payload ?? '';
450
443
  return requestOptions;
451
444
  }
452
- _encodeResponse(request, response, encoding) {
445
+ encodeResponse(request, response, encoding) {
453
446
  if (this.forceResponseEncoding) {
454
447
  encoding = this.forceResponseEncoding;
455
448
  }
@@ -467,14 +460,16 @@ export class HttpCrawler extends BasicCrawler {
467
460
  // Try to re-encode a variety of unsupported encodings to utf-8
468
461
  if (iconv.encodingExists(encoding)) {
469
462
  const encodeStream = iconv.encodeStream(utf8);
470
- const decodeStream = iconv.decodeStream(encoding).on('error', (err) => encodeStream.emit('error', err));
471
- response.on('error', (err) => decodeStream.emit('error', err));
472
- const encodedResponse = response.pipe(decodeStream).pipe(encodeStream);
473
- encodedResponse.statusCode = response.statusCode;
474
- encodedResponse.headers = response.headers;
475
- encodedResponse.url = response.url;
463
+ const decodeStream = iconv
464
+ .decodeStream(encoding)
465
+ .on('error', (err) => encodeStream.emit('error', err));
466
+ const reencodedBody = response.body
467
+ ? Readable.toWeb(Readable.from(Readable.fromWeb(response.body)
468
+ .pipe(decodeStream)
469
+ .pipe(encodeStream)))
470
+ : null;
476
471
  return {
477
- response: encodedResponse,
472
+ response: new ResponseWithUrl(reencodedBody, response),
478
473
  encoding: utf8,
479
474
  };
480
475
  }
@@ -483,7 +478,7 @@ export class HttpCrawler extends BasicCrawler {
483
478
  /**
484
479
  * Checks and extends supported mime types
485
480
  */
486
- _extendSupportedMimeTypes(additionalMimeTypes) {
481
+ extendSupportedMimeTypes(additionalMimeTypes) {
487
482
  for (const mimeType of additionalMimeTypes) {
488
483
  if (mimeType === '*/*') {
489
484
  this.supportedMimeTypes.add(mimeType);
@@ -501,17 +496,14 @@ export class HttpCrawler extends BasicCrawler {
501
496
  /**
502
497
  * Handles timeout request
503
498
  */
504
- _handleRequestTimeout(session) {
505
- session?.markBad();
506
- throw new Error(`request timed out after ${this.requestHandlerTimeoutMillis / 1000} seconds.`);
499
+ handleRequestTimeout(session) {
500
+ session.markBad();
501
+ throw new Error(`Request timed out after ${this.navigationTimeoutMillis / 1000} seconds.`);
507
502
  }
508
503
  _abortDownloadOfBody(request, response) {
509
- const { statusCode } = response;
504
+ const { status } = response;
510
505
  const { type } = parseContentTypeFromResponse(response);
511
- // eslint-disable-next-line dot-notation -- accessing private property
512
- const blockedStatusCodes = this.sessionPool ? this.sessionPool['blockedStatusCodes'] : [];
513
- // if we retry the request, can the Content-Type change?
514
- const isTransientContentType = statusCode >= 500 || blockedStatusCodes.includes(statusCode);
506
+ const isTransientContentType = status >= 500 || this.blockedStatusCodes.has(status);
515
507
  if (!this.supportedMimeTypes.has(type) && !this.supportedMimeTypes.has('*/*') && !isTransientContentType) {
516
508
  request.noRetry = true;
517
509
  throw new Error(`Resource ${request.url} served Content-Type ${type}, ` +
@@ -522,115 +514,35 @@ export class HttpCrawler extends BasicCrawler {
522
514
  * @internal wraps public utility for mocking purposes
523
515
  */
524
516
  _requestAsBrowser = async (options, session) => {
525
- const response = await this.httpClient.stream(processHttpRequestOptions({
517
+ const opts = processHttpRequestOptions({
526
518
  ...options,
527
- cookieJar: options.cookieJar, // HACK - the type of ToughCookieJar in got is wrong
528
519
  responseType: 'text',
529
- }), (redirectResponse, updatedRequest) => {
530
- if (this.persistCookiesPerSession) {
531
- session.setCookiesFromResponse(redirectResponse);
532
- const cookieString = session.getCookieString(updatedRequest.url.toString());
533
- if (cookieString !== '') {
534
- updatedRequest.headers.Cookie = cookieString;
535
- }
536
- }
537
520
  });
538
- return addResponsePropertiesToStream(response.stream, response);
539
- };
540
- }
541
- /**
542
- * The stream object returned from got does not have the below properties.
543
- * At the same time, you can't read data directly from the response stream,
544
- * because they won't get emitted unless you also read from the primary
545
- * got stream. To be able to work with only one stream, we move the expected props
546
- * from the response stream to the got stream.
547
- * @internal
548
- */
549
- function addResponsePropertiesToStream(stream, response) {
550
- const properties = [
551
- 'statusCode',
552
- 'statusMessage',
553
- 'headers',
554
- 'complete',
555
- 'httpVersion',
556
- 'rawHeaders',
557
- 'rawTrailers',
558
- 'trailers',
559
- 'url',
560
- 'request',
561
- ];
562
- stream.on('end', () => {
563
- // @ts-expect-error
564
- if (stream.rawTrailers)
565
- stream.rawTrailers = response.rawTrailers; // TODO BC with got - remove in 4.0
566
- // @ts-expect-error
567
- if (stream.trailers)
568
- stream.trailers = response.trailers;
569
- // @ts-expect-error
570
- stream.complete = response.complete;
571
- });
572
- for (const prop of properties) {
573
- if (!(prop in stream)) {
574
- stream[prop] = response[prop];
575
- }
576
- }
577
- return stream;
578
- }
579
- /**
580
- * Gets parsed content type from response object
581
- * @param response HTTP response object
582
- */
583
- function parseContentTypeFromResponse(response) {
584
- ow(response, ow.object.partialShape({
585
- url: ow.string.url,
586
- headers: new ObjectPredicate(),
587
- }));
588
- const { url, headers } = response;
589
- let parsedContentType;
590
- if (headers['content-type']) {
591
- try {
592
- parsedContentType = contentTypeParser.parse(headers['content-type']);
593
- }
594
- catch {
595
- // Can not parse content type from Content-Type header. Try to parse it from file extension.
596
- }
597
- }
598
- // Parse content type from file extension as fallback
599
- if (!parsedContentType) {
600
- const parsedUrl = new URL(url);
601
- const contentTypeFromExtname = mime.contentType(extname(parsedUrl.pathname)) || 'application/octet-stream; charset=utf-8'; // Fallback content type, specified in https://tools.ietf.org/html/rfc7231#section-3.1.1.5
602
- parsedContentType = contentTypeParser.parse(contentTypeFromExtname);
603
- }
604
- return {
605
- type: parsedContentType.type,
606
- charset: parsedContentType.parameters.charset,
521
+ // When saveResponseCookies is false, the response cookies must not mutate the
522
+ // session jar. Reads still go through the session (so session.setCookie() in pre-nav
523
+ // hooks keeps working) but a per-request clone is passed in so writes are discarded.
524
+ const cookieJar = this.saveResponseCookies ? session.cookieJar : await session.cookieJar.clone();
525
+ // Bind the request to the shared navigation window instead of a fixed per-request timeout, so
526
+ // `extendTimeout()` can push the deadline and a fixed `AbortSignal.timeout` won't fire on its own and
527
+ // kill a lazily-read body mid-extension. This aborts the socket only during the header phase; the body
528
+ // read is bounded separately at the promise level (see `processHttpResponse`), so a slow-streaming body
529
+ // still fails cleanly with a navigation timeout, though the socket is left to close on its own.
530
+ const cancelSignal = storage.getStore()?.cancelTask.signal;
531
+ const response = await this.httpClient.sendRequest(new Request(opts.url, {
532
+ body: opts.body ? Readable.toWeb(opts.body) : undefined,
533
+ headers: new Headers(opts.headers),
534
+ method: opts.method,
535
+ // Node-specific option to make the request body work with streams
536
+ duplex: 'half',
537
+ }), {
538
+ session,
539
+ cookieJar,
540
+ signal: cancelSignal,
541
+ timeoutMillis: cancelSignal ? undefined : opts.timeout,
542
+ });
543
+ return response;
607
544
  };
608
545
  }
609
- /**
610
- * Creates new {@link Router} instance that works based on request labels.
611
- * This instance can then serve as a `requestHandler` of your {@link HttpCrawler}.
612
- * Defaults to the {@link HttpCrawlingContext}.
613
- *
614
- * > Serves as a shortcut for using `Router.create<HttpCrawlingContext>()`.
615
- *
616
- * ```ts
617
- * import { HttpCrawler, createHttpRouter } from 'crawlee';
618
- *
619
- * const router = createHttpRouter();
620
- * router.addHandler('label-a', async (ctx) => {
621
- * ctx.log.info('...');
622
- * });
623
- * router.addDefaultHandler(async (ctx) => {
624
- * ctx.log.info('...');
625
- * });
626
- *
627
- * const crawler = new HttpCrawler({
628
- * requestHandler: router,
629
- * });
630
- * await crawler.run();
631
- * ```
632
- */
633
- export function createHttpRouter(routes) {
634
- return Router.create(routes);
546
+ export function createHttpRouter(routesOrSchemas) {
547
+ return Router.create(routesOrSchemas);
635
548
  }
636
- //# sourceMappingURL=http-crawler.js.map