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
Feature/sigterm (#57)
Marek Trunkát94680a97161a
diff --git a/.babelrc b/.babelrcindex ec553ce6a..b1c52cc55 100644--- a/.babelrc+++ b/.babelrc@@ -1,3 +1,9 @@{- presets: ["es2015", "stage-0"]+ "presets": [+ ["babel-preset-env", {+ "targets": {+ "node": "7.0.0"+ }+ }]+ ]}\ No newline at end of filediff --git a/.travis.yml b/.travis.ymlindex 88a2a21ff..677cb93f9 100644--- a/.travis.yml+++ b/.travis.yml@@ -16,7 +16,6 @@ language: node_jsnode_js:- "8"- "7"- - "6"script:- npm run lint- npm testdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4b25abd92..322acaaa4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,7 +6,11 @@ xxxxxx / xxxxxxxxxx- `AutoscaledPool` was completely redesigned. Check documentation for reference. It still supports previousconfiguration parameters for backwards compatibility but in the future compatibility will break.- `launchPuppeteer()` changes `User-Agent` only when in headless mode or if not using full Google Chrome,- to reduce chance of detection of the crawler+ to reduce chance of detection of the crawler.+- Apify package now supports Node 7 and newer.+- `AutoscaledPool` now scales down less aggresively.+- `PuppeteerCrawler` and `BasicCrawler` now allow its underlying `AutoscaledPool` function `isFunction` to be overriden.+- New events `persistState` and `migrating` added. Check documentation of `Apify.events` for more information.0.5.17 / 2018-03-27===================diff --git a/package.json b/package.jsonindex 27b93c197..0594c1dff 100644--- a/package.json+++ b/package.json@@ -44,23 +44,20 @@},"dependencies": {"apify-client": "^0.2.7",- "apify-shared": "0.0.23",+ "apify-shared": "0.0.25","bluebird": "^3.5.0","content-type": "^1.0.3","fs-extra": "^5.0.0",- "proxy-chain": "^0.1.2",+ "proxy-chain": "^0.1.26","request-promise": "^4.2.2","underscore": "^1.8.3","ws": "^5.1.0"},"devDependencies": {"apify-jsdoc-template": "github:apifytech/apify-jsdoc-template",- "babel-cli": "^6.6.5",- "babel-core": "^6.1.21",- "babel-eslint": "^8.0.2",+ "babel-cli": "^6.26.0","babel-polyfill": "^6.26.0",- "babel-preset-es2015": "^6.1.18",- "babel-preset-stage-0": "^6.1.18",+ "babel-preset-env": "^1.6.1","basic-auth-parser": "^0.0.2","chai": "^4.0.2","chai-as-promised": "^7.1.1",@@ -74,7 +71,7 @@"isparta": "^4.0.0","jsdoc": "^3.4.3","jsdoc-export-default-interop": "^0.3.1",- "mocha": "^3.2.0",+ "mocha": "^3.5.3","portastic": "^1.0.1","proxy": "^0.2.4","request": "^2.81.0",diff --git a/src/actor.js b/src/actor.jsindex 6351ab8b7..f8b174720 100644--- a/src/actor.js+++ b/src/actor.js@@ -1,11 +1,9 @@import _ from 'underscore';import Promise from 'bluebird';import fs from 'fs';-import EventEmitter from 'events';-import WebSocket from 'ws';-import log from 'apify-shared/log';import { checkParamOrThrow } from 'apify-client/build/utils';import { ENV_VARS, EXIT_CODES, ACT_TASK_TERMINAL_STATUSES, DEFAULT_PROXY_HOSTNAME, DEFAULT_PROXY_PORT } from './constants';+import { initializeEvents, stopEvents } from './events';import { newPromise, apifyClient, addCharsetToContentType } from './utils';import { maybeStringify } from './key_value_store';@@ -22,75 +20,6 @@ const tryParseDate = (str) => {return unix > 0 ? new Date(unix) : undefined;};-/**- * Event emitter providing access to events from Actor infrastructure. Event emitter is initiated by Apify.main().- * If you don't use Apify.main() then you must call `await Apify.initializeEvents()` yourself.- *- * Example usage:- *- * ```javascript- * import { ACTOR_EVENT_NAMES } from 'apify/constants';- *- * Apify.main(async () => {- * - * Apify.events.on(ACTOR_EVENT_NAMES.CPU_INFO, (data) => {- * if (data.isCpuOverloaded) console.log('OH NO! We are overloading CPU!');- * });- *. - * });- * ```- *- * See <a href="https://nodejs.org/api/events.html#events_class_eventemitter" target="_blank">NodeJs documentation</a>- * for more information about event emitter use.- *- * @memberof module:Apify- * @name events- */-export const events = new EventEmitter();--/**- * Websocket connection to actor events.- * @ignore- */-let eventsWs = null;--/**- * Initializes Apify.events event emitter by creating connection to a websocket that provides them.- *- * @memberof module:Apify- * @name initializeEvents- * @function- */-export const initializeEvents = () => {- if (eventsWs) return;-- const eventsWsUrl = process.env[ENV_VARS.ACTOR_EVENTS_WS_URL];-- // Locally there is no web socket to connect so just print a log message.- if (!eventsWsUrl) {- log.info(`Environment variable ${ENV_VARS.ACTOR_EVENTS_WS_URL} is not set, Apify.events will not emit any events.`);- return;- }-- eventsWs = new WebSocket(eventsWsUrl);- eventsWs.on('message', (message) => {- if (!message) return;-- try {- const { name, data } = JSON.parse(message);-- events.emit(name, data);- } catch (err) {- log.exception(err, 'Cannot parse actor event');- }- });- eventsWs.on('error', err => log.exception(err, 'Actor events web socket connection failed'));- eventsWs.on('close', () => {- log.warning('Actor events web socket has been closed');- eventsWs = null;- });-};-/*** Returns a new object which contains information parsed from the `APIFY_XXX` environment variables.* It has the following properties:@@ -237,12 +166,14 @@ export const main = (userFunc) => {.then(() => initializeEvents()).then(() => userFunc()).catch((err) => {+ stopEvents();clearInterval(intervalId);if (!exited) {exitWithError(err, EXIT_CODES.ERROR_USER_FUNCTION_THREW, 'User function threw an exception:');}}).then(() => {+ stopEvents();clearInterval(intervalId);if (!exited) {process.exit(EXIT_CODES.SUCCESS);diff --git a/src/autoscaled_pool.js b/src/autoscaled_pool.jsindex 1e063f00f..b5ced9067 100644--- a/src/autoscaled_pool.js+++ b/src/autoscaled_pool.js@@ -3,7 +3,7 @@ import log from 'apify-shared/log';import _ from 'underscore';import { checkParamOrThrow } from 'apify-client/build/utils';import { getMemoryInfo, isPromise } from './utils';-import { events } from './actor';+import events from './events';import { ACTOR_EVENT_NAMES } from './constants';const MEM_CHECK_INTERVAL_MILLIS = 200; // This is low to have at least.diff --git a/src/events.js b/src/events.jsnew file mode 100644index 000000000..2b2052919--- /dev/null+++ b/src/events.js@@ -0,0 +1,167 @@+import EventEmitter from 'events';+import WebSocket from 'ws';+import log from 'apify-shared/log';+import { ENV_VARS, ACTOR_EVENT_NAMES } from './constants';++const PERSIST_STATE_INTERVAL_MILLIS = 60 * 1000;++/**+ * Event emitter providing events from underlying Actor infrastructure and Apify package.+ * @ignore+ */+const events = new EventEmitter();++/**+ * Websocket connection to actor events.+ * @ignore+ */+let eventsWs = null;++/**+ * Interval that emits persist state events.+ * @ignore+ */+let persistStateInterval = null;++/**+ * Event emitter providing access to events from Actor infrastructure. Event emitter is initiated by Apify.main().+ * If you don't use Apify.main() then you must call `await Apify.initializeEvents()` yourself.+ *+ * Example usage:+ *+ * ```javascript+ * import { ACTOR_EVENT_NAMES } from 'apify/constants';+ *+ * Apify.main(async () => {+ * + * Apify.events.on(ACTOR_EVENT_NAMES.CPU_INFO, (data) => {+ * if (data.isCpuOverloaded) console.log('OH NO! We are overloading CPU!');+ * });+ *. + * });+ * ```+ *+ * Event types:+ *+ * <table class="table table-bordered table-condensed">+ * <thead>+ * <tr>+ * <th>Name</th>+ * <th>Constant</th>+ * <ht>Message</th>+ * <ht>Description</th>+ * </thead>+ * <tbody>+ * <tr>+ * <td>cpuInfo</td>+ * <td>`ACTOR_EVENT_NAMES.CPU_INFO`</td>+ * <td>`{ "isCpuOverloaded": true }`</td>+ * <td>+ * This event is send every second and contains information if act is using maximum amount of available+ * CPU power. If maximum is reached then there is no point in adding more workload.+ * </td>+ * </tr>+ * <tr>+ * <td>migrating</td>+ * <td>`ACTOR_EVENT_NAMES.MIGRATING`</td>+ * <td>`null`</td>+ * <td>+ * This event is send when act is going to be migrated to another worker machine. In this case act run will+ * be stopped and then reinitialized at another server.+ * </td>+ * </tr>+ * <tr>+ * <td>persistState</td>+ * <td>`ACTOR_EVENT_NAMES.PERSIST_STATE`</td>+ * <td>`{ "isMigrating": true }`</td>+ * <td>+ * This event is send in regular intervals to notify all components of Apify SDK that it's time to persist+ * state. This prevents situation when act gets restarted due to a migration to another worker machine and+ * needs to start from scratch. This event is also send as a result of `ACTOR_EVENT_NAMES.MIGRATING` and in+ * this case the message is `{ "isMigrating": true }`.+ * </td>+ * </tr>+ * </tbody>+ * </table>+ *+ * See <a href="https://nodejs.org/api/events.html#events_class_eventemitter" target="_blank">NodeJs documentation</a>+ * for more information about event emitter use.+ *+ * @memberof module:Apify+ * @name events+ */+export default events;++/**+ * Emits event telling all comonents that they should persist their state in regular interval and also when act is being+ * migrated to another worker.+ *+ * @ignore+ */+const emitPersistStateEvent = (isMigrating = false) => {+ events.emit(ACTOR_EVENT_NAMES.PERSIST_STATE, { isMigrating });+};++/**+ * Initializes Apify.events event emitter by creating connection to a websocket that provides them.+ * This is automatically called by `Apify.main()`.+ *+ * @memberof module:Apify+ * @name initializeEvents+ * @function+ */+export const initializeEvents = () => {+ if (eventsWs) return;++ if (!persistStateInterval) {+ // This is overridable only to enable unit testing.+ const intervalMillis = process.env.APIFY_TEST_PERSIST_INTERVAL_MILLIS || PERSIST_STATE_INTERVAL_MILLIS;+ persistStateInterval = setInterval(() => emitPersistStateEvent(), intervalMillis);+ }++ const eventsWsUrl = process.env[ENV_VARS.ACTOR_EVENTS_WS_URL];++ // Locally there is no web socket to connect so just print a log message.+ if (!eventsWsUrl) {+ log.info(`Environment variable ${ENV_VARS.ACTOR_EVENTS_WS_URL} is not set, Apify.events will not emit any events.`);+ return;+ }++ eventsWs = new WebSocket(eventsWsUrl);+ eventsWs.on('message', (message) => {+ if (!message) return;++ try {+ const { name, data } = JSON.parse(message);++ events.emit(name, data);++ if (name === ACTOR_EVENT_NAMES.MIGRATING) {+ clearInterval(persistStateInterval); // Don't send any other persist state event.+ emitPersistStateEvent(true);+ }+ } catch (err) {+ log.exception(err, 'Cannot parse actor event');+ }+ });+ eventsWs.on('error', err => log.exception(err, 'Actor events web socket connection failed'));+ eventsWs.on('close', () => {+ log.warning('Actor events web socket has been closed');+ eventsWs = null;+ });+};++/**+ * Closes websocket providing events from Actor infrastructure and also stops sending internal events+ * of Apify package such as `persistState`.+ * This is automatically called at the end of `Apify.main()`.+ *+ * @memberof module:Apify+ * @name stopEvents+ * @function+ */+export const stopEvents = () => {+ if (eventsWs) eventsWs.close();+ clearInterval(persistStateInterval);+ persistStateInterval = null;+};diff --git a/src/index.js b/src/index.jsindex 49b98cf0d..41eaa6ede 100644--- a/src/index.js+++ b/src/index.js@@ -1,9 +1,10 @@import log from 'apify-shared/log';import { ENV_VARS } from './constants';-import { main, readyFreddy, getEnv, call, getApifyProxyUrl, events, initializeEvents } from './actor';+import { main, readyFreddy, getEnv, call, getApifyProxyUrl } from './actor';import AutoscaledPool from './autoscaled_pool';import BasicCrawler from './basic_crawler';import { pushData, openDataset } from './dataset';+import events, { initializeEvents, stopEvents } from './events';import { getValue, setValue, openKeyValueStore } from './key_value_store';import { launchPuppeteer } from './puppeteer';import PuppeteerCrawler from './puppeteer_crawler';@@ -166,8 +167,6 @@ if (!isProduction() || process.env[ENV_VARS.LOG_LEVEL] === 'DEBUG') log.isDebugMmodule.exports = {// Actormain,- events,- initializeEvents,getEnv,call,readyFreddy,@@ -184,6 +183,11 @@ module.exports = {pushData,openDataset,+ // Events+ events,+ initializeEvents,+ stopEvents,+// Key-value storegetValue,setValue,diff --git a/test/actor.js b/test/actor.jsindex b5e08ae37..6df0b453c 100644--- a/test/actor.js+++ b/test/actor.js@@ -3,7 +3,6 @@ import _ from 'underscore';import chai, { expect } from 'chai';import chaiAsPromised from 'chai-as-promised';import 'babel-polyfill';-import WebSocket from 'ws';import sinon from 'sinon';import tmp from 'tmp';import Promise from 'bluebird';@@ -318,23 +317,6 @@ describe('Apify.main()', () => {});});-describe('Apify.events', () => {- it('is there and works as EventEmitter', () => {- return new Promise((resolve, reject) => {- try {- Apify.events.on('foo', resolve);- Apify.events.emit('foo', 'test event');- } catch (e) {- reject(e);- }- })- .then((arg) => {- expect(arg).to.eql('test event');- });- });-});--describe('Apify.readyFreddy()', () => {it('it works as expected', () => {process.env.APIFY_WATCH_FILE = createWatchFile();@@ -724,73 +706,3 @@ describe('Apify.getApifyProxyUrl()', () => {})).to.be.eql('http://auto:[email protected]:345');});});--describe('Apify.events', () => {- it('should work in Apify.main()', (done) => {- const wss = new WebSocket.Server({ port: 9099 });- const eventsReceived = [];-- // Create server that sends events- wss.on('connection', (ws, req) => {- expect(req.url).to.be.eql('/someRunId');-- const send = obj => ws.send(JSON.stringify(obj));-- setTimeout(() => send({ name: 'name-1', data: [1, 2, 3] }), 50);- setTimeout(() => send({ name: 'name-1', data: { foo: 'bar' } }), 100);- setTimeout(() => send({ name: 'name-2', data: [1] }), 50);- setTimeout(() => send({ name: 'name-2', data: [2] }), 50);- });-- process.env[ENV_VARS.ACTOR_EVENTS_WS_URL] = 'ws://localhost:9099/someRunId';-- // Run main and store received events- Apify.main(async () => {- Apify.events.on('name-1', data => eventsReceived.push(data));- await delayPromise(1000);- });-- // Main will call process.exit() so we must stub it.- const stubbedExit = sinon- .stub(process, 'exit')- .callsFake((code) => {- expect(code).to.be.eql(0);- expect(eventsReceived).to.be.eql([[1, 2, 3], { foo: 'bar' }]);-- // Cleanup.- stubbedExit.restore();- wss.close();- delete process.env[ENV_VARS.ACTOR_EVENTS_WS_URL];- done();- });- });-- it('should work without Apify.main()', async () => {- const wss = new WebSocket.Server({ port: 9099 });- const eventsReceived = [];-- wss.on('connection', (ws, req) => {- expect(req.url).to.be.eql('/someRunId');-- const send = obj => ws.send(JSON.stringify(obj));-- setTimeout(() => send({ name: 'name-1', data: [1, 2, 3] }), 50);- setTimeout(() => send({ name: 'name-1', data: { foo: 'bar' } }), 100);- setTimeout(() => send({ name: 'name-2', data: [1] }), 50);- setTimeout(() => send({ name: 'name-2', data: [2] }), 50);- });-- process.env[ENV_VARS.ACTOR_EVENTS_WS_URL] = 'ws://localhost:9099/someRunId';-- // Connect to websocket and receive events.- await Apify.initializeEvents();- Apify.events.on('name-1', data => eventsReceived.push(data));- await delayPromise(1000);-- expect(eventsReceived).to.be.eql([[1, 2, 3], { foo: 'bar' }]);-- // Cleanup.- wss.close();- delete process.env[ENV_VARS.ACTOR_EVENTS_WS_URL];- });-});diff --git a/test/dataset.js b/test/dataset.jsindex bdcb9aff7..cb88da734 100644--- a/test/dataset.js+++ b/test/dataset.js@@ -175,7 +175,7 @@ describe('dataset', () => {await expect(Apify.pushData(false)).to.be.rejectedWith(dataErrMsg);await expect(Apify.pushData(() => {})).to.be.rejectedWith(dataErrMsg);- const circularObj = { xxx: circularObj };+ const circularObj = {};circularObj.xxx = circularObj;const jsonErrMsg = 'Converting circular structure to JSON';await expect(Apify.pushData(circularObj)).to.be.rejectedWith(jsonErrMsg);diff --git a/test/events.js b/test/events.jsnew file mode 100644index 000000000..8c082326d--- /dev/null+++ b/test/events.js@@ -0,0 +1,134 @@+import 'babel-polyfill';+import WebSocket from 'ws';+import sinon from 'sinon';+import Promise from 'bluebird';+import { expect } from 'chai';+import { delayPromise } from 'apify-shared/utilities';+import { ENV_VARS, ACTOR_EVENT_NAMES } from '../build/constants';+import Apify from '../build';++describe('Apify.events', () => {+ it('is there and works as EventEmitter', () => {+ return new Promise((resolve, reject) => {+ try {+ Apify.events.on('foo', resolve);+ Apify.events.emit('foo', 'test event');+ } catch (e) {+ reject(e);+ }+ })+ .then((arg) => {+ expect(arg).to.eql('test event');+ });+ });++ it('should work in Apify.main()', (done) => {+ const wss = new WebSocket.Server({ port: 9099 });+ const eventsReceived = [];+ let isWsConnected = false;++ // Create server that sends events+ wss.on('connection', (ws, req) => {+ isWsConnected = true;++ ws.on('close', () => {+ isWsConnected = false;+ });++ expect(req.url).to.be.eql('/someRunId');++ const send = obj => ws.send(JSON.stringify(obj));++ setTimeout(() => send({ name: 'name-1', data: [1, 2, 3] }), 50);+ setTimeout(() => send({ name: 'name-1', data: { foo: 'bar' } }), 100);+ setTimeout(() => send({ name: 'name-2', data: [1] }), 50);+ setTimeout(() => send({ name: 'name-2', data: [2] }), 50);+ });++ process.env[ENV_VARS.ACTOR_EVENTS_WS_URL] = 'ws://localhost:9099/someRunId';++ // Run main and store received events+ expect(isWsConnected).to.be.eql(false);+ Apify.main(async () => {+ await delayPromise(10); // Here must be short sleep to get following line to later tick+ expect(isWsConnected).to.be.eql(true);+ Apify.events.on('name-1', data => eventsReceived.push(data));+ await delayPromise(1000);+ });++ // Main will call process.exit() so we must stub it.+ const stubbedExit = sinon+ .stub(process, 'exit')+ .callsFake(async (code) => {+ expect(code).to.be.eql(0);+ expect(eventsReceived).to.be.eql([[1, 2, 3], { foo: 'bar' }]);++ // Cleanup.+ stubbedExit.restore();+ wss.close();+ delete process.env[ENV_VARS.ACTOR_EVENTS_WS_URL];+ await delayPromise(10); // Here must be short sleep to get following line to later tick+ expect(isWsConnected).to.be.eql(false);+ done();+ });+ });++ it('should work without Apify.main()', async () => {+ const wss = new WebSocket.Server({ port: 9099 });+ const eventsReceived = [];+ let isWsConnected = false;++ wss.on('connection', (ws, req) => {+ isWsConnected = true;++ ws.on('close', () => {+ isWsConnected = false;+ });++ expect(req.url).to.be.eql('/someRunId');++ const send = obj => ws.send(JSON.stringify(obj));++ setTimeout(() => send({ name: 'name-1', data: [1, 2, 3] }), 50);+ setTimeout(() => send({ name: 'name-1', data: { foo: 'bar' } }), 100);+ setTimeout(() => send({ name: 'name-2', data: [1] }), 50);+ setTimeout(() => send({ name: 'name-2', data: [2] }), 50);+ });++ process.env[ENV_VARS.ACTOR_EVENTS_WS_URL] = 'ws://localhost:9099/someRunId';++ // Connect to websocket and receive events.+ expect(isWsConnected).to.be.eql(false);+ await Apify.initializeEvents();+ await delayPromise(10); // Here must be short sleep to get following line to later tick+ expect(isWsConnected).to.be.eql(true);+ Apify.events.on('name-1', data => eventsReceived.push(data));+ await delayPromise(1000);++ expect(eventsReceived).to.be.eql([[1, 2, 3], { foo: 'bar' }]);++ expect(isWsConnected).to.be.eql(true);+ Apify.stopEvents();+ await delayPromise(10); // Here must be short sleep to get following line to later tick+ expect(isWsConnected).to.be.eql(false);++ // Cleanup.+ wss.close();+ delete process.env[ENV_VARS.ACTOR_EVENTS_WS_URL];+ });++ it('should send persist state events in regular interval', async () => {+ process.env.APIFY_TEST_PERSIST_INTERVAL_MILLIS = 20;++ const eventsReceived = [];+ Apify.events.on(ACTOR_EVENT_NAMES.PERSIST_STATE, data => eventsReceived.push(data));+ await Apify.initializeEvents();+ await delayPromise(115);+ await Apify.stopEvents();+ expect(eventsReceived.length).to.be.eql(5);+ await delayPromise(50);+ expect(eventsReceived.length).to.be.eql(5);++ delete process.env.APIFY_TEST_PERSIST_INTERVAL_MILLIS;+ });+});