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
Developmed of Squid proxy chain and unit tests
Jan Curn88c5d35c3f96
diff --git a/package.json b/package.jsonindex 8c66adbd2..f7347b46d 100644--- a/package.json+++ b/package.json@@ -43,7 +43,8 @@"apify-client": ">=0.1.13","underscore": "^1.8.3","portastic": "^1.0.1",- "tmp": "^0.0.31"+ "tmp": "^0.0.31",+ "bluebird": "^3.5.0"},"devDependencies": {"babel-cli": "^6.6.5",@@ -52,7 +53,6 @@"babel-preset-es2015": "^6.1.18","babel-preset-stage-0": "^6.1.18","basic-auth-parser": "^0.0.2",- "bluebird": "^3.5.0","chai": "^4.0.2","eslint": "^3.19.0","eslint-config-airbnb": "^15.0.1",diff --git a/src/browser.js b/src/browser.jsindex 6613b59c3..d94b67953 100644--- a/src/browser.js+++ b/src/browser.js@@ -13,6 +13,8 @@ import { ProxyChainManager } from './proxy_chain_manager';// logging.installConsoleHandler();// logging.getLogger('webdriver.http').setLevel(logging.Level.ALL);+// TODO: on first use of Apifier.browse(), print out the version of Chrome and ChromeDriver+/*** Gets the default options for the browse() function, generated from current process environmentdiff --git a/src/proxy_chain_manager.js b/src/proxy_chain_manager.jsindex b4a2bd31f..242ba80d0 100644--- a/src/proxy_chain_manager.js+++ b/src/proxy_chain_manager.js@@ -1,13 +1,33 @@+import childProcess from 'child_process';+import fs from 'fs';+import path from 'path';import _ from 'underscore';+import tmp from 'tmp';import portastic from 'portastic';+import Promise from 'bluebird';+import { parseUrl } from './utils';/* globals process */-const PROXY_CHAIN_PORT_FROM = 50000;-const PROXY_CHAIN_PORT_TO = 60000;-const PROXY_CHAIN_HOST = '127.0.0.1';-const PROXY_CHAIN_PROTOCOL = 'http:';+// Exported to allow unit-testing+export const PROXY_CHAIN = {+ PORT_FROM: 55000,+ PORT_TO: 60000,+ HOST: '127.0.0.1',+ PROTOCOL: 'http:',+ SQUID_CMD: 'squid',+};+const tmpDirPromised = Promise.promisify(tmp.dir);+const fsWriteFilePromised = Promise.promisify(fs.writeFile);++/**+ * The class is used to manage a local Squid proxy process instance+ * that forwards HTTP requests to user-provided parent proxies.+ * The point of this is that there's no easy way to programmatically pass proxy+ * authentication credentials to web browsers such as Chrome, so we need to setup+ * local open proxy that can forward to parent proxy with authentication.+ */export class ProxyChainManager {constructor() {// Dictionary of all proxy chains, key is Squid proxy port, value is parsed@@ -16,34 +36,37 @@ export class ProxyChainManager {// PID of the Squid proxy processthis.squidPid = null;++ // Path to temporary directory with config files+ this.tmpDir = null;}/**- * Sets up an open child proxy which forwards to a specified parent proxy with authentication.+ * Sets up an open child proxy which forwards to a specified parent proxy.* @param parsedChildProxyUrl Parsed URL of the parent proxy.* @return Promise Promise resolving to the parsed URL of the child proxy.*/addProxyChain(parsedProxyUrl) {let parsedChildProxyUrl;return ProxyChainManager._findFreePort()- .then((port) => {- this.portToParsedProxyUrl[port] = _.clone(parsedProxyUrl);- parsedChildProxyUrl = parseUrl(`${PROXY_CHAIN_PROTOCOL}//${PROXY_CHAIN_HOST}:${port}`);- return this._manageSquidProcess();- })- .then(() => {- return parsedChildProxyUrl;- });+ .then((port) => {+ this.portToParsedProxyUrl[port] = _.clone(parsedProxyUrl);+ parsedChildProxyUrl = parseUrl(`${PROXY_CHAIN.PROTOCOL}//${PROXY_CHAIN.HOST}:${port}`);+ return this._manageSquidProcess();+ })+ .then(() => {+ return parsedChildProxyUrl;+ });}/*** Removes a child proxy.- * @param childParsedUrl Result of the previous call from the addProxyChain() function.+ * @param parsedChildProxyUrl The result of the earlier call to the addProxyChain() method.* @return Promise Returns a promise that resolves when the proxy chain is reconfigured.*/removeProxyChain(parsedChildProxyUrl) {- if (parsedChildProxyUrl.protocol === PROXY_CHAIN_PROTOCOL- && parsedChildProxyUrl.host === PROXY_CHAIN_HOST+ if (parsedChildProxyUrl.protocol === PROXY_CHAIN.PROTOCOL+ && parsedChildProxyUrl.host === PROXY_CHAIN.HOST&& this.portToParsedProxyUrl[parsedChildProxyUrl.port]) {delete this.portToParsedProxyUrl[parsedChildProxyUrl.port];return this._manageSquidProcess();@@ -52,35 +75,47 @@ export class ProxyChainManager {static _findFreePort() {return portastic.find({- min: PROXY_CHAIN_PORT_FROM,- max: PROXY_CHAIN_PORT_TO,+ min: PROXY_CHAIN.PORT_FROM,+ max: PROXY_CHAIN.PORT_TO,retrieve: 1,}).then((ports) => {- if (ports.length < 1) throw new Error(`There are no more free ports in range from ${PROXY_CHAIN_PORT_FROM} to ${PROXY_CHAIN_PORT_TO}`);+ if (ports.length < 1) throw new Error(`ProxyChainManager: There are no more free ports in range from ${PROXY_CHAIN.PORT_FROM} to ${PROXY_CHAIN.PORT_TO}`); // eslint-disable-line max-lenreturn ports[0];});}+ /**+ * Determines whether the Squid process is still running.+ * @return Boolean+ * @private+ */+ _isSquidRunning() {+ // Inspired by https://github.com/nisaacson/is-running/blob/master/index.js+ if (!this.squidPid) return false;+ try {+ return !!process.kill(this.squidPid, 0);+ } catch (e) {+ return e.code === 'EPERM';+ }+ }+/*** Manages Squid proxy process, which means the function either starts it, updates its configuration or kills it,* depending on the state of the `portToParsedProxyUrl` field.* @private*/_manageSquidProcess() {- // First, check whether the Squid process is still running- // (inspired by https://github.com/nisaacson/is-running/blob/master/index.js)- if (this.squidPid) {- let isRunning;- try {- isRunning = !!process.kill(this.squidPid, 0);- } catch (e) {- isRunning = e.code === 'EPERM';- }- if (!isRunning) this.squidPid = null;+ // TODO: we should ensure that this method only runs once a time,+ // to avoid conflicts in config settings, e.g. using async module's queue+ // TODO: automatically restart squid process if it crashed, maybe using forever package? or simply using setInterval()++ // First, make sure that squidPid refers to the running Squid process+ if (this.squidPid && !this._isSquidRunning()) {+ this.squidPid = null;}- // If Squid shouldn't be running but sill is, kill it+ // If Squid is no longer needed but it is still running, kill it to save system resourcesif (_.isEmpty(this.portToParsedProxyUrl)) {if (this.squidPid) {process.kill(this.squidPid);@@ -89,15 +124,88 @@ export class ProxyChainManager {return;}- const squidConf = this._generateSquidConf();-+ // If Squid is not running yet but should be, start itif (!this.squidPid) {- // Squid is not running => start it- // TODO- } else {- // Squid is already running => reconfigure it- // TODO+ return Promise.resolve()+ .then(() => {+ // Create temporary directory, if not created yet+ if (!this.tmpDir) {+ return tmpDirPromised({ template: '/tmp/squid-XXXXXX' })+ .then((tmpDir) => {+ this.tmpDir = tmpDir;+ });+ }+ })+ .then(() => {+ // Store configuration file to temp dir+ return this._writeSquidConf();+ })+ .then((squidConfPath) => {+ // Start Squid process+ const args = [`-f ${squidConfPath}`, '-N'];+ const options = { cwd: this.tmpDir };+ const process = childProcess.spawn(PROXY_CHAIN.SQUID_CMD, args, options);++ // Wait for Squid process to be running or fail+ return new Promise((resolve, reject) => {+ let isFinished = false;+ const intervalId = setInterval(() => {+ if (this._isSquidRunning()) {+ clearInterval(intervalId);+ isFinished = true;+ resolve();+ }+ }, 50);++ process.on('error', (err) => {+ if (isFinished) {+ console.log(`ProxyChainManager: Squid process failed: ${err}`);+ return;+ }++ // Give a user-friendly message for this common error+ if (err.code === 'ENOENT') err = new Error('ProxyChainManager: "squid" command not found in the PATH');++ clearInterval(intervalId);+ isFinished = true;+ reject(err);+ });+ });+ });}++ // Squid is already running, reconfigure it+ return Promise.resolve()+ .then(() => {+ // Store configuration file to temp dir+ return this._writeSquidConf();+ })+ .then((squidConfPath) => {+ // Run Squid process to reconfigure the other running instance and wait for the finish+ const args = [`-f ${squidConfPath}`, '-k reconfigure'];+ const options = { cwd: this.tmpDir };+ const process = childProcess.spawn(PROXY_CHAIN.SQUID_CMD, args, options);++ // Wait for Squid reconfiguration process to exit or fail+ return new Promise((resolve, reject) => {+ let isFinished = false;+ process.on('exit', (code, signal) => {+ if (!isFinished) {+ isFinished = true;+ if (code !== 0) {+ return reject(new Error(`ProxyChainManager: Squid reconfiguration process failed (exit code: ${code}, signal: ${signal})`)); // eslint-disable-line max-len+ }+ resolve();+ }+ });+ process.on('error', (err) => {+ if (!isFinished) {+ isFinished = true;+ return reject(new Error(`ProxyChainManager: Squid reconfiguration process failed: ${err}`));+ }+ });+ });+ });}static _generateSquidConfForPort(parsedProxyUrl, squidPort) {@@ -110,11 +218,19 @@ export class ProxyChainManager {return str;}- _generateSquidConf() {- const chainConfs = _.mapObject(this.portToParsedProxyUrl, (parsedProxyUrl, port) => {- return this._generateSquidConfForPort(parsedProxyUrl, port);- }).join('\n');+ /**+ * Generates Squid proxy configuration file and writes it to the temporary directory.+ * @return Promise Promise resolving to the path to the configuration file.+ * @private+ */+ _writeSquidConf() {+ if (!this.tmpDir) throw new Error('Temporary directory not created yet');++ const chainConfs = _.values(_.mapObject(this.portToParsedProxyUrl, (parsedProxyUrl, port) => {+ return ProxyChainManager._generateSquidConfForPort(parsedProxyUrl, port);+ }));+ // NOTE: set pid_filename to isolate our squid instance from others possibly running in the systemconst conf = `http_access allow allnever_direct allow all@@ -122,9 +238,16 @@ access_log nonecache_store_log nonecache_log /dev/nulllogfile_rotate 0+pid_filename ${path.join(this.tmpDir, 'squid.pid')}${chainConfs}`;- return conf;+ const filePath = path.join(this.tmpDir, 'squid.conf');++ console.log(`Squid config:\n${conf}`);+ return fsWriteFilePromised(filePath, conf)+ .then(() => {+ return filePath;+ });}}diff --git a/src/utils.js b/src/utils.jsindex 8d38c10a0..4ee5984fc 100644--- a/src/utils.js+++ b/src/utils.js@@ -8,6 +8,8 @@ let PromisesDependency = typeof Promise === 'function' ? Promise : null;// TODO: add methods to override console.log() and console.error(), add unit tests for that!+// TODO: use bluebird promise by default instead of native promise, rename newPromise() to newUserPromise(), get rid of nodeifyPromise()+/*** Sets the promise dependency the SDK will use wherever Promises are returned.* Passing `null` will force the SDK to use native Promises if they are available.diff --git a/test/proxy_chain_manager.js b/test/proxy_chain_manager.jsnew file mode 100644index 000000000..ffd770b02--- /dev/null+++ b/test/proxy_chain_manager.js@@ -0,0 +1,99 @@+import _ from 'underscore';+import { expect, assert } from 'chai';+import proxy from 'proxy';+import http from 'http';+import portastic from 'portastic';+import basicAuthParser from 'basic-auth-parser';+import Promise from 'bluebird';++import { getDefaultBrowseOptions } from '../build/browser';+import Apifier from '../build/index';+import { parseUrl } from '../build/utils';+import { ProxyChainManager, PROXY_CHAIN } from '../build/proxy_chain_manager';++/* globals process */++const ORIG_PROXY_CHAIN = _.clone(PROXY_CHAIN);++let proxyServer;+let proxyPort; // eslint-disable-line no-unused-vars+const proxyAuth = { scheme: 'Basic', username: 'username', password: 'password' };+let wasProxyCalled = false; // eslint-disable-line no-unused-vars++// Setup local proxy server for the tests+before(() => {+ // Find free port for the proxy+ return portastic.find({ min: 50000, max: 50100 }).then((ports) => {+ return new Promise((resolve, reject) => {+ const httpServer = http.createServer();++ // Setup proxy authorization+ httpServer.authenticate = function (req, fn) {+ // parse the "Proxy-Authorization" header+ const auth = req.headers['proxy-authorization'];+ if (!auth) {+ // optimization: don't invoke the child process if no+ // "Proxy-Authorization" header was given+ // console.log('not Proxy-Authorization');+ return fn(null, false);+ }+ const parsed = basicAuthParser(auth);+ const isEqual = _.isEqual(parsed, proxyAuth);+ console.log('parsed "Proxy-Authorization": %j - %s', parsed, isEqual);+ if (isEqual) wasProxyCalled = true;+ fn(null, isEqual);+ };++ httpServer.on('error', reject);++ proxyServer = proxy(httpServer);+ proxyServer.listen(ports[0], () => {+ proxyPort = proxyServer.address().port;+ resolve();+ });+ });+ });+});++after(function () {+ this.timeout(60 * 1000);+ if (proxyServer) return Promise.promisify(proxyServer.close).bind(proxyServer)();+});+++describe('ProxyChainManager.addProxyChain()', function () {+ // Need larger timeout for Travis CI+ this.timeout(10 * 1000);++ it('throws nice error when "squid" command not found', () => {+ const mng = new ProxyChainManager();+ PROXY_CHAIN.SQUID_CMD = 'command-that-does-not-exist';+ return mng.addProxyChain(parseUrl(`http://localhost:${proxyPort}`))+ .then(() => {+ assert.fail();+ })+ .catch((err) => {+ expect(err.message).to.contain('"squid" command not found in the PATH');+ })+ .finally(() => {+ Object.assign(PROXY_CHAIN, ORIG_PROXY_CHAIN);+ });+ });++ it('throws nice error when no more free ports available', () => {+ const mng = new ProxyChainManager();+ // we're listening on proxyPort+ PROXY_CHAIN.PORT_FROM = proxyPort;+ PROXY_CHAIN.PORT_TO = proxyPort;+ return mng.addProxyChain(parseUrl(`http://localhost:${proxyPort}`))+ .then(() => {+ assert.fail();+ })+ .catch((err) => {+ expect(err.message).to.contain('There are no more free ports');+ })+ .finally(() => {+ Object.assign(PROXY_CHAIN, ORIG_PROXY_CHAIN);+ });+ });+});