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.

Fix autoscaled pool (#165)

Ondra Urban65ff48e79ad4
diff --git a/.eslintrc.json b/.eslintrc.json
index 54ee1cd18..b091b878d 100644
--- a/.eslintrc.json
+++ b/.eslintrc.json
@@ -23,7 +23,7 @@
"func-names": 0,
"import/prefer-default-export": 0,
"import/no-absolute-path": 0,
- "import/no-extraneous-dependencies": ["error", { "devDependencies": ["**/test/*.js"] }],
+ "import/no-extraneous-dependencies": ["error", { "devDependencies": ["**/test/**/*.js"] }],
"no-await-in-loop": 0
}
}
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 81a57c36d..13b08ea28 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,9 @@
-xxx
+0.8.0 / 2018-09-19
==================
+- BREAKING CHANGES IN AUTOSCALED POOL
+ - It has been completely rebuilt for better performance.
+ - It also now works locally.
+ - see [Migration Guide](MIGRATIONS.md) for more information.
- Updated to [email protected]
0.7.4 / 2018-09-18
diff --git a/MIGRATIONS.md b/MIGRATIONS.md
new file mode 100644
index 000000000..6a01a6c76
--- /dev/null
+++ b/MIGRATIONS.md
@@ -0,0 +1,35 @@
+# Migration from 0.x.x to 0.8.0
+
+## Breaking change 1: AutoscaledPool configuration changed
+
+Originally, AutoscaledPool was just a single class that handled everything. Now it's split into 3 different classes.
+As such, the configuration changed dramatically. The API is the same however.
+
+If you were using any of the following options, you should see the current documentation and migrate accordingly:
+
+1. `options.workerFunction`
+ - REMOVED; see `options.isFinishedFunction` for similar functionality
+2. `options.finishWhenEmpty`
+ - REMOVED; see `options.isFinishedFunction` for similar functionality
+3. `options.ignoreMainProcess`
+ - REMOVED;
+4. `options.maxMemoryMbytes`
+ - MOVED; use `options.snapshotterOptions.maxMemoryMbytes`
+5. `options.minFreeMemoryRatio`
+ - MOVED AND CHANGED; use `options.snapshotterOptions.maxUsedMemoryRatio`
+6. `options.maybeRunIntervalMillis`
+ - CHANGED; use `options.maybeRunIntervalSecs`
+7. `options.loggingIntervalMillis`
+ - CHANGED; use `options.loggingIntervalSecs`
+
+For more configuration options, see Snapshotter and SystemStatus documentation.
+
+## Breaking change 2: Crawlers no longer support passing AutoscaledPool options directly
+
+Previously, setting e.g. `options.isFinishedFunction` directly on the options object passed to
+a Crawler constructor would configure the underlying AutoscaledPool. From v0.8.0,
+the options are available under `options.autoscaledPoolOptions`. Setting a custom `isFinishedFunction`
+is therefore done using `options.autoscaledPoolOptions.isFinishedFunction`.
+
+Frequently used properties `minConcurrency` and `maxConcurrency` are exempted and can still be used
+directly as `options.minConcurrency`.
diff --git a/package.json b/package.json
index 9779851ba..5a7b94d77 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "apify",
- "version": "0.7.4",
+ "version": "0.8.0",
"description": "Web scraping and automation SDK",
"engines": {
"node": ">=8.0.0"
diff --git a/src/autoscaled_pool.js b/src/autoscaled_pool.js
deleted file mode 100644
index c4206746c..000000000
--- a/src/autoscaled_pool.js
+++ /dev/null
@@ -1,482 +0,0 @@
-import Promise from 'bluebird';
-import log from 'apify-shared/log';
-import { ACTOR_EVENT_NAMES } from 'apify-shared/consts';
-import _ from 'underscore';
-import { checkParamOrThrow } from 'apify-client/build/utils';
-import { getMemoryInfo, isPromise, avg, isAtHome } from './utils';
-import events from './events';
-
-// NOTE: If this is too low, getMemoryInfo() has so much overheads that it chokes the system
-const AUTOSCALE_INTERVAL_MILLIS = 1000;
-const MIN_FREE_MEMORY_RATIO = 0.1; // Minimum amount of memory that we keep free.
-const DEFAULT_OPTIONS = {
- maxConcurrency: 1000,
- minConcurrency: 1,
- minFreeMemoryRatio: 0.2,
- maybeRunIntervalMillis: 500,
- finishWhenEmpty: true,
- ignoreMainProcess: false,
- loggingIntervalMillis: 60000,
-};
-
-// These constants defines that in Nth execution of autoscaleInterval we do:
-export const SCALE_UP_INTERVAL = 10;
-export const SCALE_UP_MAX_STEP = 10;
-export const SCALE_DOWN_INTERVAL = 1;
-
-/**
- * Helper function that coverts bytes into human readable MBs.
- *
- * @ignore
- */
-const humanReadable = bytes => `${Math.round(bytes / 1024 / 1024)} MB`;
-
-/**
- * Manages a pool of asynchronous resource-intensive tasks that are executed in parallel.
- * The pool only starts new tasks if there is enough free CPU and memory available.
- * The information about the CPU and memory usage is obtained
- * either from the local system or from the Apify cloud infrastructure in case the process
- * is running on the Apify platform.
- *
- * The auto-scaled pool is started by calling the `run()` function
- * and it finishes when the last running task gets resolved and the next call to
- * the function passed via `isFinishedFunction` resolves to `false`.
- * If any of the tasks throws then the `run()` function also throws.
- *
- * The pool evaluates whether is should start a new task every time some of the tasks is finished
- * and also in the interval set by the `options.maybeRunIntervalMillis` parameter.
- *
- * Basic usage of `AutoscaledPool`:
- *
- * ```javascript
- * const pool = new Apify.AutoscaledPool({
- * maxConcurrency: 50,
- * runTaskFunction: () => {
- * // Run some resource-intensive asynchronous operation here and return a promise...
- * },
- * });
- *
- * await pool.run();
- * ```
- *
- * @param {Object} options
- * @param {Function} [options.runTaskFunction]
- * A function that performs an asynchronous resource-intensive task.
- * The function must either return a promise or `null` if no task is currently available.
- * @param {Function} [options.isFinishedFunction]
- * A function that is called every time there are no tasks being processed.
- * If it resolves to `true` then the pool's run finishes.
- * If `isFinishedFunction` is not provided then the pool
- * is finished whenever there are no running tasks.
- * @param {Function} [options.isTaskReadyFunction]
- * A function that indicates if `runTaskFunction` should be called.
- * By default, this function is called every time there is a free capacity for new task.
- * But by overriding this you can throttle
- * number of calls to `runTaskFunction` or to prevent calls to `runTaskFunction` when you know
- * that it would return null.
- * @param {Number} [options.minConcurrency=1]
- * Minimum number of tasks running in parallel.
- * @param {Number} [options.maxConcurrency=1000]
- * Maximum number of tasks running in parallel.
- * @param {Number} [options.maxMemoryMbytes]
- * Maximum memory available in the system. By default the pool
- * uses the `totalMemory` value provided by `Apify.getMemoryInfo()`.
- * @param {Number} [options.minFreeMemoryRatio=0.2]
- * Minimum ratio of free memory kept in the system.
- * @param {Number} [options.maybeRunIntervalMillis=500]
- * Indicates how often should the pool try to call `opts.runTaskFunction` to start a new task.
- * @param {Boolean} [options.ignoreMainProcess=false]
- * If set to `true` then the auto-scaling manager does not consider memory consumption
- * of the main Node.js process when scaling the pool up or down.
- * This is mainly useful when tasks are running as separate processes (e.g. web browsers).
- * @param {Number} [options.loggingIntervalMillis=60000]
- * Specifies a period in which the instance logs it state, in milliseconds.
- * Set to `null` to disable periodic logging.
- */
-export default class AutoscaledPool {
- constructor(opts) {
- // TODO: remove this when we release v1.0.0
- // For backwards compatibility with opts.workerFunction.
- if (opts.workerFunction) {
- // For backwards compatiblity with opts.finishWhenEmpty and this.finish();
- if (opts.finishWhenEmpty !== undefined) {
- log.warning('AutoscaledPool: Parameter `finishWhenEmpty` is deprecated!!! Use `isFinishedFunction` instead!');
- checkParamOrThrow(opts.finishWhenEmpty, 'opts.finishWhenEmpty', 'Boolean');
- let mayFinish = false;
- opts.isFinishedFunction = () => Promise.resolve(mayFinish);
- this.finish = () => { mayFinish = true; };
- } else {
- opts.isFinishedFunction = () => Promise.resolve(true);
- }
-
- log.warning('AutoscaledPool: Parameter `workerFunction` is deprecated!!! Use `runTaskFunction` instead!');
- checkParamOrThrow(opts.workerFunction, 'opts.workerFunction', 'Function');
- opts.runTaskFunction = opts.workerFunction;
- opts.isTaskReadyFunction = () => Promise.resolve(true);
- }
-
- const {
- maxConcurrency,
- minConcurrency,
- maxMemoryMbytes,
- minFreeMemoryRatio,
- maybeRunIntervalMillis,
- runTaskFunction,
- isFinishedFunction,
- isTaskReadyFunction,
- ignoreMainProcess,
- loggingIntervalMillis,
- } = _.defaults(opts, DEFAULT_OPTIONS);
-
- checkParamOrThrow(maxConcurrency, 'opts.maxConcurrency', 'Number');
- checkParamOrThrow(minConcurrency, 'opts.minConcurrency', 'Number');
- checkParamOrThrow(maxMemoryMbytes, 'opts.maxMemoryMbytes', 'Maybe Number');
- checkParamOrThrow(minFreeMemoryRatio, 'opts.minFreeMemoryRatio', 'Number');
- checkParamOrThrow(maybeRunIntervalMillis, 'opts.maybeRunIntervalMillis', 'Number');
- checkParamOrThrow(runTaskFunction, 'opts.runTaskFunction', 'Function');
- checkParamOrThrow(isFinishedFunction, 'opts.isFinishedFunction', 'Maybe Function');
- checkParamOrThrow(isTaskReadyFunction, 'opts.isTaskReadyFunction', 'Maybe Function');
- checkParamOrThrow(ignoreMainProcess, 'opts.ignoreMainProcess', 'Boolean');
- checkParamOrThrow(loggingIntervalMillis, 'opts.loggingIntervalMillis', 'Maybe Number');
-
- // Configuration.
- this.maxMemoryMbytes = maxMemoryMbytes;
- this.maxConcurrency = maxConcurrency;
- this.minConcurrency = Math.min(minConcurrency, maxConcurrency);
- this.minFreeMemoryRatio = minFreeMemoryRatio;
- this.maybeRunIntervalMillis = maybeRunIntervalMillis;
- this.runTaskFunction = runTaskFunction;
- this.isFinishedFunction = isFinishedFunction;
- this.isTaskReadyFunction = isTaskReadyFunction;
- this.ignoreMainProcess = ignoreMainProcess;
- this.loggingIntervalMillis = loggingIntervalMillis;
-
- // State.
- this.intervalCounter = 0;
- this.concurrency = minConcurrency;
- this.runningCount = 0;
- this.freeBytesSnapshots = [];
- this.isCpuOverloadedSnapshots = [false];
- this.queryingIsTaskReady = false;
- this.queryingIsFinished = false;
- this.lastLoggingTime = 0;
-
- // Intervals.
- this.autoscaleInterval = null;
- this.maybeRunTaskInterval = null;
-
- // This is resolve function of Promise returned by this.run()
- // which gets resolved once everything is done.
- this.poolPromise = null;
- this.resolve = null;
- this.reject = null;
-
- // Connect to actor events for CPU info.
- // TODO: This doesn't work on local machine! use blocked() both locally and on server!!!!
- // CPU is overloaded if either blocked() or the CPU_INFO event says so
- // the CPU status sampling should be in regular intervals (e.g. once per second),
- // otherwise the auto-scaled pool cannot know what the data means
- this.cpuInfoListener = (data) => {
- this.isCpuOverloadedSnapshots = this.isCpuOverloadedSnapshots
- .concat(data.isCpuOverloaded)
- .slice(-SCALE_DOWN_INTERVAL);
- };
- events.on(ACTOR_EVENT_NAMES.CPU_INFO, this.cpuInfoListener);
- }
-
- /**
- * Runs the auto-scaled pool. Returns promise that gets resolved or rejected once
- * all the task got finished or some of them fails.
- *
- * @return {Promise}
- */
- run() {
- this.poolPromise = new Promise((resolve, reject) => {
- this.resolve = resolve;
- this.reject = reject;
- });
-
- this._maybeRunTask();
-
- // This is here because if we scale down to let's say 1, then after each promise is finished
- // this._maybeRunTask() doesn't trigger another one. So if that 1 instance gets stuck it results
- // in whole actor to get stuck and even after scaling up it never triggers another promise.
- this.maybeRunTaskInterval = setInterval(() => this._maybeRunTask(), this.maybeRunIntervalMillis);
-
- // This interval checks memory and in each call saves current memory stats and in every
- // SCALE_UP_INTERVAL-th/SCALE_DOWN_INTERVAL-th call it may scale up/down based on memory.
- if (isAtHome()) {
- this.autoscaleInterval = setInterval(() => this._autoscale(), AUTOSCALE_INTERVAL_MILLIS);
- } else {
- log.warning('Auto-scaling is currently available only when running on Apify platform! '
- + 'Use `minConcurrency` parameter if you need to test multiple requests in parallel. '
- + 'This feature will be enabled soon.');
- }
-
- return this.poolPromise
- .then(() => {
- this._destroy();
- })
- .catch((err) => {
- this._destroy();
-
- throw err;
- });
- }
-
- /**
- * Stops the auto-scaled pool, discards all currently running tasks and destroys it.
- *
- * @return {Promise}
- */
- async abort() {
- if (this.resolve) this.resolve();
- // _destroy gets called 10 lines above so no need to do it here
- }
-
- /**
- * Gets called every AUTOSCALE_INTERVAL_MILLIS and saves number of free bytes in this.freeBytesSnapshots.
- *
- * Every:
- * - SCALE_DOWN_INTERVAL-th call checks memory and possibly scales DOWN by 1.
- * - SCALE_UP_INTERVAL-th call checks memory and possibly scales UP
- * - MEM_INFO_INTERVAL-th call logs statistics about memory.
- *
- * NOTE: Parameter this.ignoreMainProcess=true solves the situation where for example we have 3GB memory,
- * node process takes 1.5GB and Chrome 500MB so autoscaling things that we 1 concurrency allocates
- * 2/3 of memory and therefore it doesn't scales up.
- *
- * Ignoring the main process we get total memory decreased to 1.5GB so AutoscaledPool considers that
- * one Chrome process to be correctly taking that 1/3 of memory.
- *
- * @ignore
- */
- _autoscale() {
- // Returning promise so that we can await it in unit tests.
- return getMemoryInfo()
- .then(({ freeBytes, totalBytes, mainProcessBytes }) => {
- if (this.ignoreMainProcess) totalBytes -= mainProcessBytes;
- if (this.maxMemoryMbytes) totalBytes = Math.min(totalBytes, this.maxMemoryMbytes);
-
- this.intervalCounter++;
- this.freeBytesSnapshots = this.freeBytesSnapshots.concat(freeBytes).slice(-SCALE_UP_INTERVAL);
-
- // On periodic intervals, print comprehensive log information
- let logData = null;
- if (this.loggingIntervalMillis > 0) {
- const now = Date.now();
- if (now > this.lastLoggingTime + this.loggingIntervalMillis) {
- this.lastLoggingTime = now;
- logData = {
- concurrency: this.concurrency,
- runningCount: this.runningCount,
- };
- }
- }
-
- const scaledDown = this._maybeScaleDown(totalBytes, logData);
- if (!scaledDown) this._maybeScaleUp(totalBytes, logData);
-
- if (logData) {
- log.info('AutoscaledPool state', logData);
- }
- })
- .catch(err => log.exception(err, 'AutoscaledPool._autoscale() function failed'));
- }
-
- /**
- * Scales pool down if there is enough memory and CPU.
- *
- * @return true if concurrency was changed
- * @ignore
- */
- _maybeScaleDown(totalBytes, logData) {
- const snapshots = this.freeBytesSnapshots.slice(-SCALE_DOWN_INTERVAL);
- const averageFreeBytes = avg(snapshots);
- const isMemoryOverloaded = averageFreeBytes / totalBytes < this.minFreeMemoryRatio;
- const isCpuOverloaded = _.all(this.isCpuOverloadedSnapshots);
-
- // Update logData even if not scaling down
- if (logData) {
- Object.assign(logData, {
- concurrency: this.concurrency,
- isMemoryOverloaded,
- isCpuOverloaded,
- });
- }
-
- if (this.intervalCounter % SCALE_DOWN_INTERVAL !== 0
- || this.concurrency <= this.minConcurrency
- || (!isCpuOverloaded && !isMemoryOverloaded)) return false;
-
- this.concurrency--;
- log.debug('AutoscaledPool: scaling down', {
- oldConcurrency: this.concurrency + 1,
- newConcurrency: this.concurrency,
- isMemoryOverloaded,
- isCpuOverloaded,
- });
-
- return true;
- }
-
- /**
- * Scales pool up if there is enough memory and CPU.
- *
- * @return true if concurrency was changed
- * @ignore
- */
- _maybeScaleUp(totalBytes, logData) {
- // Update logData even if not scaling down
- const spaceForInstances = this._computeSpaceForInstances(totalBytes, logData);
-
- if (this.intervalCounter % SCALE_UP_INTERVAL !== 0
- || this.concurrency >= this.maxConcurrency
- || spaceForInstances <= 0) return false;
-
- const increaseBy = Math.min(spaceForInstances, SCALE_UP_MAX_STEP);
- const oldConcurrency = this.concurrency;
-
- this.concurrency = Math.min(this.concurrency + increaseBy, this.maxConcurrency);
- log.debug('AutoscaledPool: scaling up', {
- oldConcurrency,
- newConcurrency: this.concurrency,
- });
-
- return true;
- }
-
- /**
- * Gets memory info and computes how much we can scale pool
- * to avoid exceeding the maximum memory.
- *
- * If shouldLogInfo = true then also logs info about memory usage.
- *
- * @ignore
- */
- _computeSpaceForInstances(totalBytes, logData) {
- const minFreeBytes = Math.min(...this.freeBytesSnapshots);
- const minFreeRatio = minFreeBytes / totalBytes;
- const maxTakenBytes = totalBytes - minFreeBytes;
- const perInstanceRatio = (maxTakenBytes / totalBytes) / this.runningCount;
- const hasSpaceForInstances = Math.floor((minFreeRatio - MIN_FREE_MEMORY_RATIO) / perInstanceRatio);
-
- if (logData) {
- Object.assign(logData, {
- freeBytesSnapshots: humanReadable(_.last(this.freeBytesSnapshots)),
- totalBytes: humanReadable(totalBytes),
- minFreeBytes: humanReadable(minFreeBytes),
- minFreePerc: minFreeRatio,
- maxTakenBytes: humanReadable(maxTakenBytes),
- perInstancePerc: perInstanceRatio,
- hasSpaceForInstances,
- });
- }
-
- return hasSpaceForInstances;
- }
-
- /**
- * If number of running task is lower than allowed concurrency and this.isTaskReadyFunction()
- * returns true then starts a new task.
- *
- * It doesn't allow multiple concurrent runs of this method.
- *
- * @ignore
- */
- _maybeRunTask(recursion = 0) {
- if (recursion >= this.concurrency) return;
- if (this.runningCount >= this.concurrency) return;
- if (this.queryingIsTaskReady) return;
-
- this.queryingIsTaskReady = true;
-
- const isTaskReadyPromise = this.isTaskReadyFunction
- ? this.isTaskReadyFunction()
- : Promise.resolve(true);
-
- // It's not null so it must be a promise!
- if (!isPromise(isTaskReadyPromise)) throw new Error('User provided isTaskReadyFunction must return a Promise.');
-
- // We don't want to chain this so don't return here!
- isTaskReadyPromise
- .catch((err) => {
- this.queryingIsTaskReady = false;
- log.exception(err, 'AutoscaledPool: isTaskReadyFunction failed');
- })
- .then((isTaskReady) => {
- this.queryingIsTaskReady = false;
-
- if (!isTaskReady) return this._maybeFinish();
-
- const taskPromise = this.runTaskFunction();
-
- // We are not done but don't want to execute new promise at this point.
- // This may happen when there are less pages in the queue than max concurrency
- // but all of them are being served already.
- if (!taskPromise) return this._maybeFinish();
-
- // It's not null so it must be a promise!
- if (!isPromise(taskPromise)) throw new Error('User provided runTaskFunction must return a Promise.');
-
- this.runningCount++;
- this._maybeRunTask(recursion + 1);
-
- return taskPromise
- .then(() => {
- this.runningCount--;
- this._maybeRunTask();
- });
- })
- .catch((err) => {
- log.exception(err, 'AutoscaledPool: runTaskFunction failed');
- this.runningCount--;
- // This is here because we might have already rejected this promise.
- if (this.reject) this.reject(err);
- });
- }
-
- /**
- * If there is no running task and this.isFinishedFunction() returns true then closes
- * the pool and resolves the pool dependency..
- *
- * It doesn't allow multiple concurrent runs of this method.
- *
- * @ignore
- */
- _maybeFinish() {
- if (this.queryingIsFinished) return;
- if (this.runningCount > 0) return;
- if (!this.isFinishedFunction) return this.resolve();
-
- this.queryingIsFinished = true;
-
- return this
- .isFinishedFunction()
- .then((isFinished) => {
- this.queryingIsFinished = false;
-
- if (!isFinished) return;
- if (this.resolve) this.resolve();
- })
- .catch((err) => {
- this.queryingIsFinished = false;
- log.exception(err, 'AutoscaledPool: isFinishedFunction failed');
- });
- }
-
- /**
- * Cleanups resources.
- *
- * @ignore
- */
- _destroy() {
- this.resolve = null;
- this.reject = null;
-
- events.removeListener(ACTOR_EVENT_NAMES.CPU_INFO, this.cpuInfoListener);
-
- clearInterval(this.autoscaleInterval);
- clearInterval(this.maybeRunTaskInterval);
- }
-}
diff --git a/src/autoscaling/autoscaled_pool.js b/src/autoscaling/autoscaled_pool.js
new file mode 100644
index 000000000..b40cb9b7f
--- /dev/null
+++ b/src/autoscaling/autoscaled_pool.js
@@ -0,0 +1,396 @@
+import _ from 'underscore';
+import { betterSetInterval, betterClearInterval } from 'apify-shared/utilities';
+import log from 'apify-shared/log';
+import { checkParamOrThrow } from 'apify-client/build/utils';
+import Snapshotter from './snapshotter';
+import SystemStatus from './system_status';
+
+const DEFAULT_OPTIONS = {
+ maxConcurrency: 1000,
+ minConcurrency: 1,
+ desiredConcurrencyRatio: 0.95,
+ scaleUpStepRatio: 0.05,
+ scaleDownStepRatio: 0.05,
+ maybeRunIntervalSecs: 0.5,
+ loggingIntervalSecs: 60,
+ autoscaleIntervalSecs: 10,
+};
+
+/**
+ * Manages a pool of asynchronous resource-intensive tasks that are executed in parallel.
+ * The pool only starts new tasks if there is enough free CPU and memory available
+ * and the Javascript event loop is not blocked.
+ *
+ * The information about the CPU and memory usage is obtained by the `Snapshotter` class,
+ * which makes regular snapshots of system resources that may be either local
+ * or from the Apify cloud infrastructure in case the process is running on the Apify platform.
+ * Meaningful data gathered from these snapshots is provided to `AutoscaledPool` by the `SystemStatus` class.
+ *
+ * Before running the pool, one must implement three functions. `runTaskFunction()`,
+ * `isTaskReadyFunction()` and `isFinishedFunction()`.
+ *
+ * The auto-scaled pool is started by calling the `run()` function. It queries the `isTaskReadyFunction()`
+ * for more tasks, managing optimal concurrency, until the function resolves to `false`. The pool then queries
+ * the `isFinishedFunction()`. If it resolves to `true`, the pool finishes. If it resolves to `false`, it assumes
+ * there will be more tasks available later and keeps querying for tasks, until finally both the
+ * `isTaskReadyFunction()` and `isFinishedFunction()` resolve to `true`. If any of the tasks throws
+ * then the `run()` function also throws.
+ *
+ * The pool evaluates whether it should start a new task every time one of the tasks finishes
+ * and also in the interval set by the `options.maybeRunIntervalSecs` parameter.
+ *
+ * Basic usage of `AutoscaledPool`:
+ *
+ * ```javascript
+ * const pool = new Apify.AutoscaledPool({
+ * maxConcurrency: 50,
+ * runTaskFunction: async () => {
+ * // Run some resource-intensive asynchronous operation here.
+ * },
+ * isTaskReadyFunction: async () => {
+ * // Tell the pool whether more tasks are ready to be processed. (true / false)
+ * },
+ * isFinishedFunction: async () => {
+ * // Tell the pool whether it should finish or wait for more tasks to become available. (true / false)
+ * }
+ * });
+ *
+ * await pool.run();
+ * ```
+ *
+ * @param {Object} options
+ * @param {Function} options.runTaskFunction
+ * A function that performs an asynchronous resource-intensive task.
+ * The function must either be labeled `async` or return a promise.
+ *
+ * @param {Function} options.isTaskReadyFunction
+ * A function that indicates whether `runTaskFunction` should be called.
+ * This function is called every time there is free capacity for a new task and it should
+ * indicate whether it should start or not by resolving to either `true` or `false.
+ * Besides its obvious use, it is also useful for task throttling to save resources.
+ *
+ * @param {Function} options.isFinishedFunction
+ * A function that is called only when there are no tasks to be processed.
+ * If it resolves to `true` then the pool's run finishes. Being called only
+ * when there are no tasks being processed means that as long as `isTaskReadyFunction()`
+ * keeps resolving to `true`, `isFinishedFunction()` will never be called.
+ * To abort a run, use the `pool.abort()` method.
+ *
+ * @param {Number} [options.minConcurrency=1]
+ * Minimum number of tasks running in parallel.
+ * @param {Number} [options.maxConcurrency=1000]
+ * Maximum number of tasks running in parallel.
+ * @param {Number} [options.desiredConcurrencyRatio=0.95]
+ * Minimum level of desired concurrency to reach before more scaling up is allowed.
+ * @param {Number} [options.scaleUpStepRatio=0.05]
+ * Defines the fractional amount of desired concurrency to be added with each scaling up.
+ * The minimum scaling step is one.
+ * @param {Number} [options.scaleDownStepRatio=0.05]
+ * Defines the amount of desired concurrency to be subtracted with each scaling down.
+ * The minimum scaling step is one.
+ * @param {Number} [options.maybeRunIntervalSecs=0.5]
+ * Indicates how often should the pool call the `runTaskFunction()` to start a new task, in seconds.
+ * This has no effect on starting new tasks immediately after a task completes.
+ * @param {Number} [options.loggingIntervalSecs=60]
+ * Specifies a period in which the instance logs it state, in seconds.
+ * Set to `null` to disable periodic logging.
+ * @param {Number} [options.autoscaleIntervalSecs=10]
+ * Defines in seconds how often should the pool attempt to adjust the desired concurrency
+ * based on the latest system status. Setting it lower than 1 might have a severe impact on performance.
+ * We suggest using a value from 5 to 20.
+ * @param {Number} [options.snapshotterOptions]
+ * Options to be passed down to the `Snapshotter` constructor. This is useful for fine-tuning
+ * the snapshot intervals and history. See the <a href="#Snapshotter">Snapshotter documentation</a>
+ * for available options.
+ * @param {Number} [options.systemStatusOptions]
+ * Options to be passed down to the `SystemStatus` constructor. This is useful for fine-tuning
+ * the system status reports. See the <a href="#SystemStatus">SystemStatus documentation</a>
+ * for available options. If a custom snapshotter is set in the options, it will be used
+ * by the pool.
+ */
+export default class AutoscaledPool {
+ constructor(options = {}) {
+ const {
+ maxConcurrency,
+ minConcurrency,
+ desiredConcurrencyRatio,
+ scaleUpStepRatio,
+ scaleDownStepRatio,
+ maybeRunIntervalSecs,
+ loggingIntervalSecs,
+ autoscaleIntervalSecs,
+ runTaskFunction,
+ isFinishedFunction,
+ isTaskReadyFunction,
+ systemStatusOptions,
+ snapshotterOptions,
+ } = _.defaults(options, DEFAULT_OPTIONS);
+
+ checkParamOrThrow(maxConcurrency, 'options.maxConcurrency', 'Number');
+ checkParamOrThrow(minConcurrency, 'options.minConcurrency', 'Number');
+ checkParamOrThrow(desiredConcurrencyRatio, 'options.desiredConcurrencyRatio', 'Number');
+ checkParamOrThrow(scaleUpStepRatio, 'options.scaleUpStepRatio', 'Number');
+ checkParamOrThrow(scaleDownStepRatio, 'options.scaleDownStepRatio', 'Number');
+ checkParamOrThrow(maybeRunIntervalSecs, 'options.maybeRunIntervalSecs', 'Number');
+ checkParamOrThrow(loggingIntervalSecs, 'options.loggingIntervalSecs', 'Number');
+ checkParamOrThrow(autoscaleIntervalSecs, 'options.autoscaleIntervalSecs', 'Number');
+ checkParamOrThrow(runTaskFunction, 'options.runTaskFunction', 'Function');
+ checkParamOrThrow(isFinishedFunction, 'options.isFinishedFunction', 'Function');
+ checkParamOrThrow(isTaskReadyFunction, 'options.isTaskReadyFunction', 'Function');
+ checkParamOrThrow(systemStatusOptions, 'options.systemStatusOptions', 'Maybe Object');
+ checkParamOrThrow(snapshotterOptions, 'options.snapshotterOptions', 'Maybe Object');
+
+ // Configurable properties.
+ this.maxConcurrency = maxConcurrency;
+ this.minConcurrency = minConcurrency;
+ this.desiredConcurrencyRatio = desiredConcurrencyRatio;
+ this.scaleUpStepRatio = scaleUpStepRatio;
+ this.scaleDownStepRatio = scaleDownStepRatio;
+ this.maybeRunIntervalMillis = maybeRunIntervalSecs * 1000;
+ this.loggingIntervalMillis = loggingIntervalSecs * 1000;
+ this.autoscaleIntervalMillis = autoscaleIntervalSecs * 1000;
+ this.runTaskFunction = runTaskFunction;
+ this.isFinishedFunction = isFinishedFunction;
+ this.isTaskReadyFunction = isTaskReadyFunction;
+
+ // Internal properties.
+ this.desiredConcurrency = this.minConcurrency;
+ this.currentConcurrency = 0;
+ this.lastLoggingTime = 0;
+ this.resolve = null;
+ this.reject = null;
+ this._autoscale = this._autoscale.bind(this);
+ this._maybeRunTask = this._maybeRunTask.bind(this);
+
+ // Create instances with correct options.
+ const ssoCopy = Object.assign({}, systemStatusOptions);
+ if (!ssoCopy.snapshotter) ssoCopy.snapshotter = new Snapshotter(snapshotterOptions);
+ this.snapshotter = ssoCopy.snapshotter;
+ this.systemStatus = new SystemStatus(ssoCopy);
+ }
+
+ /**
+ * Runs the auto-scaled pool. Returns a promise that gets resolved or rejected once
+ * all the tasks are finished or one of them fails.
+ *
+ * @return {Promise}
+ */
+ async run() {
+ this.poolPromise = new Promise((resolve, reject) => {
+ this.resolve = resolve;
+ this.reject = reject;
+ });
+
+ await this.snapshotter.start();
+
+ // This interval checks the system status and updates the desired concurrency accordingly.
+ this.autoscaleInterval = betterSetInterval(this._autoscale, this.autoscaleIntervalMillis);
+
+ // This is here because if we scale down to let's say 1, then after each promise is finished
+ // this._maybeRunTask() doesn't trigger another one. So if that 1 instance gets stuck it results
+ // in the actor getting stuck and even after scaling up it never triggers another promise.
+ this.maybeRunInterval = betterSetInterval(this._maybeRunTask, this.maybeRunIntervalMillis);
+
+ try {
+ await this.poolPromise;
+ } finally {
+ // If resolve is null, the pool is already destroyed.
+ if (this.resolve) await this._destroy();
+ }
+ }
+
+ /**
+ * Aborts the run of the auto-scaled pool, discards all currently running tasks and destroys it.
+ *
+ * @return {Promise}
+ */
+ async abort() {
+ if (this.resolve) {
+ this.resolve();
+ await this._destroy();
+ }
+ }
+
+ /**
+ * Starts a new task
+ * if the number of running tasks (current concurrency) is lower than desired concurrency
+ * and the system is not currently overloaded
+ * and this.isTaskReadyFunction() returns true.
+ *
+ * It doesn't allow multiple concurrent runs of this method.
+ *
+ * @ignore
+ */
+ async _maybeRunTask(intervalCallback) {
+ // Check if the function was invoked by the maybeRunInterval and use an empty function if not.
+ const done = intervalCallback || (() => {});
+
+ // Only run task if:
+ // - we're not already querying for a task
+ if (this.queryingIsTaskReady) return done();
+ // - we will not exceed desired concurrency.
+ if (this.currentConcurrency >= this.desiredConcurrency) return done();
+ // - system is not overloaded now
+ const currentStatus = this.systemStatus.getCurrentStatus();
+ const { isSystemIdle } = currentStatus;
+ if (!isSystemIdle) {
+ log.debug('AutoscaledPool: Task will not be run. System is overloaded.', currentStatus);
+ return done();
+ }
+ // - a task is ready.
+ this.queryingIsTaskReady = true;
+ let isTaskReady;
+ try {
+ isTaskReady = await this.isTaskReadyFunction();
+ } catch (err) {
+ log.exception(err, 'AutoscaledPool: isTaskReadyFunction failed');
+ } finally {
+ this.queryingIsTaskReady = false;
+ }
+ if (!isTaskReady) {
+ done();
+ // No tasks could mean that we're finished with all tasks.
+ return this._maybeFinish();
+ }
+
+ try {
+ // Everything's fine. Run task.
+ this.currentConcurrency++;
+ // Try to run next task to build up concurrency,
+ // but defer it so it doesn't create a cycle.
+ setImmediate(this._maybeRunTask);
+
+ // We need to restart interval here, so that it doesn't get blocked by a stalled task.
+ done();
+
+ // Execute the current task.
+ await this.runTaskFunction();
+ this.currentConcurrency--;
+ // Run task after the previous one finished.
+ setImmediate(this._maybeRunTask);
+ } catch (err) {
+ // We might have already rejected this promise.
+ if (this.reject) {
+ this.reject(err);
+ // No need to log all concurrent errors.
+ log.exception(err, 'AutoscaledPool: runTaskFunction failed');
+ }
+ }
+ }
+
+ /**
+ * Gets called every autoScaleIntervalSecs and evaluates the current system status.
+ * If the system IS NOT overloaded and the settings allow it, it scales up.
+ * If the system IS overloaded and the settings allow it, it scales down.
+ *
+ * @ignore
+ */
+ _autoscale(intervalCallback) {
+ // Only scale up if:
+ // - system has not been overloaded lately.
+ const systemStatus = this.systemStatus.getHistoricalStatus();
+ const { isSystemIdle } = systemStatus;
+ // - we're not already at max concurrency.
+ const weAreNotAtMax = this.desiredConcurrency < this.maxConcurrency;
+ // - current concurrency reaches at least the given ratio of desired concurrency.
+ const minCurrentConcurrency = Math.floor(this.desiredConcurrency * this.desiredConcurrencyRatio);
+ const weAreReachingDesiredConcurrency = this.currentConcurrency >= minCurrentConcurrency;
+
+ if (isSystemIdle && weAreNotAtMax && weAreReachingDesiredConcurrency) this._scaleUp(systemStatus);
+
+ // Always scale down if:
+ // - the system has been overloaded lately.
+ const isSystemOverloaded = !isSystemIdle;
+ // - we're over min concurrency.
+ const weAreNotAtMin = this.desiredConcurrency > this.minConcurrency;
+
+ if (isSystemOverloaded && weAreNotAtMin) this._scaleDown(systemStatus);
+
+ // On periodic intervals, print comprehensive log information
+ if (this.loggingIntervalMillis > 0) {
+ const now = Date.now();
+ if (now > this.lastLoggingTime + this.loggingIntervalMillis) {
+ this.lastLoggingTime = now;
+ log.info('AutoscaledPool state', {
+ currentConcurrency: this.currentConcurrency,
+ desiredConcurrency: this.desiredConcurrency,
+ systemStatus,
+ });
+ }
+ }
+
+ // Start a new interval cycle.
+ intervalCallback();
+ }
+
+ /**
+ * Scales the pool up by increasing
+ * the desired concurrency by the scaleUpStepRatio.
+ *
+ * @param {Object} systemStatus for logging
+ * @ignore
+ */
+ _scaleUp(systemStatus) {
+ const step = Math.ceil(this.desiredConcurrency * this.scaleUpStepRatio);
+ this.desiredConcurrency = Math.min(this.maxConcurrency, this.desiredConcurrency + step);
+ log.debug('AutoscaledPool: scaling up', {
+ oldConcurrency: this.desiredConcurrency - step,
+ newConcurrency: this.desiredConcurrency,
+ systemStatus,
+ });
+ }
+
+ /**
+ * Scales the pool down by decreasing
+ * the desired concurrency by the scaleDownStepRatio.
+ *
+ * @param {Object} systemStatus for logging
+ * @ignore
+ */
+ _scaleDown(systemStatus) {
+ const step = Math.ceil(this.desiredConcurrency * this.scaleUpStepRatio);
+ this.desiredConcurrency = Math.max(this.minConcurrency, this.desiredConcurrency - step);
+ log.debug('AutoscaledPool: scaling down', {
+ oldConcurrency: this.desiredConcurrency + step,
+ newConcurrency: this.desiredConcurrency,
+ systemStatus,
+ });
+ }
+
+ /**
+ * If there are no running tasks and this.isFinishedFunction() returns true then closes
+ * the pool and resolves the pool's promise returned by the run() method.
+ *
+ * It doesn't allow multiple concurrent runs of this method.
+ *
+ * @ignore
+ */
+ async _maybeFinish() {
+ if (this.queryingIsFinished) return;
+ if (this.runningCount > 0) return;
+
+ this.queryingIsFinished = true;
+ try {
+ const isFinished = await this.isFinishedFunction();
+ if (isFinished && this.resolve) this.resolve();
+ } catch (err) {
+ log.exception(err, 'AutoscaledPool: isFinishedFunction failed');
+ } finally {
+ this.queryingIsFinished = false;
+ }
+ }
+
+ /**
+ * Cleans up resources.
+ *
+ * @ignore
+ */
+ async _destroy() {
+ this.resolve = null;
+ this.reject = null;
+
+ betterClearInterval(this.autoscaleInterval);
+ betterClearInterval(this.maybeRunInterval);
+ if (this.snapshotter) await this.snapshotter.stop();
+ }
+}
diff --git a/src/autoscaling/snapshotter.js b/src/autoscaling/snapshotter.js
new file mode 100644
index 000000000..c4daafb9b
--- /dev/null
+++ b/src/autoscaling/snapshotter.js
@@ -0,0 +1,269 @@
+import _ from 'underscore';
+import { betterSetInterval, betterClearInterval } from 'apify-shared/utilities';
+import log from 'apify-shared/log';
+import { ACTOR_EVENT_NAMES } from 'apify-shared/consts';
+import { checkParamOrThrow } from 'apify-client/build/utils';
+import { getMemoryInfo, isAtHome } from '../utils';
+import events from '../events';
+
+const DEFAULT_OPTIONS = {
+ eventLoopSnapshotIntervalSecs: 0.5,
+ maxBlockedMillis: 50,
+ memorySnapshotIntervalSecs: 1,
+ maxUsedMemoryRatio: 0.7,
+ snapshotHistorySecs: 60,
+};
+
+/**
+ * Creates snapshots of system resources at given intervals and marks the resource
+ * as either overloaded or not during the last interval. Keeps a history of the snapshots.
+ * It tracks the following resources: Memory, EventLoop and CPU.
+ *
+ * There are differences in behavior when running locally and on the Apify platform,
+ * but those differences are handled internally by the class and do not affect its interface.
+ *
+ * Memory becomes overloaded if its current use exceeds the `minFreeMemoryRatio` option.
+ * It's computed using the total memory available to the container when running on
+ * the Apify platform and a quarter of total system memory when running locally.
+ * Use of total memory may be overridden by using the `maxBlockedRatio` option.
+ *
+ * Event Loop becomes overloaded if it slows down by more than the `maxBlockedMillis` option.
+ *
+ * CPU tracking is available only on the Apify platform and the CPU overloaded event is read
+ * directly off the container and is not configurable.
+ *
+ * @param {Object} options
+ * @param {Number} [options.eventLoopSnapshotIntervalSecs=0.5]
+ * Defines the interval of measuring the event loop response time.
+ * @param {Number} [options.maxBlockedMillis=50]
+ * Maximum allowed delay of the event loop in milliseconds.
+ * Exceeding this limit overloads the event loop.
+ * @param {Number} [options.memorySnapshotIntervalSecs=1]
+ * Defines the interval of measuring memory consumption.
+ * The measurement itself is resource intensive (25 - 50ms async),
+ * therefore, setting this interval below 1 second is not recommended.
+ * @param {Number} [options.maxUsedMemoryRatio=0.7]
+ * Defines the maximum ratio of memory that can be used.
+ * Exceeding this limit overloads the memory.
+ * @param {Number} [options.snapshotHistorySecs=60]
+ * Sets the interval in seconds for which a history of resource snapshots
+ * will be kept. Increasing this to very high numbers will affect performance.
+ * @param {Number} [options.maxMemoryMbytes]
+ * Sets the maximum amount of memory to be used in megabytes.
+ * @ignore
+ */
+export default class Snapshotter {
+ constructor(options = {}) {
+ const {
+ eventLoopSnapshotIntervalSecs,
+ memorySnapshotIntervalSecs,
+ snapshotHistorySecs,
+ maxBlockedMillis,
+ maxUsedMemoryRatio,
+ maxMemoryMbytes,
+ } = _.defaults(options, DEFAULT_OPTIONS);
+
+ checkParamOrThrow(eventLoopSnapshotIntervalSecs, 'options.eventLoopSnapshotIntervalSecs', 'Number');
+ checkParamOrThrow(memorySnapshotIntervalSecs, 'options.memorySnapshotIntervalSecs', 'Number');
+ checkParamOrThrow(snapshotHistorySecs, 'options.snapshotHistorySecs', 'Number');
+ checkParamOrThrow(maxBlockedMillis, 'options.maxBlockedMillis', 'Number');
+ checkParamOrThrow(maxUsedMemoryRatio, 'options.maxUsedMemoryRatio', 'Number');
+ checkParamOrThrow(maxMemoryMbytes, 'options.maxMemoryMbytes', 'Maybe Number');
+
+ this.eventLoopSnapshotIntervalMillis = eventLoopSnapshotIntervalSecs * 1000;
+ this.memorySnapshotIntervalMillis = memorySnapshotIntervalSecs * 1000;
+ this.snapshotHistoryMillis = snapshotHistorySecs * 1000;
+ this.maxBlockedMillis = maxBlockedMillis;
+ this.maxUsedMemoryRatio = maxUsedMemoryRatio;
+ this.maxMemoryBytes = maxMemoryMbytes ? maxMemoryMbytes * 1024 * 1024 : null;
+
+ this.cpuSnapshots = [];
+ this.eventLoopSnapshots = [];
+ this.memorySnapshots = [];
+ }
+
+ /**
+ * Starts capturing snapshots in configured intervals.
+ * @return {Promise}
+ * @ignore
+ */
+ async start() {
+ // Ensure max memory is correctly computed.
+ if (!this.maxMemoryBytes) {
+ const { totalBytes } = await getMemoryInfo();
+ if (isAtHome()) {
+ this.maxMemoryBytes = totalBytes;
+ } else {
+ this.maxMemoryBytes = Math.ceil(totalBytes / 4);
+ log.info(`Snapshotter: Setting max memory of this run to ${Math.round(this.maxMemoryBytes / 1024 / 1024)} MB.`);
+ }
+ }
+ // Add dummy snapshot to compare the first with.
+ this.eventLoopSnapshots.push({
+ createdAt: new Date(),
+ isOverloaded: false,
+ exceededMillis: 0,
+ });
+
+ // Start snapshotting.
+ this.eventLoopInterval = betterSetInterval(this._snapshotEventLoop.bind(this), this.eventLoopSnapshotIntervalMillis);
+ this.memoryInterval = betterSetInterval(this._snapshotMemory.bind(this), this.memorySnapshotIntervalMillis);
+ events.on(ACTOR_EVENT_NAMES.CPU_INFO, this._snapshotCpu.bind(this));
+ }
+
+ /**
+ * Stops all resource capturing.
+ * @return {Promise}
+ * @ignore
+ */
+ async stop() {
+ betterClearInterval(this.eventLoopInterval);
+ betterClearInterval(this.memoryInterval);
+ events.removeListener(ACTOR_EVENT_NAMES.CPU_INFO, this._snapshotCpu);
+ // Allow microtask queue to unwind before stop returns.
+ await new Promise(resolve => setImmediate(resolve));
+ }
+
+ /**
+ * Returns a sample of latest memory snapshots, with the size of the sample defined
+ * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.
+ * @param {Number} [sampleDurationMillis]
+ * @return {Array} sample
+ * @ignore
+ */
+ getMemorySample(sampleDurationMillis) {
+ return this._getSample(this.memorySnapshots, sampleDurationMillis);
+ }
+
+ /**
+ * Returns a sample of latest event loop snapshots, with the size of the sample defined
+ * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.
+ * @param {Number} [sampleDurationMillis]
+ * @return {Array} sample
+ * @ignore
+ */
+ getEventLoopSample(sampleDurationMillis) {
+ return this._getSample(this.eventLoopSnapshots, sampleDurationMillis);
+ }
+
+ /**
+ * Returns a sample of latest CPU snapshots, with the size of the sample defined
+ * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.
+ * @param {Number} [sampleDurationMillis]
+ * @return {Array} sample
+ * @ignore
+ */
+ getCpuSample(sampleDurationMillis) {
+ return this._getSample(this.cpuSnapshots, sampleDurationMillis);
+ }
+
+ /**
+ * Finds the latest snapshots by sampleDurationMillis in the provided array.
+ * @param {Array} snapshots
+ * @param {Number} [sampleDurationMillis]
+ * @return {Array} sample
+ * @ignore
+ */
+ _getSample(snapshots, sampleDurationMillis) { // eslint-disable-line class-methods-use-this
+ if (!sampleDurationMillis) return snapshots;
+
+ const sample = [];
+ let idx = snapshots.length;
+ if (!idx) return sample;
+
+ const latestTime = snapshots[idx - 1].createdAt;
+ while (idx--) {
+ const snapshot = snapshots[idx];
+ if (latestTime - snapshot.createdAt <= sampleDurationMillis) sample.unshift(snapshot);
+ else break;
+ }
+ return sample;
+ }
+
+ /**
+ * Creates a snapshot of current memory usage.
+ * @param {Function} intervalCallback
+ * @return {Promise}
+ * @ignore
+ */
+ async _snapshotMemory(intervalCallback) {
+ try {
+ const now = new Date();
+ const memInfo = await getMemoryInfo();
+ const { mainProcessBytes, childProcessesBytes } = memInfo;
+ this._pruneSnapshots(this.memorySnapshots, now);
+
+ const usedBytes = mainProcessBytes + childProcessesBytes;
+ const snapshot = Object.assign(memInfo, {
+ createdAt: now,
+ isOverloaded: usedBytes / this.maxMemoryBytes > this.maxUsedMemoryRatio,
+ });
+
+ this.memorySnapshots.push(snapshot);
+ } catch (err) {
+ log.exception(err, 'Snapshotter: Memory snapshot failed.');
+ } finally {
+ intervalCallback();
+ }
+ }
+
+ /**
+ * Creates a snapshot of current event loop delay.
+ * @param {Function} intervalCallback
+ * @return {Promise}
+ * @ignore
+ */
+ _snapshotEventLoop(intervalCallback) {
+ try {
+ const now = new Date();
+ this._pruneSnapshots(this.eventLoopSnapshots, now);
+ const { createdAt } = this.eventLoopSnapshots[this.eventLoopSnapshots.length - 1];
+ const delta = now - createdAt - this.eventLoopSnapshotIntervalMillis;
+
+ const snapshot = {
+ createdAt: now,
+ isOverloaded: false,
+ exceededMillis: Math.max(delta - this.maxBlockedMillis, 0),
+ };
+
+ if (delta > this.maxBlockedMillis) snapshot.isOverloaded = true;
+ this.eventLoopSnapshots.push(snapshot);
+ } catch (err) {
+ log.exception(err, 'Snapshotter: Event Loop snapshot failed.');
+ } finally {
+ intervalCallback();
+ }
+ }
+
+ /**
+ * Creates a snapshot of current CPU usage.
+ * @param {Object} cpuInfoEvent
+ * @return {Promise}
+ * @ignore
+ */
+ _snapshotCpu(cpuInfoEvent) {
+ const createdAt = (new Date(cpuInfoEvent.createdAt));
+ this._pruneSnapshots(this.cpuSnapshots, createdAt);
+ this.cpuSnapshots.push({
+ createdAt,
+ isOverloaded: cpuInfoEvent.isCpuOverloaded,
+ });
+ }
+
+ /**
+ * Removes snapshots that are older than the snapshotHistorySecs option
+ * from the array (destructively - in place).
+ * @param {Array} snapshots
+ * @param {Date} now
+ * @ignore
+ */
+ _pruneSnapshots(snapshots, now) {
+ let oldCount = 0;
+ for (let i = 0; i < snapshots.length; i++) {
+ const { createdAt } = snapshots[i];
+ if (now - createdAt > this.snapshotHistoryMillis) oldCount++;
+ else break;
+ }
+ snapshots.splice(0, oldCount);
+ }
+}
diff --git a/src/autoscaling/system_status.js b/src/autoscaling/system_status.js
new file mode 100644
index 000000000..12ddc2390
--- /dev/null
+++ b/src/autoscaling/system_status.js
@@ -0,0 +1,173 @@
+import _ from 'underscore';
+import { checkParamOrThrow } from 'apify-client/build/utils';
+import Snapshotter from './snapshotter';
+import { weightedAvg } from '../utils';
+
+const DEFAULT_OPTIONS = {
+ currentHistorySecs: 5, // TODO this should be something like "nowDurationSecs" but it's weird, ideas?
+ maxMemoryOverloadedRatio: 0.2,
+ maxEventLoopOverloadedRatio: 0.02,
+ maxCpuOverloadedRatio: 0.1,
+};
+
+/**
+ * Provides a simple interface to reading system status from a Snapshotter
+ * instance. It only exposes two functions `isOk()` and `hasBeenOkLately()`.
+ * The system status is calculated using a weighted average of overloaded
+ * messages in the snapshots, with the weights being the time intervals
+ * between the snapshots. Each resource is calculated separately
+ * and the system is overloaded whenever at least one resource is overloaded.
+ *
+ * `getCurrentStatus()` returns a boolean that represents the current status of the system.
+ * The length of the current timeframe in seconds is configurable
+ * by the currentHistorySecs option and represents the max age
+ * of snapshots to be considered for the calculation.
+ *
+ * `getHistoricalStatus()` returns a boolean that represents the long term status
+ * of the system. It considers the full snapshot history available
+ * in the Snapshotter instance.
+ *
+ * @param {Object} options
+ * @param {Number} [options.currentHistorySecs=5]
+ * Defines max age of snapshots used in the `isOk()` measurement.
+ * @param {Number} [options.maxMemoryOverloadedRatio=0.2]
+ * Sets the maximum ratio of overloaded snapshots in a memory sample.
+ * If the sample exceeds this ratio, the system will be overloaded.
+ * @param {Number} [options.maxEventLoopOverloadedRatio=0.02]
+ * Sets the maximum ratio of overloaded snapshots in an event loop sample.
+ * If the sample exceeds this ratio, the system will be overloaded.
+ * @param {Number} [options.maxCpuOverloadedRatio=0.1]
+ * Sets the maximum ratio of overloaded snapshots in a CPU sample.
+ * If the sample exceeds this ratio, the system will be overloaded.
+ * @ignore
+ */
+export default class SystemStatus {
+ constructor(options = {}) {
+ const {
+ currentHistorySecs,
+ maxMemoryOverloadedRatio,
+ maxEventLoopOverloadedRatio,
+ maxCpuOverloadedRatio,
+ snapshotter,
+ } = _.defaults(options, DEFAULT_OPTIONS);
+
+ checkParamOrThrow(currentHistorySecs, 'options.currentHistorySecs', 'Number');
+ checkParamOrThrow(maxMemoryOverloadedRatio, 'options.maxMemoryOverloadedRatio', 'Number');
+ checkParamOrThrow(maxEventLoopOverloadedRatio, 'options.maxEventLoopOverloadedRatio', 'Number');
+ checkParamOrThrow(maxCpuOverloadedRatio, 'options.maxCpuOverloadedRatio', 'Number');
+ checkParamOrThrow(snapshotter, 'options.snapshotter', 'Maybe Object');
+
+ this.currentHistorySecs = currentHistorySecs * 1000;
+ this.maxMemoryOverloadedRatio = maxMemoryOverloadedRatio;
+ this.maxEventLoopOverloadedRatio = maxEventLoopOverloadedRatio;
+ this.maxCpuOverloadedRatio = maxCpuOverloadedRatio;
+
+ this.snapshotter = snapshotter || new Snapshotter();
+ }
+
+ /**
+ * Returns true if the system has not been overloaded in the last
+ * currentHistorySecs seconds, otherwise returns false.
+ * @return {boolean}
+ * @ignore
+ */
+ getCurrentStatus() {
+ return this._isSystemIdle(this.currentHistorySecs);
+ }
+
+ /**
+ * Returns true if the system has not been overloaded in the full
+ * history of the snapshotter (which is configurable in the snapshotter).
+ * @return {boolean}
+ * @ignore
+ */
+ getHistoricalStatus() {
+ return this._isSystemIdle();
+ }
+
+ /**
+ * Returns true if the system has been overloaded
+ * in the last sampleDurationMillis.
+ *
+ * @param {Number} [sampleDurationMillis]
+ * @return {boolean}
+ * @ignore
+ */
+ _isSystemIdle(sampleDurationMillis) {
+ const memInfo = this._isMemoryOverloaded(sampleDurationMillis);
+ const eventLoopInfo = this._isEventLoopOverloaded(sampleDurationMillis);
+ const cpuInfo = this._isCpuOverloaded(sampleDurationMillis);
+ return {
+ isSystemIdle: !memInfo.isOverloaded && !eventLoopInfo.isOverloaded && !cpuInfo.isOverloaded,
+ memInfo,
+ eventLoopInfo,
+ cpuInfo,
+ };
+ }
+
+ /**
+ * Returns true if the memory has been overloaded
+ * in the last sampleDurationMillis.
+ *
+ * @param {Number} sampleDurationMillis
+ * @return {Object}
+ * @ignore
+ */
+ _isMemoryOverloaded(sampleDurationMillis) {
+ const sample = this.snapshotter.getMemorySample(sampleDurationMillis);
+ return this._isSampleOverloaded(sample, this.maxMemoryOverloadedRatio);
+ }
+
+ /**
+ * Returns true if the event loop has been overloaded
+ * in the last sampleDurationMillis.
+ *
+ * @param {Number} sampleDurationMillis
+ * @return {Object}
+ * @ignore
+ */
+ _isEventLoopOverloaded(sampleDurationMillis) {
+ const sample = this.snapshotter.getEventLoopSample(sampleDurationMillis);
+ return this._isSampleOverloaded(sample, this.maxEventLoopOverloadedRatio);
+ }
+
+ /**
+ * Returns an object with an isOverloaded property set to true
+ * if the CPU has been overloaded in the last sampleDurationMillis.
+ *
+ * @param {Number} sampleDurationMillis
+ * @return {Object}
+ * @ignore
+ */
+ _isCpuOverloaded(sampleDurationMillis) {
+ const sample = this.snapshotter.getCpuSample(sampleDurationMillis);
+ return this._isSampleOverloaded(sample, this.maxCpuOverloadedRatio);
+ }
+
+ /**
+ * Returns an object with sample information and an isOverloaded property
+ * set to true if at least the ratio of snapshots in the sample are overloaded.
+ *
+ * @param {Array} sample
+ * @param {Number} ratio
+ * @return {Object}
+ * @ignore
+ */
+ _isSampleOverloaded(sample, ratio) { // eslint-disable-line class-methods-use-this
+ const weights = [];
+ const values = [];
+ for (let i = 1; i < sample.length; i++) {
+ const previous = sample[i - 1];
+ const current = sample[i];
+ const weight = current.createdAt - previous.createdAt;
+ weights.push(weight || 1); // Prevent errors from 0ms long intervals (sync) between snapshots.
+ values.push(Number(current.isOverloaded));
+ }
+ const wAvg = weightedAvg(values, weights);
+ return {
+ isOverloaded: wAvg > ratio,
+ maxOverloadedRatio: ratio,
+ actualRatio: wAvg,
+ };
+ }
+}
diff --git a/src/basic_crawler.js b/src/basic_crawler.js
index ee96a9bc5..5ee684a11 100644
--- a/src/basic_crawler.js
+++ b/src/basic_crawler.js
@@ -2,7 +2,7 @@ import { checkParamOrThrow } from 'apify-client/build/utils';
import _ from 'underscore';
import log from 'apify-shared/log';
import { checkParamPrototypeOrThrow } from 'apify-shared/utilities';
-import AutoscaledPool from './autoscaled_pool';
+import AutoscaledPool from './autoscaling/autoscaled_pool';
import RequestList from './request_list';
import { RequestQueue, RequestQueueLocal } from './request_queue';
@@ -12,6 +12,7 @@ const DEFAULT_OPTIONS = {
const details = _.pick(request, 'id', 'url', 'method', 'uniqueKey');
log.error('BasicCrawler: Request failed and reached maximum retries', details);
},
+ autoscaledPoolOptions: {},
};
/**
@@ -21,8 +22,10 @@ const DEFAULT_OPTIONS = {
*
* `BasicCrawler` invokes `handleRequestFunction` for each `Request` object fetched from `options.requestList` or `options.requestQueue`,
* as long as any of them is not empty. New requests are only handled if there is enough free CPU and memory available,
- * using the functionality provided by the `AutoscaledPool` class.
- * Note that all `AutoscaledPool` configuration options can be passed to `options` parameter of the `BasicCrawler` constructor.
+ * using the functionality provided by the `AutoscaledPool` class. See <a href="#AutoscaledPool">AutoscaledPool documentation</a>.
+ *
+ * All `AutoscaledPool` configuration options can be passed to the `autoscaledPoolOptions` parameter
+ * of the `CheerioCrawler` constructor. The `minConcurrency` and `maxConcurrency` options are available directly.
*
* If both `requestList` and `requestQueue` is used, the instance first
* processes URLs from the `requestList` and automatically enqueues all of them to `requestQueue` before it starts
@@ -59,46 +62,30 @@ const DEFAULT_OPTIONS = {
* ```
*
* @param {Object} options
+ * @param {Function} options.handleRequestFunction
+ * Function that processes a single `Request` object. It must return a promise.
+ *
* @param {RequestList} [options.requestList]
* Static list of URLs to be processed.
* @param {RequestQueue} [options.requestQueue]
* Dynamic queue of URLs to be processed. This is useful for recursive crawling of websites.
- * @param {Function} [options.handleRequestFunction]
- * Function that processes a single `Request` object. It must return a promise.
- * @param {Function} [options.handleFailedRequestFunction=({ request }) => {
- * const details = _.pick(request, 'id', 'url', 'method', 'uniqueKey');
- * log.error('BasicCrawler: Request failed and reached maximum retries', details);
- * }]
+ * @param {Function} [options.handleFailedRequestFunction]
* Function that handles requests that failed more then `option.maxRequestRetries` times.
+ * See source code on <a href="https://github.com/apifytech/apify-js/blob/master/src/basic_crawler.js#L11">GitHub</a> for default behavior.
* @param {Number} [options.maxRequestRetries=3]
* How many times the request is retried if `handleRequestFunction` failed.
* @param {Number} [options.maxRequestsPerCrawl]
* Maximum number of pages that the crawler will open. The crawl will stop when this limit is reached.
* Always set this value in order to prevent infinite loops in misconfigured crawlers.
* Note that in cases of parallel crawling, the actual number of pages visited might be slightly higher than this value.
- * @param {Number} [options.maxMemoryMbytes]
- * Maximum memory available in the system
- * See `AutoscaledPool` for details.
- * @param {Number} [options.minConcurrency=1]
- * Minimum number of request to process in parallel.
- * See `AutoscaledPool` for details.
- * @param {Number} [options.maxConcurrency=1000]
- * Maximum number of request to process in parallel.
- * See `AutoscaledPool` for details.
- * @param {Number} [options.minFreeMemoryRatio=0.2]
- * Minimum ratio of free memory kept in the system.
- * See `AutoscaledPool` for details.
- * @param {Function} [opts.isFinishedFunction]
- * By default BasicCrawler finishes when all the requests have been processed.
- * You can override this behaviour by providing custom `isFinishedFunction`.
- * This function that is called every time there are no requests being processed.
- * If it resolves to `true` then the crawler's run finishes.
- * See `AutoscaledPool` for details.
- * @param {Boolean} [options.ignoreMainProcess=false]
- * If set to `true` then the auto-scaling manager does not consider memory consumption
- * of the main Node.js process when scaling the pool up or down.
- * This is mainly useful when tasks are running as separate processes (e.g. web browsers).
- * See `AutoscaledPool` for details.
+ * @param {Object} [options.autoscaledPoolOptions]
+ * Configures the AutoscaledPool. See <a href="#AutoscaledPool">AutoscaledPool documentation</a>.
+ * runTaskFunction(), isTaskReadyFunction() and isFinishedFunction() are provided by BasicCrawler.
+ * @param {Object} [options.minConcurrency=1]
+ * Sets the minimal concurrency (parallelism) for the crawl. Shorthand to the AutoscaledPool option.
+ * @param {Object} [options.maxConcurrency=1000]
+ * Sets the maximal concurrency (parallelism) for the crawl. Shorthand to the AutoscaledPool option.
+
*/
export default class BasicCrawler {
constructor(opts) {
@@ -109,14 +96,11 @@ export default class BasicCrawler {
handleFailedRequestFunction,
maxRequestRetries,
maxRequestsPerCrawl,
+ autoscaledPoolOptions,
- // AutoscaledPool options
- maxMemoryMbytes,
- maxConcurrency,
+ // AutoscaledPool shorthands
minConcurrency,
- minFreeMemoryRatio,
- isFinishedFunction,
- ignoreMainProcess,
+ maxConcurrency,
} = _.defaults(opts, DEFAULT_OPTIONS);
checkParamPrototypeOrThrow(requestList, 'opts.requestList', RequestList, 'Apify.RequestList', true);
@@ -125,6 +109,7 @@ export default class BasicCrawler {
checkParamOrThrow(handleFailedRequestFunction, 'opts.handleFailedRequestFunction', 'Function');
checkParamOrThrow(maxRequestRetries, 'opts.maxRequestRetries', 'Number');
checkParamOrThrow(maxRequestsPerCrawl, 'opts.maxRequestsPerCrawl', 'Maybe Number');
+ checkParamOrThrow(autoscaledPoolOptions, 'opts.autoscaledPoolOptions', 'Object');
if (!requestList && !requestQueue) {
throw new Error('At least one of the parameters "opts.requestList" and "opts.requestQueue" must be provided!');
@@ -139,11 +124,10 @@ export default class BasicCrawler {
const isMaxPagesExceeded = () => maxRequestsPerCrawl && maxRequestsPerCrawl <= this.handledRequestsCount;
- this.autoscaledPoolOptions = {
- maxMemoryMbytes,
- maxConcurrency,
+ const { isFinishedFunction } = autoscaledPoolOptions;
+ const basicCrawlerAutoscaledPoolConfiguration = {
minConcurrency,
- minFreeMemoryRatio,
+ maxConcurrency,
runTaskFunction: async () => {
if (!this.isRunning) return null;
@@ -161,8 +145,9 @@ export default class BasicCrawler {
? isFinishedFunction()
: this._defaultIsFinishedFunction();
},
- ignoreMainProcess,
};
+
+ this.autoscaledPoolOptions = _.defaults(basicCrawlerAutoscaledPoolConfiguration, autoscaledPoolOptions);
}
/**
@@ -175,26 +160,26 @@ export default class BasicCrawler {
this.autoscaledPool = new AutoscaledPool(this.autoscaledPoolOptions);
this.isRunning = true;
- this.rejectOnStopPromise = new Promise((r, reject) => { this.rejectOnStop = reject; });
+ this.rejectOnAbortPromise = new Promise((r, reject) => { this.rejectOnAbort = reject; });
this.isRunningPromise = this.autoscaledPool.run();
try {
await this.isRunningPromise;
this.isRunning = false;
} catch (err) {
this.isRunning = false; // Doing this before rejecting to make sure it's set when error handlers fire.
- this.rejectOnStop(err);
+ this.rejectOnAbort(err);
}
}
/**
- * Stops the crawler by preventing additional requests and terminating the running ones.
+ * Aborts the crawler by preventing additional requests and terminating the running ones.
*
* @return {Promise}
*/
async abort() {
this.isRunning = false;
await this.autoscaledPool.abort();
- this.rejectOnStop(new Error('BasicCrawler: .stop() function has been called. Stopping the crawler.'));
+ this.rejectOnAbort(new Error('BasicCrawler: .abort() function has been called. Aborting the crawler.'));
}
/**
@@ -238,9 +223,9 @@ export default class BasicCrawler {
if (!request) return;
try {
- // rejectOnStopPromise rejects when .stop() is called or AutoscaledPool throws.
+ // rejectOnAbortPromise rejects when .abort() is called or AutoscaledPool throws.
// All running tasks are therefore terminated with an error to be reclaimed and retried.
- await Promise.race([this.handleRequestFunction({ request }), this.rejectOnStopPromise]);
+ await Promise.race([this.handleRequestFunction({ request }), this.rejectOnAbortPromise]);
await source.markRequestHandled(request);
this.handledRequestsCount++;
} catch (err) {
@@ -288,7 +273,7 @@ export default class BasicCrawler {
* @ingore
*/
async _requestFunctionErrorHandler(error, request, source) {
- // Handles case where the crawler was deliberately stopped.
+ // Handles case where the crawler was aborted.
// All running requests are reclaimed and will be retried.
if (!this.isRunning) return source.reclaimRequest(request);
diff --git a/src/cheerio_crawler.js b/src/cheerio_crawler.js
index 13a8b31ae..19c208756 100644
--- a/src/cheerio_crawler.js
+++ b/src/cheerio_crawler.js
@@ -7,6 +7,7 @@ import BasicCrawler from './basic_crawler';
import { createTimeoutPromise } from './utils';
const DEFAULT_OPTIONS = {
+ requestTimeoutSecs: 30,
handlePageTimeoutSecs: 300,
ignoreSslErrors: false,
handleFailedRequestFunction: ({ request }) => {
@@ -16,7 +17,6 @@ const DEFAULT_OPTIONS = {
},
};
-
/**
* Builds upon the `BasicCrawler` with functionality specifically designed for parsing raw HTML
* of web pages. It uses the `cheerio` npm package to provide the user with a pre-parsed HTML
@@ -29,8 +29,10 @@ const DEFAULT_OPTIONS = {
*
* `CheerioCrawler` invokes `handlePageFunction` for each `Request` object fetched from `options.requestList` or `options.requestQueue`,
* as long as none of them is empty. New requests are only handled if there is enough free CPU and memory available,
- * using the functionality provided by the `AutoscaledPool` class.
- * Note that all `AutoscaledPool` configuration options can be passed to `options` parameter of the `CheerioCrawler` constructor.
+ * using the functionality provided by the `AutoscaledPool` class. See <a href="#AutoscaledPool">AutoscaledPool documentation</a>.
+ *
+ * All `AutoscaledPool` configuration options can be passed to the `autoscaledPoolOptions` parameter
+ * of the `CheerioCrawler` constructor. The `minConcurrency` and `maxConcurrency` options are available directly.
*
* If both `requestList` and `requestQueue` are used, the instance first
* processes URLs from the `requestList` and automatically enqueues all of them to `requestQueue` before it starts
@@ -39,8 +41,6 @@ const DEFAULT_OPTIONS = {
* Example usage:
*
* ```javascript
- * const rp = require('request-promise');
- *
* // Prepare a list of URLs to crawl
* const requestList = new Apify.RequestList({
* sources: [
@@ -75,75 +75,52 @@ const DEFAULT_OPTIONS = {
* ```
*
* @param {Object} options
+ * @param {Function} options.handlePageFunction
+ * A function that receives three arguments: the Cheerio object `$`, the raw HTML and the `Request` object and does all the document manipulation.
+ * If it returns a promise, it is awaited.
+ *
+ * @param {Function} [options.requestFunction]
+ * Overrides the function that performs the HTTP request to get the raw HTML needed for Cheerio.
+ * See source code on <a href="https://github.com/apifytech/apify-js/blob/master/src/cheerio_crawler.js#L246">GitHub</a> for default behavior.
* @param {RequestList} [options.requestList]
* Static list of URLs to be processed.
* @param {RequestQueue} [options.requestQueue]
* Dynamic queue of URLs to be processed. This is useful for recursive crawling of websites.
- * @param {Function} [options.handlePageFunction]
- * A function that receives three arguments: the Cheerio object `$`, the raw HTML and the `Request` object and does all the document manipulation.
- * If it returns a promise, it is awaited.
* @param {Number} [options.handlePageTimeoutSecs=300]
* Timeout in which the function passed as `options.handlePageFunction` needs to finish, given in seconds.
- * @param {Function} [options.requestFunction=({ request }) => {
- * return requestPromise({
- * url: request.url,
- * method: request.method,
- * headers: request.headers,
- * strictSSL: !this.ignoreSslErrors,
- * });
- * }]
- * Overrides the function that performs the HTTP request to get the raw HTML needed for Cheerio.
+ * @param {Number} [options.requestTimeoutSecs=30]
+ * Timeout in which the function passed as `options.requestFunction` needs to finish, given in seconds.
* @param {Boolean} [options.ignoreSslErrors=false]
* If set to true, SSL certificate errors will be ignored. This is dependent on using the default
* request function. If using a custom request function, user needs to implement this functionality.
- * @param {Function} [options.handleFailedRequestFunction=({ request }) => {
- * const details = _.pick(request, 'id', 'url', 'method', 'uniqueKey');
- * log.error('BasicCrawler: Request failed and reached maximum retries', details);]
+ * @param {Function} [options.handleFailedRequestFunction]
* Function that handles requests that failed more then `option.maxRequestRetries` times.
+ * See source code on <a href="https://github.com/apifytech/apify-js/blob/master/src/cheerio_crawler.js#L12">GitHub</a> for default behavior.
* @param {Number} [options.maxRequestRetries=3]
* How many times the request is retried if either `requestFunction` or `handlePageFunction` failed.
* @param {Number} [options.maxRequestsPerCrawl]
* Maximum number of pages that the crawler will open. The crawl will stop when this limit is reached.
* Always set this value in order to prevent infinite loops in misconfigured crawlers.
* Note that in cases of parallel crawling, the actual number of pages visited might be slightly higher than this value.
- * @param {Number} [options.maxMemoryMbytes]
- * Maximum memory available in the system
- * See `AutoscaledPool` for details.
- * @param {Number} [options.minConcurrency=1]
- * Minimum number of request to process in parallel.
- * See `AutoscaledPool` for details.
- * @param {Number} [options.maxConcurrency=1000]
- * Maximum number of request to process in parallel.
- * See `AutoscaledPool` for details.
- * @param {Number} [options.minFreeMemoryRatio=0.2]
- * Minimum ratio of free memory kept in the system.
- * See `AutoscaledPool` for details.
- * @param {Function} [opts.isFinishedFunction]
- * By default CheerioCrawler finishes when all the requests have been processed.
- * You can override this behaviour by providing custom `isFinishedFunction`.
- * This function that is called every time there are no requests being processed.
- * If it resolves to `true` then the crawler's run finishes.
- * See `AutoscaledPool` for details.
- * @param {Boolean} [options.ignoreMainProcess=false]
- * If set to `true` then the auto-scaling manager does not consider memory consumption
- * of the main Node.js process when scaling the pool up or down.
- * This is mainly useful when tasks are running as separate processes (e.g. web browsers).
- * See `AutoscaledPool` for details.
+ * @param {Object} [options.autoscaledPoolOptions]
+ * Configures the AutoscaledPool. See <a href="#AutoscaledPool">AutoscaledPool documentation</a>.
+ * @param {Object} [options.minConcurrency]
+ * Sets the minimal concurrency (parallelism) for the crawl. Shorthand to the AutoscaledPool option.
+ * @param {Object} [options.maxConcurrency]
+ * Sets the maximal concurrency (parallelism) for the crawl. Shorthand to the AutoscaledPool option.
*/
export default class CheerioCrawler {
- constructor(opts) {
+ constructor(opts = {}) {
const {
requestFunction,
handlePageFunction,
+ requestTimeoutSecs,
handlePageTimeoutSecs,
ignoreSslErrors,
- // Autoscaled pool options
- maxMemoryMbytes,
- maxConcurrency,
+ // Autoscaled pool shorthands
minConcurrency,
- minFreeMemoryRatio,
- isFinishedFunction,
+ maxConcurrency,
// Basic crawler options
requestList,
@@ -151,11 +128,14 @@ export default class CheerioCrawler {
maxRequestRetries,
maxRequestsPerCrawl,
handleFailedRequestFunction,
+ autoscaledPoolOptions,
} = _.defaults(opts, DEFAULT_OPTIONS);
checkParamOrThrow(handlePageFunction, 'opts.handlePageFunction', 'Function');
checkParamOrThrow(requestFunction, 'opts.requestFunction', 'Maybe Function');
- checkParamOrThrow(handleFailedRequestFunction, 'opts.handleFailedRequestFunction', 'Maybe Function');
+ checkParamOrThrow(requestTimeoutSecs, 'opts.requestTimeoutSecs', 'Number');
+ checkParamOrThrow(handlePageTimeoutSecs, 'opts.handlePageTimeoutSecs', 'Number');
+ checkParamOrThrow(ignoreSslErrors, 'opts.ignoreSslErrors', 'Boolean');
this.ignoreSslErrors = ignoreSslErrors;
@@ -167,7 +147,8 @@ export default class CheerioCrawler {
: this._defaultRequestFunction({ request });
};
this.handlePageFunction = handlePageFunction;
- this.handlePageTimeoutSecs = handlePageTimeoutSecs;
+ this.handlePageTimeoutMillis = handlePageTimeoutSecs * 1000;
+ this.requestTimeoutMillis = requestTimeoutSecs * 1000;
this.basicCrawler = new BasicCrawler({
// Basic crawler options.
@@ -179,12 +160,9 @@ export default class CheerioCrawler {
handleFailedRequestFunction,
// Autoscaled pool options.
- maxMemoryMbytes,
- maxConcurrency,
minConcurrency,
- minFreeMemoryRatio,
- isFinishedFunction,
- ignoreMainProcess: true,
+ maxConcurrency,
+ autoscaledPoolOptions,
});
}
@@ -197,26 +175,26 @@ export default class CheerioCrawler {
if (this.isRunning) return this.isRunningPromise;
this.isRunning = true;
- this.rejectOnStopPromise = new Promise((r, reject) => { this.rejectOnStop = reject; });
+ this.rejectOnAbortPromise = new Promise((r, reject) => { this.rejectOnAbort = reject; });
try {
this.isRunningPromise = this.basicCrawler.run();
await this.isRunningPromise;
this.isRunning = false;
} catch (err) {
this.isRunning = false; // Doing this before rejecting to make sure it's set when error handlers fire.
- this.rejectOnStop(err);
+ this.rejectOnAbort(err);
}
}
/**
- * Stops the crawler by preventing crawls of additional pages and terminating the running ones.
+ * Aborts the crawler by preventing crawls of additional pages and terminating the running ones.
*
* @return {Promise}
*/
async abort() {
this.isRunning = false;
await this.basicCrawler.abort();
- this.rejectOnStop(new Error('CheerioCrawler: .stop() function has been called. Stopping the crawler.'));
+ this.rejectOnAbort(new Error('CheerioCrawler: .abort() function has been called. Aborting the crawler.'));
}
/**
@@ -227,16 +205,19 @@ export default class CheerioCrawler {
async _handleRequestFunction({ request }) {
if (!this.isRunning) throw new Error('CheerioCrawler is stopped.');
- const html = await this.requestFunction({ request });
+ // rejectOnAbortPromise rejects when .abort() is called or BasicCrawler throws.
+ // All running pages are therefore terminated with an error to be reclaimed and retried.
+ const html = await Promise.race([
+ this.requestFunction({ request }),
+ createTimeoutPromise(this.requestTimeoutMillis, 'CheerioCrawler: requestFunction timed out.'),
+ this.rejectOnAbortPromise,
+ ]);
const $ = cheerio.load(html);
- const pageHandledOrTimedOutPromise = Promise.race([
+ await Promise.race([
this.handlePageFunction({ $, html, request }),
- createTimeoutPromise(this.handlePageTimeoutSecs * 1000, 'CheerioCrawler: handlePageFunction timed out.'),
+ createTimeoutPromise(this.handlePageTimeoutMillis, 'CheerioCrawler: handlePageFunction timed out.'),
+ this.rejectOnAbortPromise,
]);
-
- // rejectOnStopPromise rejects when .stop() is called or BasicCrawler throws.
- // All running pages are therefore terminated with an error to be reclaimed and retried.
- return Promise.race([pageHandledOrTimedOutPromise, this.rejectOnStopPromise]);
}
/**
@@ -253,7 +234,7 @@ export default class CheerioCrawler {
headers: request.headers,
strictSSL: !this.ignoreSslErrors,
}),
- this.rejectOnStopPromise,
+ this.rejectOnAbortPromise,
]);
}
}
diff --git a/src/index.js b/src/index.js
index bf33de0f2..774af9286 100644
--- a/src/index.js
+++ b/src/index.js
@@ -1,7 +1,7 @@
import log from 'apify-shared/log';
import { ENV_VARS } from 'apify-shared/consts';
import { main, getEnv, call, getApifyProxyUrl } from './actor';
-import AutoscaledPool from './autoscaled_pool';
+import AutoscaledPool from './autoscaling/autoscaled_pool';
import BasicCrawler from './basic_crawler';
import CheerioCrawler from './cheerio_crawler';
import { pushData, openDataset } from './dataset';
diff --git a/src/puppeteer_crawler.js b/src/puppeteer_crawler.js
index a8de1a81d..631bb26e6 100644
--- a/src/puppeteer_crawler.js
+++ b/src/puppeteer_crawler.js
@@ -212,28 +212,28 @@ export default class PuppeteerCrawler {
this.puppeteerPool = new PuppeteerPool(this.puppeteerPoolOptions);
this.isRunning = true;
- this.rejectOnStopPromise = new Promise((r, reject) => { this.rejectOnStop = reject; });
+ this.rejectOnAbortPromise = new Promise((r, reject) => { this.rejectOnAbort = reject; });
try {
this.isRunningPromise = this.basicCrawler.run();
await this.isRunningPromise;
this.isRunning = false;
} catch (err) {
this.isRunning = false; // Doing this before rejecting to make sure it's set when error handlers fire.
- this.rejectOnStop(err);
+ this.rejectOnAbort(err);
} finally {
this.puppeteerPool.destroy();
}
}
/**
- * Stops the crawler by preventing crawls of additional pages and terminating the running ones.
+ * Stops the crawler by preventing crawls of additional pages and terminating the running ones.
*
* @return {Promise}
*/
async abort() {
this.isRunning = false;
await this.basicCrawler.abort();
- this.rejectOnStop(new Error('PuppeteerCrawler: .stop() function has been called. Stopping the crawler.'));
+ this.rejectOnAbort(new Error('PuppeteerCrawler: .abort() function has been called. Aborting the crawler.'));
}
/**
@@ -256,9 +256,9 @@ export default class PuppeteerCrawler {
]);
});
- // rejectOnStopPromise rejects when .stop() is called or BasicCrawler throws.
+ // rejectOnAbortPromise rejects when .abort() is called or BasicCrawler throws.
// All running pages are therefore terminated with an error to be reclaimed and retried.
- return await Promise.race([pageOperationsPromise, this.rejectOnStopPromise]);
+ return await Promise.race([pageOperationsPromise, this.rejectOnAbortPromise]);
} finally {
try {
await Promise.race([page.close(), createTimeoutPromise(PAGE_CLOSE_TIMEOUT_MILLIS, 'Operation timed out.')]);
diff --git a/src/utils.js b/src/utils.js
index 5e97c2f35..6c761a007 100644
--- a/src/utils.js
+++ b/src/utils.js
@@ -157,6 +157,23 @@ export const sum = arr => arr.reduce((total, c) => total + c, 0);
*/
export const avg = arr => sum(arr) / arr.length;
+/**
+ * Computes a weighted average of an array of numbers, complemented by an array of weights.
+ * @param {Array} arrValues
+ * @param {Array} arrWeights
+ * @return {number}
+ */
+export const weightedAvg = (arrValues, arrWeights) => {
+ const result = arrValues.map((value, i) => {
+ const weight = arrWeights[i];
+ const sum = value * weight; // eslint-disable-line no-shadow
+
+ return [sum, weight];
+ }).reduce((p, c) => [p[0] + c[0], p[1] + c[1]], [0, 0]);
+
+ return result[0] / result[1];
+};
+
/**
* Returns memory statistics of the process and the system, which is an object with the following properties:
*
diff --git a/test/autoscaled_pool.js b/test/autoscaled_pool.js
deleted file mode 100644
index 0f5824427..000000000
--- a/test/autoscaled_pool.js
+++ /dev/null
@@ -1,762 +0,0 @@
-import chai, { expect } from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import 'babel-polyfill';
-import _ from 'underscore';
-import sinon from 'sinon';
-import { delayPromise } from 'apify-shared/utilities';
-import log from 'apify-shared/log';
-import { ACTOR_EVENT_NAMES, ENV_VARS } from 'apify-shared/consts';
-import * as Apify from '../build/index';
-import { SCALE_UP_MAX_STEP, SCALE_UP_INTERVAL, SCALE_DOWN_INTERVAL } from '../build/autoscaled_pool';
-import * as utils from '../build/utils';
-
-/* eslint-disable no-underscore-dangle */
-
-chai.use(chaiAsPromised);
-const toBytes = x => x * 1024 * 1024;
-
-describe('AutoscaledPool', () => {
- let logLevel;
- // This is here to enable autoscaling that is temporarily disabled when running locally.
- before(() => {
- logLevel = log.getLevel();
- log.setLevel(log.LEVELS.ERROR);
- process.env[ENV_VARS.IS_AT_HOME] = 1;
- });
-
- after(() => {
- log.setLevel(logLevel);
- delete process.env[ENV_VARS.IS_AT_HOME];
- });
-
- it('should work with concurrency 1', async () => {
- const range = _.range(0, 10);
- const result = [];
-
- let isFinished = false;
-
- const runTaskFunction = () => {
- if (range.length === 1) {
- isFinished = true;
- }
-
- return new Promise((resolve) => {
- const item = range.shift();
- result.push(item);
- setTimeout(resolve, 10);
- });
- };
-
- const pool = new Apify.AutoscaledPool({
- minConcurrency: 1,
- maxConcurrency: 1,
- runTaskFunction,
- isFinishedFunction: () => Promise.resolve(isFinished),
- isTaskReadyFunction: () => Promise.resolve(!isFinished),
- });
- const startedAt = Date.now();
- await pool.run();
-
- expect(result).to.be.eql(_.range(0, 10));
- expect(Date.now() - startedAt).to.be.within(100, 150);
- });
-
- it('should work with concurrency 10', async () => {
- const range = _.range(0, 100);
- const result = [];
-
- let isFinished = false;
-
- const runTaskFunction = () => {
- if (range.length === 1) {
- isFinished = true;
- }
-
- return new Promise((resolve) => {
- const item = range.shift();
- result.push(item);
- setTimeout(resolve, 10);
- });
- };
-
- const pool = new Apify.AutoscaledPool({
- minConcurrency: 10,
- maxConcurrency: 10,
- runTaskFunction,
- isFinishedFunction: () => Promise.resolve(isFinished),
- isTaskReadyFunction: () => Promise.resolve(!isFinished),
- });
-
- const startedAt = Date.now();
- await pool.run();
-
- expect(result).to.be.eql(_.range(0, 100));
- expect(Date.now() - startedAt).to.be.within(100, 150);
- });
-
- it('correctly computed space for instances', async () => {
- const pool = new Apify.AutoscaledPool({
- minConcurrency: 1,
- maxConcurrency: 100,
- runTaskFunction: () => Promise.resolve(),
- isFinishedFunction: () => Promise.resolve(false),
- isTaskReadyFunction: () => Promise.resolve(true),
- });
-
- pool.concurrency = 20;
- pool.runningCount = 20;
- pool.freeBytesSnapshots = [
- toBytes(50),
- toBytes(30),
- toBytes(50),
- toBytes(40),
- ];
- const hasSpaceForInstances = pool._computeSpaceForInstances(toBytes(100), null);
- expect(hasSpaceForInstances).to.be.eql(5);
-
- pool.concurrency = 20;
- pool.runningCount = 20;
- pool.freeBytesSnapshots = [
- toBytes(5),
- toBytes(5),
- toBytes(5),
- toBytes(5),
- ];
- const hasSpaceForInstances2 = pool._computeSpaceForInstances(toBytes(100), null);
- expect(hasSpaceForInstances2).to.be.eql(-2);
- });
-
- it('should autoscale correctly', async () => {
- const pool = new Apify.AutoscaledPool({
- minConcurrency: 1,
- maxConcurrency: 100,
- minFreeMemoryRatio: 0.1,
- runTaskFunction: () => Promise.resolve(),
- isFinishedFunction: () => Promise.resolve(false),
- isTaskReadyFunction: () => Promise.resolve(true),
- });
- const mock = sinon.mock(utils);
-
- // Should scale up.
- pool.concurrency = 1;
- pool.runningCount = 1;
- pool.intervalCounter = SCALE_UP_INTERVAL - 1;
- mock.expects('getMemoryInfo')
- .once()
- .returns(Promise.resolve({ freeBytes: toBytes(9.99), totalBytes: toBytes(10) }));
- await pool._autoscale();
- expect(pool.concurrency).to.be.eql(1 + SCALE_UP_MAX_STEP);
-
- // Should not do anything when there is right amount of memory used.
- pool.concurrency = 10;
- pool.runningCount = 10;
- pool.intervalCounter = SCALE_UP_INTERVAL - 1;
- mock.expects('getMemoryInfo')
- .once()
- .returns(Promise.resolve({ freeBytes: toBytes(1), totalBytes: toBytes(10) }));
- await pool._autoscale();
- expect(pool.concurrency).to.be.eql(10);
-
- // Now there is not enough of memory but average from last SCALE_DOWN_INTERVAL snapshots is still ok.
- // TODO: this test is failing now that we changed the constants in hotfix!
- /* pool.concurrency = 10;
- pool.runningCount = 10;
- mock.expects('getMemoryInfo')
- .exactly(3)
- .returns(Promise.resolve({ freeBytes: toBytes(0.9), totalBytes: toBytes(10) }));
- let promise = Promise.resolve();
- for (let i = 0; i < 3; i++) {
- promise = promise.then(() => {
- pool.intervalCounter = SCALE_UP_INTERVAL - 1;
- return pool._autoscale();
- });
- }
- await promise;
- expect(pool.concurrency).to.be.eql(10); */
-
- // Now the average is below threshold so pool scales down.
- pool.concurrency = 10;
- pool.runningCount = 10;
- mock.expects('getMemoryInfo')
- .once()
- .returns(Promise.resolve({ freeBytes: toBytes(0.9), totalBytes: toBytes(10) }));
- pool.intervalCounter = SCALE_UP_INTERVAL - 1;
- await pool._autoscale();
- expect(pool.concurrency).to.be.eql(9);
-
- mock.verify();
- mock.restore();
- });
-
- it('should autoscale correctly when ignoring main process', async () => {
- const pool = new Apify.AutoscaledPool({
- ignoreMainProcess: true,
- minConcurrency: 1,
- maxConcurrency: 100,
- minFreeMemoryRatio: 0.1,
- runTaskFunction: () => Promise.resolve(),
- isFinishedFunction: () => Promise.resolve(false),
- isTaskReadyFunction: () => Promise.resolve(true),
- });
- const mock = sinon.mock(utils);
-
- // Should not scale up.
- pool.concurrency = 1;
- pool.runningCount = 1;
- pool.intervalCounter = SCALE_UP_INTERVAL - 1;
- mock.expects('getMemoryInfo')
- .once()
- .returns(Promise.resolve({
- freeBytes: toBytes(5),
- totalBytes: toBytes(10),
- mainProcessBytes: 0,
- }));
- await pool._autoscale();
- expect(pool.concurrency).to.be.eql(1);
-
- // Should scale up.
- pool.concurrency = 1;
- pool.runningCount = 1;
- pool.intervalCounter = SCALE_UP_INTERVAL - 1;
- mock.expects('getMemoryInfo')
- .once()
- .returns(Promise.resolve({
- freeBytes: toBytes(5),
- totalBytes: toBytes(10),
- mainProcessBytes: toBytes(4),
- }));
- await pool._autoscale();
- expect(pool.concurrency).to.be.eql(5);
-
- mock.verify();
- mock.restore();
- });
-
- it('should work with loggingIntervalMillis = null', async () => {
- const pool = new Apify.AutoscaledPool({
- ignoreMainProcess: true,
- minConcurrency: 1,
- maxConcurrency: 100,
- minFreeMemoryRatio: 0.1,
- runTaskFunction: () => Promise.resolve(),
- isFinishedFunction: () => Promise.resolve(false),
- isTaskReadyFunction: () => Promise.resolve(true),
- loggingIntervalMillis: null,
- });
- const mock = sinon.mock(utils);
-
- // Should not scale up.
- pool.concurrency = 1;
- pool.runningCount = 1;
- pool.intervalCounter = SCALE_UP_INTERVAL - 1;
- mock.expects('getMemoryInfo')
- .once()
- .returns(Promise.resolve({
- freeBytes: toBytes(5),
- totalBytes: toBytes(10),
- mainProcessBytes: 0,
- }));
- await pool._autoscale();
- expect(pool.concurrency).to.be.eql(1);
-
- mock.verify();
- mock.restore();
- });
-
- it('should throw when some of the promises throws', async () => {
- let counter = 0;
- const runTaskFunction = () => {
- counter++;
-
- if (counter > 100) return;
-
- if (counter === 100) {
- const err = new Error('some-error');
-
- return new Promise((resolve, reject) => setTimeout(reject(err), 10));
- }
-
- return delayPromise(10);
- };
-
- const pool = new Apify.AutoscaledPool({
- minConcurrency: 10,
- maxConcurrency: 10,
- runTaskFunction,
- isFinishedFunction: () => Promise.resolve(false),
- isTaskReadyFunction: () => Promise.resolve(true),
- });
-
- await expect(pool.run()).to.be.rejectedWith('some-error');
- });
-
- it('should throw when runTaskFunction throws', async () => {
- const runTaskFunction = () => {
- throw new Error('some-error');
- };
-
- const pool = new Apify.AutoscaledPool({
- minConcurrency: 10,
- maxConcurrency: 10,
- runTaskFunction,
- isFinishedFunction: () => Promise.resolve(false),
- isTaskReadyFunction: () => Promise.resolve(true),
- });
-
- await expect(pool.run()).to.be.rejectedWith('some-error');
- });
-
- it('should scale down when CPU is overloaded', async () => {
- const pool = new Apify.AutoscaledPool({
- minConcurrency: 1,
- maxConcurrency: 100,
- minFreeMemoryRatio: 0.1,
- runTaskFunction: () => Promise.resolve(),
- isFinishedFunction: () => Promise.resolve(false),
- isTaskReadyFunction: () => Promise.resolve(true),
- });
- const mock = sinon.mock(utils);
-
- // Emit CPU overloaded events but not required amount so that we can still scale up.
- for (let i = 0; i < SCALE_DOWN_INTERVAL - 1; i++) {
- Apify.events.emit(ACTOR_EVENT_NAMES.CPU_INFO, { isCpuOverloaded: true });
- }
-
- // Should scale up.
- pool.intervalCounter = SCALE_UP_INTERVAL - 1;
- pool.runningCount = pool.concurrency;
- mock.expects('getMemoryInfo')
- .once()
- .returns(Promise.resolve({ freeBytes: toBytes(9.99), totalBytes: toBytes(10) }));
- await pool._autoscale();
- expect(pool.concurrency).to.be.eql(1 + SCALE_UP_MAX_STEP);
-
- // Should scale up.
- pool.intervalCounter = SCALE_UP_INTERVAL - 1;
- pool.runningCount = pool.concurrency;
- mock.expects('getMemoryInfo')
- .once()
- .returns(Promise.resolve({ freeBytes: toBytes(9.99), totalBytes: toBytes(10) }));
- await pool._autoscale();
- expect(pool.concurrency).to.be.eql(1 + (2 * SCALE_UP_MAX_STEP));
-
- // Emit final CPU overloaded = true event.
- Apify.events.emit(ACTOR_EVENT_NAMES.CPU_INFO, { isCpuOverloaded: true });
-
- // Should scale up but because of CPU overloaded event it always scales down.
- pool.runningCount = pool.concurrency;
- for (let i = 1; i <= 5; i++) {
- pool.intervalCounter = SCALE_UP_INTERVAL - 1;
- mock.expects('getMemoryInfo')
- .once()
- .returns(Promise.resolve({ freeBytes: toBytes(9.99), totalBytes: toBytes(10) }));
- await pool._autoscale(); //eslint-disable-line
- expect(pool.concurrency).to.be.eql((1 + (2 * SCALE_UP_MAX_STEP)) - i);
- }
-
- // Emit CPU overloaded = false event.
- Apify.events.emit(ACTOR_EVENT_NAMES.CPU_INFO, { isCpuOverloaded: false });
-
- // Should scale up again.
- pool.runningCount = pool.concurrency;
- pool.intervalCounter = SCALE_UP_INTERVAL - 1;
- mock.expects('getMemoryInfo')
- .once()
- .returns(Promise.resolve({ freeBytes: toBytes(9.99), totalBytes: toBytes(10) }));
- await pool._autoscale();
- expect(pool.concurrency).to.be.eql((1 + (3 * SCALE_UP_MAX_STEP)) - 5);
-
- mock.verify();
- mock.restore();
- });
-
- it('should not handle tasks added after isFinishedFunction returned true', async () => {
- const tasks = [];
- const finished = [];
-
- let isFinished = false;
-
- // Start 3 tasks immediately.
- tasks.push(delayPromise(50).then(() => finished.push(0)));
- tasks.push(delayPromise(50).then(() => finished.push(1)));
- tasks.push(delayPromise(50).then(() => finished.push(2)));
-
- setTimeout(() => {
- isFinished = true;
- }, 200);
-
- // Add 2 tasks after 500ms.
- setTimeout(() => tasks.push(delayPromise(50).then(() => finished.push(3))), 300);
- setTimeout(() => tasks.push(delayPromise(50).then(() => finished.push(4))), 300);
-
- // Run the pool and close it after 3s.
- const pool = new Apify.AutoscaledPool({
- maybeRunIntervalMillis: 10,
- minConcurrency: 3,
- runTaskFunction: () => tasks.pop(),
- isFinishedFunction: () => Promise.resolve(isFinished),
- isTaskReadyFunction: () => Promise.resolve(true),
- });
- await pool.run();
-
- // Check finished tasks.
- expect(finished).to.be.eql([0, 1, 2]);
- });
-
- it('should not handle tasks added if isTaskReadyFunction returned true', async () => {
- const tasks = [];
- const finished = [];
-
- let isFinished = false;
- let isTaskReady = true;
-
- const getTask = (id) => {
- return () => delayPromise(50).then(() => finished.push(id));
- };
-
- // Start 3 tasks immediately.
- tasks.push(getTask(0));
- tasks.push(getTask(1));
- setTimeout(() => tasks.push(getTask(2)), 150);
-
- setTimeout(() => {
- isTaskReady = false;
- }, 200);
-
- // Add 2 tasks after 500ms.
- setTimeout(() => tasks.push(getTask(3)), 300);
- setTimeout(() => tasks.push(getTask(4)), 300);
-
- // Remove tasks and se isTaskReady=true to accept a new task.
- setTimeout(() => {
- tasks.pop();
- tasks.pop();
- isTaskReady = true;
- }, 390);
-
- // Add one more task.
- setTimeout(() => tasks.push(getTask(5)), 400);
-
- // Finish.
- setTimeout(() => {
- isFinished = true;
- }, 500);
-
- // Run the pool and close it after 3s.
- const pool = new Apify.AutoscaledPool({
- maybeRunIntervalMillis: 10,
- minConcurrency: 3,
- runTaskFunction: () => {
- const task = tasks.shift();
-
- if (!task) return;
-
- return task();
- },
- isFinishedFunction: () => Promise.resolve(isFinished),
- isTaskReadyFunction: () => Promise.resolve(isTaskReady),
- });
- await pool.run();
-
- // Check finished tasks.
- expect(finished).to.be.eql([0, 1, 2, 5]);
- });
-
- /**
- * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
- *
- * All the tests below use workerFunction and opts.finishWhenEmpty
- * to test that new version of AutoscaledPool is backwards compatible.
- *
- * TODO: after we release v1.0.0 we can remove this compatibility.
- *
- * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
- */
-
- it('[DEPRECATED] should work with concurrency 1', async () => {
- const range = _.range(0, 10);
- const result = [];
-
- const workerFunction = () => {
- if (range.length === 0) return;
-
- return new Promise((resolve) => {
- const item = range.shift();
- result.push(item);
- setTimeout(resolve, 10);
- });
- };
-
- const pool = new Apify.AutoscaledPool({
- minConcurrency: 1,
- maxConcurrency: 1,
- workerFunction,
- });
- const startedAt = Date.now();
- await pool.run();
-
- expect(result).to.be.eql(_.range(0, 10));
- expect(Date.now() - startedAt).to.be.within(100, 150);
- });
-
- it('[DEPRECATED] should work with concurrency 10', async () => {
- const range = _.range(0, 100);
- const result = [];
-
- const workerFunction = () => {
- if (range.length === 0) return;
-
- return new Promise((resolve) => {
- const item = range.shift();
- result.push(item);
- setTimeout(resolve, 10);
- });
- };
-
- const pool = new Apify.AutoscaledPool({
- minConcurrency: 10,
- maxConcurrency: 10,
- workerFunction,
- });
-
- const startedAt = Date.now();
- await pool.run();
-
- expect(result).to.be.eql(_.range(0, 100));
- expect(Date.now() - startedAt).to.be.within(100, 150);
- });
-
- it('[DEPRECATED] correctly computed space for instances using', async () => {
- const pool = new Apify.AutoscaledPool({
- minConcurrency: 1,
- maxConcurrency: 100,
- workerFunction: async () => {},
- });
-
- pool.concurrency = 20;
- pool.runningCount = 20;
- pool.freeBytesSnapshots = [
- toBytes(50),
- toBytes(30),
- toBytes(50),
- toBytes(40),
- ];
- const hasSpaceForInstances = pool._computeSpaceForInstances(toBytes(100), null);
- expect(hasSpaceForInstances).to.be.eql(5);
-
- pool.concurrency = 20;
- pool.runningCount = 20;
- pool.freeBytesSnapshots = [
- toBytes(5),
- toBytes(5),
- toBytes(5),
- toBytes(5),
- ];
- const hasSpaceForInstances2 = pool._computeSpaceForInstances(toBytes(100), null);
- expect(hasSpaceForInstances2).to.be.eql(-2);
- });
-
- it('[DEPRECATED] should autoscale correctly', async () => {
- const pool = new Apify.AutoscaledPool({
- minConcurrency: 1,
- maxConcurrency: 100,
- minFreeMemoryRatio: 0.1,
- workerFunction: async () => {},
- });
- const mock = sinon.mock(utils);
-
- // Should scale up.
- pool.concurrency = 1;
- pool.runningCount = 1;
- pool.intervalCounter = SCALE_UP_INTERVAL - 1;
- mock.expects('getMemoryInfo')
- .once()
- .returns(Promise.resolve({ freeBytes: toBytes(9.99), totalBytes: toBytes(10) }));
- await pool._autoscale();
- expect(pool.concurrency).to.be.eql(1 + SCALE_UP_MAX_STEP);
-
- // Should not do anything when there is right amount of memory used.
- pool.concurrency = 10;
- pool.runningCount = 10;
- pool.intervalCounter = SCALE_UP_INTERVAL - 1;
- mock.expects('getMemoryInfo')
- .once()
- .returns(Promise.resolve({ freeBytes: toBytes(1), totalBytes: toBytes(10) }));
- await pool._autoscale();
- expect(pool.concurrency).to.be.eql(10);
-
- // Now there is not enough of memory but average from last SCALE_DOWN_INTERVAL snapshots is still ok.
- /*
- pool.concurrency = 10;
- pool.runningCount = 10;
- mock.expects('getMemoryInfo')
- .exactly(3)
- .returns(Promise.resolve({ freeBytes: toBytes(0.9), totalBytes: toBytes(10) }));
- let promise = Promise.resolve();
- for (let i = 0; i < 3; i++) {
- promise = promise.then(() => {
- pool.intervalCounter = SCALE_UP_INTERVAL - 1;
- return pool._autoscale();
- });
- }
- await promise;
- expect(pool.concurrency).to.be.eql(10); */
-
- // Now the average is below threshold so pool scales down.
- pool.concurrency = 10;
- pool.runningCount = 10;
- mock.expects('getMemoryInfo')
- .once()
- .returns(Promise.resolve({ freeBytes: toBytes(0.9), totalBytes: toBytes(10) }));
- pool.intervalCounter = SCALE_UP_INTERVAL - 1;
- await pool._autoscale();
- expect(pool.concurrency).to.be.eql(9);
-
- mock.verify();
- mock.restore();
- });
-
- it('[DEPRECATED] should throw when some of the promises throws', async () => {
- let counter = 0;
- const workerFunction = () => {
- counter++;
-
- if (counter > 100) return;
-
- if (counter === 100) {
- const err = new Error('some-error');
-
- return new Promise((resolve, reject) => setTimeout(reject(err), 10));
- }
-
- return delayPromise(10);
- };
-
- const pool = new Apify.AutoscaledPool({
- minConcurrency: 10,
- maxConcurrency: 10,
- workerFunction,
- });
-
- await expect(pool.run()).to.be.rejectedWith('some-error');
- });
-
- it('[DEPRECATED] should scale down when CPU is overloaded', async () => {
- const pool = new Apify.AutoscaledPool({
- minConcurrency: 1,
- maxConcurrency: 100,
- minFreeMemoryRatio: 0.1,
- workerFunction: async () => {},
- });
- const mock = sinon.mock(utils);
-
- // Emit CPU overloaded events but not required emount so that we can still scale up.
- for (let i = 0; i < SCALE_DOWN_INTERVAL - 1; i++) {
- Apify.events.emit(ACTOR_EVENT_NAMES.CPU_INFO, { isCpuOverloaded: true });
- }
-
- // Should scale up.
- pool.intervalCounter = SCALE_UP_INTERVAL - 1;
- pool.runningCount = pool.concurrency;
- mock.expects('getMemoryInfo')
- .once()
- .returns(Promise.resolve({ freeBytes: toBytes(9.99), totalBytes: toBytes(10) }));
- await pool._autoscale();
- expect(pool.concurrency).to.be.eql(1 + SCALE_UP_MAX_STEP);
-
- // Should scale up.
- pool.intervalCounter = SCALE_UP_INTERVAL - 1;
- pool.runningCount = pool.concurrency;
- mock.expects('getMemoryInfo')
- .once()
- .returns(Promise.resolve({ freeBytes: toBytes(9.99), totalBytes: toBytes(10) }));
- await pool._autoscale();
- expect(pool.concurrency).to.be.eql(1 + (2 * SCALE_UP_MAX_STEP));
-
- // Emit final CPU overloaded = true event.
- Apify.events.emit(ACTOR_EVENT_NAMES.CPU_INFO, { isCpuOverloaded: true });
-
- // Should scale up but because of CPU overloaded event it always scales down.
- pool.runningCount = pool.concurrency;
- for (let i = 1; i <= 5; i++) {
- pool.intervalCounter = SCALE_UP_INTERVAL - 1;
- mock.expects('getMemoryInfo')
- .once()
- .returns(Promise.resolve({ freeBytes: toBytes(9.99), totalBytes: toBytes(10) }));
- await pool._autoscale(); //eslint-disable-line
- expect(pool.concurrency).to.be.eql((1 + (2 * SCALE_UP_MAX_STEP)) - i);
- }
-
- // Emit CPU overloaded = false event.
- Apify.events.emit(ACTOR_EVENT_NAMES.CPU_INFO, { isCpuOverloaded: false });
-
- // Should scale up again.
- pool.runningCount = pool.concurrency;
- pool.intervalCounter = SCALE_UP_INTERVAL - 1;
- mock.expects('getMemoryInfo')
- .once()
- .returns(Promise.resolve({ freeBytes: toBytes(9.99), totalBytes: toBytes(10) }));
- await pool._autoscale();
- expect(pool.concurrency).to.be.eql((1 + (3 * SCALE_UP_MAX_STEP)) - 5);
-
- mock.verify();
- mock.restore();
- });
-
- it('[DEPRECATED] should not handle tasks added later when opts.finishWhenEmpty is not used', async () => {
- const tasks = [];
- const finished = [];
-
- // Start 3 tasks immediately.
- tasks.push(delayPromise(50).then(() => finished.push(0)));
- tasks.push(delayPromise(50).then(() => finished.push(1)));
- tasks.push(delayPromise(50).then(() => finished.push(2)));
-
- // Add 2 tasks after 500ms.
- setTimeout(() => tasks.push(delayPromise(50).then(() => finished.push(3))), 500);
- setTimeout(() => tasks.push(delayPromise(50).then(() => finished.push(4))), 500);
-
- // Run the pool and close it after 3s.
- const pool = new Apify.AutoscaledPool({
- maybeRunIntervalMillis: 10,
- minConcurrency: 3,
- workerFunction: () => tasks.pop(),
- });
- await pool.run();
-
- // Check finished tasks.
- expect(finished).to.be.eql([0, 1, 2]);
- });
-
- it('[DEPRECATED] should be possible let pool running forever with opts.finishWhenEmpty=false', async () => {
- const tasks = [];
- const finished = [];
-
- // Start 3 tasks immediately.
- tasks.push(delayPromise(50).then(() => finished.push(0)));
- tasks.push(delayPromise(50).then(() => finished.push(1)));
- tasks.push(delayPromise(50).then(() => finished.push(2)));
-
- // Add 2 tasks after 500ms.
- setTimeout(() => tasks.push(delayPromise(50).then(() => finished.push(3))), 500);
- setTimeout(() => tasks.push(delayPromise(50).then(() => finished.push(4))), 500);
-
- // Add 1 task after 2s.
- setTimeout(() => tasks.push(delayPromise(50).then(() => finished.push(5))), 2000);
-
- // Run the pool and close it after 3s.
- const pool = new Apify.AutoscaledPool({
- maybeRunIntervalMillis: 10,
- finishWhenEmpty: false,
- minConcurrency: 3,
- workerFunction: () => tasks.pop(),
- });
- setTimeout(() => pool.finish(), 3000);
- await pool.run();
-
- // Check finished tasks.
- expect(finished).to.be.eql([0, 1, 2, 3, 4, 5]);
- });
-});
-
-/* eslint-enable no-underscore-dangle */
diff --git a/test/autoscaling/autoscaled_pool.js b/test/autoscaling/autoscaled_pool.js
new file mode 100644
index 000000000..c42180134
--- /dev/null
+++ b/test/autoscaling/autoscaled_pool.js
@@ -0,0 +1,328 @@
+import chai, { expect } from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import _ from 'underscore';
+import { delayPromise } from 'apify-shared/utilities';
+import log from 'apify-shared/log';
+import AutoscaledPool from '../../build/autoscaling/autoscaled_pool';
+
+/* eslint-disable no-underscore-dangle */
+
+chai.use(chaiAsPromised);
+
+describe('AutoscaledPool', () => {
+ let logLevel;
+ before(() => {
+ logLevel = log.getLevel();
+ log.setLevel(log.LEVELS.ERROR);
+ });
+
+ after(() => {
+ log.setLevel(logLevel);
+ });
+
+ it('should work with concurrency 1', async () => {
+ const range = _.range(0, 10);
+ const result = [];
+
+ let isFinished = false;
+
+ const runTaskFunction = () => {
+ if (range.length === 1) {
+ isFinished = true;
+ }
+
+ return new Promise((resolve) => {
+ const item = range.shift();
+ result.push(item);
+ setTimeout(resolve, 5);
+ });
+ };
+
+ const pool = new AutoscaledPool({
+ minConcurrency: 1,
+ maxConcurrency: 1,
+ runTaskFunction,
+ isFinishedFunction: () => Promise.resolve(isFinished),
+ isTaskReadyFunction: () => Promise.resolve(!isFinished),
+ });
+ const startedAt = Date.now();
+ await pool.run();
+
+ expect(result).to.be.eql(_.range(0, 10));
+ expect(Date.now() - startedAt).to.be.within(50, 200);
+ });
+
+ it('should work with concurrency 10', async () => {
+ const range = _.range(0, 100);
+ const result = [];
+
+ let isFinished = false;
+
+ const runTaskFunction = () => {
+ if (range.length === 1) {
+ isFinished = true;
+ }
+
+ return new Promise((resolve) => {
+ const item = range.shift();
+ result.push(item);
+ setTimeout(resolve, 5);
+ });
+ };
+
+ const pool = new AutoscaledPool({
+ minConcurrency: 10,
+ maxConcurrency: 10,
+ runTaskFunction,
+ isFinishedFunction: () => Promise.resolve(isFinished),
+ isTaskReadyFunction: () => Promise.resolve(!isFinished),
+ });
+
+ const startedAt = Date.now();
+ await pool.run();
+
+ expect(result).to.be.eql(_.range(0, 100));
+ expect(Date.now() - startedAt).to.be.within(50, 200);
+ });
+
+ describe('should scale correctly', () => {
+ class MockSystemStatus {
+ constructor(okNow, okLately) {
+ this.okNow = okNow;
+ this.okLately = okLately;
+ this.getCurrentStatus = () => ({ isSystemIdle: this.okNow });
+ this.getHistoricalStatus = () => ({ isSystemIdle: this.okLately });
+ }
+ }
+
+ let pool;
+ let systemStatus;
+ const cb = () => {};
+ beforeEach(() => {
+ systemStatus = new MockSystemStatus(true, true);
+ pool = new AutoscaledPool({
+ minConcurrency: 1,
+ maxConcurrency: 100,
+ runTaskFunction: () => Promise.resolve(),
+ isFinishedFunction: () => Promise.resolve(false),
+ isTaskReadyFunction: () => Promise.resolve(true),
+ });
+ pool.systemStatus = systemStatus;
+ });
+
+ it('works with low values', () => {
+ pool._autoscale(cb);
+ expect(pool.desiredConcurrency).to.be.eql(2);
+
+ pool._autoscale(cb);
+ expect(pool.desiredConcurrency).to.be.eql(2); // because currentConcurrency is not high enough;
+
+ pool.currentConcurrency = 2;
+ pool._autoscale(cb);
+ expect(pool.desiredConcurrency).to.be.eql(3);
+
+ systemStatus.okNow = false; // this should have no effect
+ pool.currentConcurrency = 3;
+ pool._autoscale(cb);
+ expect(pool.desiredConcurrency).to.be.eql(4);
+
+ systemStatus.okLately = false;
+ pool._autoscale(cb);
+ expect(pool.desiredConcurrency).to.be.eql(3);
+ });
+
+ it('works with high values', () => {
+ // Should not scale because current concurrency is too low.
+ pool.desiredConcurrency = 50;
+ pool.currentConcurrency = Math.floor(pool.desiredConcurrency * pool.desiredConcurrencyRatio) - 1;
+ systemStatus.okLately = true;
+ pool._autoscale(cb);
+ expect(pool.desiredConcurrency).to.be.eql(50);
+
+ // Should scale because we bumped up current concurrency.
+ pool.currentConcurrency = Math.floor(pool.desiredConcurrency * pool.desiredConcurrencyRatio);
+ let newConcurrency = pool.desiredConcurrency + Math.ceil(pool.desiredConcurrency * pool.scaleUpStepRatio);
+ pool._autoscale(cb);
+ expect(pool.desiredConcurrency).to.be.eql(newConcurrency);
+
+ // Should scale down.
+ systemStatus.okLately = false;
+ newConcurrency = pool.desiredConcurrency - Math.ceil(pool.desiredConcurrency * pool.scaleDownStepRatio);
+ pool._autoscale(cb);
+ expect(pool.desiredConcurrency).to.be.eql(newConcurrency);
+ });
+ });
+
+ describe('should throw', () => {
+ // Turn off unnecessary error logging.
+ let originalLevel;
+ before(() => {
+ originalLevel = log.getLevel();
+ log.setLevel(log.LEVELS.OFF);
+ });
+
+ after(() => {
+ log.setLevel(originalLevel);
+ });
+
+ it('when some of the promises throws', async () => {
+ let counter = 0;
+ const runTaskFunction = () => {
+ counter++;
+
+ if (counter > 100) return;
+
+ if (counter === 100) {
+ const err = new Error('some-promise-error');
+
+ return new Promise((resolve, reject) => setTimeout(reject(err), 3));
+ }
+
+ return delayPromise(3);
+ };
+
+ const pool = new AutoscaledPool({
+ minConcurrency: 10,
+ maxConcurrency: 10,
+ runTaskFunction,
+ isFinishedFunction: () => Promise.resolve(false),
+ isTaskReadyFunction: () => Promise.resolve(true),
+ });
+
+ await expect(pool.run()).to.be.rejectedWith('some-promise-error');
+ });
+
+ it('when runTaskFunction throws', async () => {
+ const runTaskFunction = () => {
+ throw new Error('some-runtask-error');
+ };
+
+ const pool = new AutoscaledPool({
+ minConcurrency: 10,
+ maxConcurrency: 10,
+ runTaskFunction,
+ isFinishedFunction: () => Promise.resolve(false),
+ isTaskReadyFunction: () => Promise.resolve(true),
+ });
+
+
+ await expect(pool.run()).to.be.rejectedWith('some-runtask-error');
+ });
+ });
+
+
+ it('should not handle tasks added after isFinishedFunction returned true', async () => {
+ const tasks = [];
+ const finished = [];
+
+ let isFinished = false;
+
+ // Prepare 3 tasks.
+ tasks.push(() => delayPromise(10).then(() => finished.push(0)));
+ tasks.push(() => delayPromise(10).then(() => finished.push(1)));
+ tasks.push(() => delayPromise(10).then(() => finished.push(2)));
+
+ // Run the pool and close it after 3s.
+ const pool = new AutoscaledPool({
+ minConcurrency: 3,
+ runTaskFunction: () => {
+ const task = tasks.shift();
+ if (!task) return;
+ return task();
+ },
+ isFinishedFunction: () => Promise.resolve(isFinished),
+ isTaskReadyFunction: () => Promise.resolve(!isFinished),
+ });
+ pool.maybeRunIntervalMillis = 5;
+
+ const poolPromise = pool.run();
+ // This is an important part of the test to see if the tasks do not get
+ // stuck in a microtask cycle. Do not refactor this to some other scheduling.
+ setTimeout(() => {
+ isFinished = true;
+ }, 50);
+ // Add 2 tasks after 70ms.
+ setTimeout(() => tasks.push(() => delayPromise(5).then(() => finished.push(3))), 70);
+ setTimeout(() => tasks.push(() => delayPromise(5).then(() => finished.push(4))), 70);
+ // Make sure tasks were not added.
+ await delayPromise(100);
+
+ // Check finished tasks.
+ await poolPromise;
+ expect(finished).to.be.eql([0, 1, 2]);
+ });
+
+ it('should break and resume when the task queue is empty for a while', async () => {
+ const tasks = [];
+ const finished = [];
+
+ let isFinished = false;
+ let isTaskReady = true;
+
+ const getTask = (id) => {
+ return () => delayPromise(10).then(() => finished.push(id));
+ };
+
+ // Start 3 tasks immediately.
+ tasks.push(getTask(0));
+ tasks.push(getTask(1));
+ setTimeout(() => tasks.push(getTask(2)), 20);
+
+ setTimeout(() => {
+ isTaskReady = false;
+ }, 50);
+
+ // Add 2 tasks after 80ms.
+ setTimeout(() => tasks.push(getTask(3)), 80);
+ setTimeout(() => tasks.push(getTask(4)), 80);
+
+ // Remove tasks and set isTaskReady=true to accept a new task.
+ setTimeout(() => {
+ tasks.pop();
+ tasks.pop();
+ isTaskReady = true;
+ }, 120);
+
+ // Add one more task.
+ setTimeout(() => tasks.push(getTask(5)), 150);
+
+ // Finish.
+ setTimeout(() => {
+ isFinished = true;
+ }, 200);
+
+ // Run the pool and close it after 3s.
+ const pool = new AutoscaledPool({
+ minConcurrency: 3,
+ runTaskFunction: () => {
+ const task = tasks.shift();
+
+ if (!task) return;
+
+ return task();
+ },
+ isFinishedFunction: () => Promise.resolve(isFinished),
+ isTaskReadyFunction: () => Promise.resolve(!isFinished && isTaskReady),
+ });
+ pool.maybeRunIntervalMillis = 5;
+ await pool.run();
+
+ // Check finished tasks.
+ expect(finished).to.be.eql([0, 1, 2, 5]);
+ });
+
+ it('should work with loggingIntervalMillis = null', async () => {
+ const pool = new AutoscaledPool({
+ minConcurrency: 1,
+ maxConcurrency: 100,
+ runTaskFunction: () => Promise.resolve(),
+ isFinishedFunction: () => Promise.resolve(false),
+ isTaskReadyFunction: () => Promise.resolve(true),
+ loggingIntervalMillis: null,
+ });
+ pool._autoscale(() => {});
+ expect(pool.desiredConcurrency).to.be.eql(2);
+ });
+});
+
+/* eslint-enable no-underscore-dangle */
diff --git a/test/autoscaling/snapshotter.js b/test/autoscaling/snapshotter.js
new file mode 100644
index 000000000..4d2079647
--- /dev/null
+++ b/test/autoscaling/snapshotter.js
@@ -0,0 +1,190 @@
+import { expect } from 'chai';
+import log from 'apify-shared/log';
+import { ACTOR_EVENT_NAMES, ENV_VARS } from 'apify-shared/consts';
+import * as Apify from '../../build/index';
+import events from '../../build/events';
+import Snapshotter from '../../build/autoscaling/snapshotter';
+
+const toBytes = x => x * 1024 * 1024;
+
+describe('Snapshotter', () => {
+ let logLevel;
+ before(() => {
+ logLevel = log.getLevel();
+ log.setLevel(log.LEVELS.ERROR);
+ });
+
+ after(() => {
+ log.setLevel(logLevel);
+ });
+
+ it('should collect snapshots with some values', async () => {
+ const snapshotter = new Snapshotter();
+ await snapshotter.start();
+ await Apify.utils.sleep(1250);
+ await snapshotter.stop();
+ const memorySnapshots = snapshotter.getMemorySample();
+ const eventLoopSnapshots = snapshotter.getEventLoopSample();
+ const cpuSnapshots = snapshotter.getCpuSample();
+
+ expect(cpuSnapshots).to.be.an('array');
+ expect(cpuSnapshots).to.have.lengthOf(0);
+
+ expect(memorySnapshots).to.be.an('array');
+ expect(memorySnapshots).to.have.lengthOf(2);
+ memorySnapshots.forEach((ss) => {
+ expect(ss.createdAt).to.be.a('date');
+ expect(ss.isOverloaded).to.be.a('boolean');
+ expect(ss.totalBytes).to.be.a('number');
+ expect(ss.usedBytes).to.be.a('number');
+ expect(ss.freeBytes).to.be.a('number');
+ expect(ss.mainProcessBytes).to.be.a('number');
+ expect(ss.childProcessesBytes).to.be.a('number');
+ });
+
+ expect(eventLoopSnapshots).to.be.an('array');
+ expect(eventLoopSnapshots).to.have.lengthOf(4);
+ eventLoopSnapshots.forEach((ss) => {
+ expect(ss.createdAt).to.be.a('date');
+ expect(ss.isOverloaded).to.be.a('boolean');
+ expect(ss.exceededMillis).to.be.a('number');
+ });
+ });
+
+ it('should override default timers', async () => {
+ const options = {
+ eventLoopSnapshotIntervalSecs: 0.05,
+ memorySnapshotIntervalSecs: 0.1,
+ snapshotHistorySecs: 0.5,
+ };
+ const snapshotter = new Snapshotter(options);
+ await snapshotter.start();
+ await Apify.utils.sleep(600);
+ await snapshotter.stop();
+ const memorySnapshots = snapshotter.getMemorySample();
+ const eventLoopSnapshots = snapshotter.getEventLoopSample();
+ const cpuSnapshots = snapshotter.getCpuSample();
+
+ expect(cpuSnapshots).to.have.lengthOf(0);
+ expect(memorySnapshots.length).to.be.above(3);
+ expect(eventLoopSnapshots.length).to.be.above(9);
+ });
+
+ it('should collect CPU events on Platform', async () => {
+ process.env[ENV_VARS.IS_AT_HOME] = '1';
+ let count = 0;
+ const emitAndWait = async (delay) => {
+ events.emit(ACTOR_EVENT_NAMES.CPU_INFO, {
+ isCpuOverloaded: count % 2 === 0,
+ createdAt: (new Date()).toISOString(),
+ });
+ count++;
+ await Apify.utils.sleep(delay);
+ };
+
+ try {
+ const snapshotter = new Snapshotter();
+ await snapshotter.start();
+ await emitAndWait(10);
+ await emitAndWait(10);
+ await emitAndWait(10);
+ await emitAndWait(0);
+ await snapshotter.stop();
+ const cpuSnapshots = snapshotter.getCpuSample();
+
+ expect(cpuSnapshots).to.have.lengthOf(4);
+ cpuSnapshots.forEach((ss, i) => {
+ expect(ss.createdAt).to.be.a('date');
+ expect(ss.isOverloaded).to.be.a('boolean');
+ expect(ss.isOverloaded).to.be.eql(i % 2 === 0);
+ });
+ } finally {
+ delete process.env[ENV_VARS.IS_AT_HOME];
+ }
+ });
+
+ it('correctly marks eventLoopOverloaded', async () => {
+ const options = {
+ eventLoopSnapshotIntervalSecs: 0.01,
+ maxBlockedMillis: 10,
+ };
+ const TICK = options.eventLoopSnapshotIntervalSecs * 1000;
+ const DELAY = 75;
+
+ const snapshotter = new Snapshotter(options);
+ await snapshotter.start();
+ await Apify.utils.sleep(3 * TICK);
+ const start = Date.now();
+ let now = Date.now();
+ while (now < start + DELAY) {
+ now = Date.now();
+ }
+ await Apify.utils.sleep(3 * TICK);
+ await snapshotter.stop();
+ const eventLoopSnapshots = snapshotter.getEventLoopSample();
+ expect(eventLoopSnapshots.length).to.be.above(6);
+ let overloadedCount = 0;
+ eventLoopSnapshots.forEach((ss, idx) => {
+ if (ss.isOverloaded) {
+ overloadedCount++;
+ const prev = eventLoopSnapshots[idx - 1].createdAt;
+ const curr = ss.createdAt;
+ const next = eventLoopSnapshots[idx + 1].createdAt;
+ expect(curr - prev).to.be.above(DELAY - 1);
+ expect(next - curr).to.be.within(TICK - 1, TICK + snapshotter.maxBlockedMillis);
+ expect(ss.exceededMillis).to.be.within(1, DELAY - snapshotter.maxBlockedMillis);
+ } else {
+ expect(ss.exceededMillis).to.be.eql(0);
+ }
+ });
+ expect(overloadedCount).to.be.eql(1);
+ });
+
+ it('correctly marks memoryOverloaded', async () => {
+ const options = {
+ memorySnapshotIntervalSecs: 0.1,
+ maxMemoryMbytes: 20,
+ };
+
+ const snapshotter = new Snapshotter(options);
+ await snapshotter.start();
+ await Apify.utils.sleep(199);
+ snapshotter.maxMemoryBytes = toBytes(1000); // Override memory to get an OK reading.
+ await Apify.utils.sleep(199);
+ await snapshotter.stop();
+ const memorySnapshots = snapshotter.getMemorySample();
+
+ expect(memorySnapshots.length).to.be.above(2);
+ expect(memorySnapshots[0].isOverloaded).to.be.eql(true);
+ expect(memorySnapshots[1].isOverloaded).to.be.eql(true);
+ expect(memorySnapshots[2].isOverloaded).to.be.eql(false);
+ });
+
+ it('.get...Sample limits amount of samples', async () => {
+ const SAMPLE_SIZE_MILLIS = 120;
+ const options = {
+ eventLoopSnapshotIntervalSecs: 0.01,
+ memorySnapshotIntervalSecs: 0.01,
+ };
+ const snapshotter = new Snapshotter(options);
+ await snapshotter.start();
+ await Apify.utils.sleep(300);
+ await snapshotter.stop();
+ const memorySnapshots = snapshotter.getMemorySample();
+ const eventLoopSnapshots = snapshotter.getEventLoopSample();
+ const memorySample = snapshotter.getMemorySample(SAMPLE_SIZE_MILLIS);
+ const eventLoopSample = snapshotter.getEventLoopSample(SAMPLE_SIZE_MILLIS);
+
+ expect(memorySnapshots.length).to.be.above(memorySample.length);
+ expect(eventLoopSnapshots.length).to.be.above(eventLoopSample.length);
+ for (let i = 0; i < eventLoopSample.length; i++) {
+ const sample = eventLoopSample[eventLoopSample.length - 1 - i];
+ const snapshot = eventLoopSnapshots[eventLoopSnapshots.length - 1 - i];
+ expect(sample).to.be.eql(snapshot);
+ }
+ const diffBetween = eventLoopSample[eventLoopSample.length - 1].createdAt - eventLoopSnapshots[eventLoopSnapshots.length - 1].createdAt;
+ const diffWithin = eventLoopSample[0].createdAt - eventLoopSample[eventLoopSample.length - 1].createdAt;
+ expect(diffBetween).to.be.below(SAMPLE_SIZE_MILLIS);
+ expect(diffWithin).to.be.below(SAMPLE_SIZE_MILLIS);
+ });
+});
diff --git a/test/autoscaling/system_status.js b/test/autoscaling/system_status.js
new file mode 100644
index 000000000..d940fdeb9
--- /dev/null
+++ b/test/autoscaling/system_status.js
@@ -0,0 +1,184 @@
+import { expect } from 'chai';
+import log from 'apify-shared/log';
+import SystemStatus from '../../build/autoscaling/system_status';
+import Snapshotter from '../../build/autoscaling/snapshotter';
+
+describe('SystemStatus', () => {
+ let logLevel;
+ before(() => {
+ logLevel = log.getLevel();
+ log.setLevel(log.LEVELS.ERROR);
+ });
+
+ after(() => {
+ log.setLevel(logLevel);
+ });
+
+ class MockSnapshotter {
+ constructor(memSnapshots, loopSnapshots, cpuSnapshots) {
+ this.memSnapshots = memSnapshots;
+ this.loopSnapshots = loopSnapshots;
+ this.cpuSnapshots = cpuSnapshots;
+ }
+
+ getMemorySample(offset) {
+ return this.memSnapshots.slice(-offset);
+ }
+
+ getEventLoopSample(offset) {
+ return this.loopSnapshots.slice(-offset);
+ }
+
+ getCpuSample(offset) {
+ return this.cpuSnapshots.slice(-offset);
+ }
+ }
+
+ const generateSnapsSync = (percentage, overloaded) => {
+ const snaps = [];
+ for (let i = 0; i < 100; i++) {
+ snaps.push({
+ createdAt: new Date(),
+ isOverloaded: i < percentage ? overloaded : !overloaded,
+ });
+ }
+ return snaps;
+ };
+
+ it('should return OK for OK snapshots', () => {
+ const snaps = generateSnapsSync(100, false);
+ const systemStatus = new SystemStatus({
+ snapshotter: new MockSnapshotter(snaps, snaps, snaps),
+ });
+ expect(systemStatus.getCurrentStatus().isSystemIdle).to.be.eql(true);
+ expect(systemStatus.getHistoricalStatus().isSystemIdle).to.be.eql(true);
+ });
+
+ it('should return overloaded for overloaded snapshots', () => {
+ const snaps = generateSnapsSync(100, true);
+ const systemStatus = new SystemStatus({
+ snapshotter: new MockSnapshotter(snaps, snaps, snaps),
+ });
+ expect(systemStatus.getCurrentStatus().isSystemIdle).to.be.eql(false);
+ expect(systemStatus.getHistoricalStatus().isSystemIdle).to.be.eql(false);
+ });
+
+ it('should work with some samples empty', () => {
+ const snaps = generateSnapsSync(100, true);
+ let systemStatus = new SystemStatus({
+ snapshotter: new MockSnapshotter(snaps, [], []),
+ });
+ expect(systemStatus.getCurrentStatus().isSystemIdle).to.be.eql(false);
+ expect(systemStatus.getHistoricalStatus().isSystemIdle).to.be.eql(false);
+ systemStatus = new SystemStatus({
+ snapshotter: new MockSnapshotter([], snaps, []),
+ });
+ expect(systemStatus.getCurrentStatus().isSystemIdle).to.be.eql(false);
+ expect(systemStatus.getHistoricalStatus().isSystemIdle).to.be.eql(false);
+ systemStatus = new SystemStatus({
+ snapshotter: new MockSnapshotter([], [], snaps),
+ });
+ expect(systemStatus.getCurrentStatus().isSystemIdle).to.be.eql(false);
+ expect(systemStatus.getHistoricalStatus().isSystemIdle).to.be.eql(false);
+ systemStatus = new SystemStatus({
+ snapshotter: new MockSnapshotter([], [], []),
+ });
+ expect(systemStatus.getCurrentStatus().isSystemIdle).to.be.eql(true);
+ expect(systemStatus.getHistoricalStatus().isSystemIdle).to.be.eql(true);
+ });
+
+ it('should overload if only one sample is overloaded', () => {
+ const overloaded = generateSnapsSync(100, true);
+ const fine = generateSnapsSync(100, false);
+ let systemStatus = new SystemStatus({
+ snapshotter: new MockSnapshotter(fine, fine, overloaded),
+ });
+ expect(systemStatus.getCurrentStatus().isSystemIdle).to.be.eql(false);
+ expect(systemStatus.getHistoricalStatus().isSystemIdle).to.be.eql(false);
+ systemStatus = new SystemStatus({
+ snapshotter: new MockSnapshotter(fine, overloaded, fine),
+ });
+ expect(systemStatus.getCurrentStatus().isSystemIdle).to.be.eql(false);
+ expect(systemStatus.getHistoricalStatus().isSystemIdle).to.be.eql(false);
+ systemStatus = new SystemStatus({
+ snapshotter: new MockSnapshotter(overloaded, fine, fine),
+ });
+ expect(systemStatus.getCurrentStatus().isSystemIdle).to.be.eql(false);
+ expect(systemStatus.getHistoricalStatus().isSystemIdle).to.be.eql(false);
+ });
+
+ it('should overload when threshold is crossed', () => {
+ const snaps = generateSnapsSync(50, true);
+ const systemStatus = new SystemStatus({
+ snapshotter: new MockSnapshotter(snaps, snaps, snaps),
+ maxMemoryOverloadedRatio: 0.5,
+ maxEventLoopOverloadedRatio: 0.5,
+ maxCpuOverloadedRatio: 0.5,
+ });
+ expect(systemStatus.getCurrentStatus().isSystemIdle).to.be.eql(true);
+ expect(systemStatus.getHistoricalStatus().isSystemIdle).to.be.eql(true);
+
+ systemStatus.maxMemoryOverloadedRatio = 0.49;
+ systemStatus.maxEventLoopOverloadedRatio = 0.49;
+ systemStatus.maxEventLoopOverloadedRatio = 0.49;
+ expect(systemStatus.getCurrentStatus().isSystemIdle).to.be.eql(false);
+ expect(systemStatus.getHistoricalStatus().isSystemIdle).to.be.eql(false);
+
+ systemStatus.maxMemoryOverloadedRatio = 0.5;
+ systemStatus.maxEventLoopOverloadedRatio = 0.5;
+ systemStatus.maxEventLoopOverloadedRatio = 0.49;
+ expect(systemStatus.getCurrentStatus().isSystemIdle).to.be.eql(false);
+ expect(systemStatus.getHistoricalStatus().isSystemIdle).to.be.eql(false);
+
+ systemStatus.maxMemoryOverloadedRatio = 1;
+ systemStatus.maxEventLoopOverloadedRatio = 1;
+ systemStatus.maxEventLoopOverloadedRatio = 1;
+ expect(systemStatus.getCurrentStatus().isSystemIdle).to.be.eql(true);
+ expect(systemStatus.getHistoricalStatus().isSystemIdle).to.be.eql(true);
+ });
+
+ it('should show different values for now and lately', () => {
+ let snaps = generateSnapsSync(95, false);
+ let systemStatus = new SystemStatus({
+ snapshotter: new MockSnapshotter(snaps, snaps, snaps),
+ maxMemoryOverloadedRatio: 0.5,
+ maxEventLoopOverloadedRatio: 0.5,
+ maxCpuOverloadedRatio: 0.5,
+ });
+ systemStatus.currentHistorySecs = 5;
+ expect(systemStatus.getCurrentStatus().isSystemIdle).to.be.eql(false);
+ expect(systemStatus.getHistoricalStatus().isSystemIdle).to.be.eql(true);
+
+ systemStatus.currentHistorySecs = 10;
+ expect(systemStatus.getCurrentStatus().isSystemIdle).to.be.eql(false);
+ expect(systemStatus.getHistoricalStatus().isSystemIdle).to.be.eql(true);
+
+ systemStatus.currentHistorySecs = 12;
+ expect(systemStatus.getCurrentStatus().isSystemIdle).to.be.eql(true);
+ expect(systemStatus.getHistoricalStatus().isSystemIdle).to.be.eql(true);
+
+ snaps = generateSnapsSync(95, true);
+ systemStatus = new SystemStatus({
+ snapshotter: new MockSnapshotter(snaps, snaps, snaps),
+ maxMemoryOverloadedRatio: 0.5,
+ maxEventLoopOverloadedRatio: 0.5,
+ maxCpuOverloadedRatio: 0.5,
+ });
+ systemStatus.currentHistorySecs = 5;
+ expect(systemStatus.getCurrentStatus().isSystemIdle).to.be.eql(true);
+ expect(systemStatus.getHistoricalStatus().isSystemIdle).to.be.eql(false);
+
+ systemStatus.currentHistorySecs = 10;
+ expect(systemStatus.getCurrentStatus().isSystemIdle).to.be.eql(true);
+ expect(systemStatus.getHistoricalStatus().isSystemIdle).to.be.eql(false);
+
+ systemStatus.currentHistorySecs = 12;
+ expect(systemStatus.getCurrentStatus().isSystemIdle).to.be.eql(false);
+ expect(systemStatus.getHistoricalStatus().isSystemIdle).to.be.eql(false);
+ });
+
+ it('creates a snapshotter when none is passed', () => {
+ const systemStatus = new SystemStatus();
+ expect(systemStatus.snapshotter).to.be.an.instanceof(Snapshotter);
+ });
+});
diff --git a/test/basic_crawler.js b/test/basic_crawler.js
index ea3f6dd93..7127d33c2 100644
--- a/test/basic_crawler.js
+++ b/test/basic_crawler.js
@@ -45,7 +45,7 @@ describe('BasicCrawler', () => {
await basicCrawler.run();
expect(processed).to.be.eql(sources);
- expect(Date.now() - startedAt).to.be.within(200, 400);
+ expect(Date.now() - startedAt).to.be.within(200, 500);
expect(await requestList.isFinished()).to.be.eql(true);
expect(await requestList.isEmpty()).to.be.eql(true);
});
@@ -392,15 +392,17 @@ describe('BasicCrawler', () => {
const basicCrawler = new Apify.BasicCrawler({
requestQueue,
- minConcurrency: 1,
- maxConcurrency: 1,
+ autoscaledPoolOptions: {
+ minConcurrency: 1,
+ maxConcurrency: 1,
+ isFinishedFunction: () => {
+ return Promise.resolve(isFinished);
+ },
+ },
handleRequestFunction: async ({ request }) => {
await delayPromise(10);
processed.push(request);
},
- isFinishedFunction: () => {
- return Promise.resolve(isFinished);
- },
});
// Speed up the test
diff --git a/test/cheerio_crawler.js b/test/cheerio_crawler.js
index 7430f42b7..c422a5b57 100644
--- a/test/cheerio_crawler.js
+++ b/test/cheerio_crawler.js
@@ -168,4 +168,94 @@ describe('CheerioCrawler', () => {
expect(request.userData.title).to.be.eql(request.url[request.url.length - 1]);
});
});
+
+ describe('should timeout', () => {
+ let ll;
+ before(() => {
+ ll = log.getLevel();
+ log.setLevel(log.LEVELS.OFF);
+ });
+
+ after(() => {
+ log.setLevel(ll);
+ });
+
+ it('should timeout after requestTimeoutSecs', async () => {
+ const sources = [
+ { url: 'http://example.com/?q=0' },
+ { url: 'http://example.com/?q=1' },
+ { url: 'http://example.com/?q=2' },
+ ];
+ const processed = [];
+ const failed = [];
+ const requestList = new Apify.RequestList({ sources });
+ const requestFunction = async () => {
+ await delayPromise(3000);
+ return '<html><head></head><body>Body</body></html>';
+ };
+ const handlePageFunction = async ({ request }) => {
+ processed.push(request);
+ };
+
+ const cheerioCrawler = new Apify.CheerioCrawler({
+ requestList,
+ requestTimeoutSecs: 0.05,
+ maxRequestRetries: 1,
+ minConcurrency: 2,
+ maxConcurrency: 2,
+ handlePageFunction,
+ requestFunction,
+ handleFailedRequestFunction: ({ request }) => failed.push(request),
+ });
+
+ await requestList.initialize();
+ await cheerioCrawler.run();
+
+ expect(processed).to.have.lengthOf(0);
+ expect(failed).to.have.lengthOf(3);
+
+ failed.forEach((request) => {
+ expect(request.errorMessages).to.have.lengthOf(2);
+ expect(request.errorMessages[0]).to.include('requestFunction timed out');
+ expect(request.errorMessages[1]).to.include('requestFunction timed out');
+ });
+ });
+
+ it('should timeout after handlePageTimeoutSecs', async () => {
+ const sources = [
+ { url: 'http://example.com/?q=0' },
+ { url: 'http://example.com/?q=1' },
+ { url: 'http://example.com/?q=2' },
+ ];
+ const processed = [];
+ const failed = [];
+ const requestList = new Apify.RequestList({ sources });
+ const handlePageFunction = async ({ request }) => {
+ await delayPromise(3000);
+ processed.push(request);
+ };
+
+ const cheerioCrawler = new Apify.CheerioCrawler({
+ requestList,
+ handlePageTimeoutSecs: 0.05,
+ maxRequestRetries: 1,
+ minConcurrency: 2,
+ maxConcurrency: 2,
+ handlePageFunction,
+ handleFailedRequestFunction: ({ request }) => failed.push(request),
+ });
+
+ await requestList.initialize();
+ await cheerioCrawler.run();
+
+ expect(processed).to.have.lengthOf(0);
+ expect(failed).to.have.lengthOf(3);
+
+ failed.forEach((request) => {
+ expect(request.errorMessages).to.have.lengthOf(2);
+ expect(request.errorMessages[0]).to.include('handlePageFunction timed out');
+ expect(request.errorMessages[1]).to.include('handlePageFunction timed out');
+ });
+ });
+ });
});
diff --git a/test/utils.js b/test/utils.js
index 21534301a..c59b31b08 100644
--- a/test/utils.js
+++ b/test/utils.js
@@ -318,6 +318,18 @@ describe('utils.avg()', () => {
});
});
+describe('utils.weightedAvg()', () => {
+ it('works', () => {
+ expect(utils.weightedAvg([10, 10, 10], [1, 1, 1])).to.be.eql(10);
+ expect(utils.weightedAvg([5, 10, 15], [1, 1, 1])).to.be.eql(10);
+ expect(utils.weightedAvg([10, 10, 10], [0.5, 1, 1.5])).to.be.eql(10);
+ expect(utils.weightedAvg([29, 35, 89], [13, 91, 3])).to.be.eql(((29 * 13) + (35 * 91) + (89 * 3)) / (13 + 91 + 3));
+ expect(utils.weightedAvg([], [])).to.be.eql(NaN);
+ expect(utils.weightedAvg([1], [0])).to.be.eql(NaN);
+ expect(utils.weightedAvg([], [1])).to.be.eql(NaN);
+ });
+});
+
describe('Apify.utils.sleep()', () => {
it('works', () => {
let timeBefore;