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.

Improve request creation performance (#869)

Andrey Bykov42d19197c3fe
diff --git a/src/request.js b/src/request.js
index c00efc6b4..f396f49f2 100644
--- a/src/request.js
+++ b/src/request.js
@@ -1,6 +1,6 @@
import { normalizeUrl } from 'apify-shared/utilities';
import * as crypto from 'crypto';
-import ow from 'ow';
+import ow, { ArgumentError } from 'ow';
import * as util from 'util';
import defaultLog from './utils_log';
@@ -16,6 +16,22 @@ export function hashPayload(payload) {
.substr(0, 8);
}
+const requestOptionalPredicates = {
+ id: ow.optional.string,
+ loadedUrl: ow.optional.string.url,
+ uniqueKey: ow.optional.string,
+ method: ow.optional.string,
+ payload: ow.optional.any(ow.string, ow.buffer),
+ noRetry: ow.optional.boolean,
+ retryCount: ow.optional.number,
+ errorMessages: ow.optional.array.ofType(ow.string),
+ headers: ow.optional.object,
+ userData: ow.optional.object,
+ handledAt: ow.optional.any(ow.string.date, ow.date),
+ keepUrlFragment: ow.optional.boolean,
+ useExtendedUniqueKey: ow.optional.boolean,
+};
+
/**
* Represents a URL to be crawled, optionally including HTTP method, headers, payload and other metadata.
* The `Request` object also stores information about errors that occurred during processing of the request.
@@ -81,22 +97,24 @@ class Request {
* `Request` parameters including the URL, HTTP method and headers, and others.
*/
constructor(options) {
- ow(options, ow.object.exactShape({
- url: ow.string.url,
- id: ow.optional.string,
- loadedUrl: ow.optional.string.url,
- uniqueKey: ow.optional.string,
- method: ow.optional.string,
- payload: ow.optional.any(ow.string, ow.buffer),
- noRetry: ow.optional.boolean,
- retryCount: ow.optional.number,
- errorMessages: ow.optional.array.ofType(ow.string),
- headers: ow.optional.object,
- userData: ow.optional.object,
- handledAt: ow.optional.any(ow.string.date, ow.date),
- keepUrlFragment: ow.optional.boolean,
- useExtendedUniqueKey: ow.optional.boolean,
- }));
+ ow(options, 'RequestOptions', ow.object);
+ ow(options.url, 'RequestOptions.url', ow.string.url);
+ // 'ow' validation is slow, because it checks all predicates
+ // even if the validated object has only 1 property.
+ // This custom validation loop iterates only over existing
+ // properties and speeds up the validation cca 3-fold.
+ // See https://github.com/sindresorhus/ow/issues/193
+ Object.keys(options).forEach((prop) => {
+ const predicate = requestOptionalPredicates[prop];
+ const value = options[prop];
+ if (predicate) {
+ ow(value, `RequestOptions.${prop}`, predicate);
+ // 'url' is checked above because it's not optional
+ } else if (prop !== 'url') {
+ const msg = `Did not expect property \`${prop}\` to exist, got \`${value}\` in object \`RequestOptions\``;
+ throw new ArgumentError(msg, this.constructor);
+ }
+ });
const {
id,
@@ -125,9 +143,9 @@ class Request {
this.payload = payload;
this.noRetry = noRetry;
this.retryCount = retryCount;
- this.errorMessages = JSON.parse(JSON.stringify(errorMessages));
- this.headers = JSON.parse(JSON.stringify(headers));
- this.userData = JSON.parse(JSON.stringify(userData));
+ this.errorMessages = [...errorMessages];
+ this.headers = { ...headers };
+ this.userData = { ...userData };
// Requests received from API will have ISOString dates,
// but we want to have a Date instance.
this.handledAt = typeof handledAt === 'string'
diff --git a/test/request.test.js b/test/request.test.js
index 5ebfa795c..ff5276fe8 100644
--- a/test/request.test.js
+++ b/test/request.test.js
@@ -6,7 +6,10 @@ import Apify from '../build/index';
describe('Apify.Request', () => {
test('should not accept invalid values', () => {
expect(() => new Apify.Request({ url: 1 })).toThrowError();
- expect(() => new Apify.Request({ url: 'https://www.test12345xxx' })).not.toThrowError();
+ expect(() => new Apify.Request({ url: 'https://apify.com' })).not.toThrowError();
+ expect(() => new Apify.Request({ url: 'https://apify.com', method: 1 })).toThrowError();
+ expect(() => new Apify.Request({ url: 'https://apify.com', headers: 'x' })).toThrowError();
+ expect(() => new Apify.Request({ url: 'https://apify.com', foo: 'invalid-property' })).toThrowError();
});
test('should create unique key based on url for GET requests', () => {
@@ -18,20 +21,17 @@ describe('Apify.Request', () => {
expect(request.uniqueKey).not.toEqual(request.url);
});
- test(
- 'should create unique key based on url, method and payload for POST requests',
- () => {
- const url = 'https://user:[email protected]/a/vb/c /d?q=1&q=kjnjkn$lkn#lkmlkml';
- const payload = JSON.stringify({ foo: 'bar' });
- const payloadHash = hashPayload(payload);
- const normalizedUrl = normalizeUrl(url);
- const request = new Apify.Request({ url, method: 'post', payload, useExtendedUniqueKey: true });
+ test('should create unique key based on url, method and payload for POST requests', () => {
+ const url = 'https://user:[email protected]/a/vb/c /d?q=1&q=kjnjkn$lkn#lkmlkml';
+ const payload = JSON.stringify({ foo: 'bar' });
+ const payloadHash = hashPayload(payload);
+ const normalizedUrl = normalizeUrl(url);
+ const request = new Apify.Request({ url, method: 'post', payload, useExtendedUniqueKey: true });
- const uniqueKey = `POST(${payloadHash}):${normalizedUrl}`;
+ const uniqueKey = `POST(${payloadHash}):${normalizedUrl}`;
- expect(request.uniqueKey).toEqual(uniqueKey);
- },
- );
+ expect(request.uniqueKey).toEqual(uniqueKey);
+ });
test('works', () => {
const data = {
@@ -119,4 +119,15 @@ describe('Apify.Request', () => {
expect(() => new Apify.Request({ url: 'http://example.com', payload: 'foo' })).toThrowError();
expect(() => new Apify.Request({ url: 'http://example.com', payload: 'foo', method: 'POST' })).not.toThrowError();
});
+
+ test('should have acceptable request creation time', () => {
+ const requests = [];
+ const start = Date.now();
+ for (let i = 0; i < 1000; i++) requests.push(new Apify.Request({ url: `https://example.com/${i}` }));
+ const durationMillis = Date.now() - start;
+ // Under normal load, the Requests are created in ~25-30ms
+ // In tests the load is high, so we only check if it doesn't
+ // overshoot some crazy range like 100ms.
+ expect(durationMillis).toBeLessThan(100);
+ });
});