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.

Implement solution, ensure original tests pass

Ondra Urbanae3b5d9a44d0
diff --git a/.babelrc b/.babelrc
index 9d0e8d967..3f77b8750 100644
--- a/.babelrc
+++ b/.babelrc
@@ -1,8 +1,8 @@
{
"presets": [
- ["babel-preset-env", {
+ ["@babel/preset-env", {
"targets": {
- "node": "8.0.0"
+ "node": "8.14.0"
}
}]
]
diff --git a/package.json b/package.json
index b66352053..00adc3bd0 100644
--- a/package.json
+++ b/package.json
@@ -3,7 +3,7 @@
"version": "0.10.0",
"description": "The scalable web crawling and scraping library for JavaScript. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.",
"engines": {
- "node": ">=8.0.0"
+ "node": ">=8.14.0"
},
"main": "build/index.js",
"keywords": [
@@ -41,7 +41,7 @@
"build": "rm -rf ./build && babel src --out-dir build",
"build-docs": "npm run clean && npm run build && node ./website/tools/build_docs.js",
"build-readme": "node ./tools/build_readme.js",
- "test": "npm run build && nyc --reporter=html --reporter=text mocha --timeout 60000 --require babel-core/register --recursive --exit",
+ "test": "npm run build && nyc --reporter=html --reporter=text mocha --timeout 60000 --require @babel/register --recursive --exit",
"prepare": "npm run build",
"prepublishOnly": "(test $RUNNING_FROM_SCRIPT || (echo \"You must use publish.sh instead of 'npm publish' directly!\"; exit 1)) && npm test && npm run lint",
"clean": "rm -rf build",
@@ -68,9 +68,11 @@
"xregexp": "^4.2.0"
},
"devDependencies": {
- "babel-cli": "^6.26.0",
- "babel-polyfill": "^6.26.0",
- "babel-preset-env": "^1.7.0",
+ "@babel/cli": "^7.0.0",
+ "@babel/core": "^7.0.0",
+ "@babel/polyfill": "^7.0.0",
+ "@babel/preset-env": "^7.0.0",
+ "@babel/register": "^7.0.0",
"basic-auth-parser": "^0.0.2",
"chai": "^4.2.0",
"chai-as-promised": "^7.1.1",
diff --git a/src/request_list.js b/src/request_list.js
index 975f83408..c37910429 100644
--- a/src/request_list.js
+++ b/src/request_list.js
@@ -1,24 +1,16 @@
import { checkParamOrThrow } from 'apify-client/build/utils';
import log from 'apify-shared/log';
import _ from 'underscore';
-import Promise from 'bluebird';
+import { ENV_VARS } from 'apify-shared/consts';
import { ACTOR_EVENT_NAMES_EX } from './constants';
import Request from './request';
import events from './events';
-import { getFirstKey, publicUtils } from './utils';
+import { ensureTokenOrLocalStorageEnvExists, getFirstKey, openLocalStorage, openRemoteStorage, publicUtils } from './utils';
import { getValue, setValue } from './key_value_store';
+import { RequestQueue, RequestQueueLocal } from './request_queue';
-/**
- * Helper function that validates unique.
- * Throws an error if uniqueKey is not nonempty string.
- *
- * @ignore
- */
-const ensureUniqueKeyValid = (uniqueKey) => {
- if (typeof uniqueKey !== 'string' || !uniqueKey) {
- throw new Error('Request object\'s uniqueKey must be a non-empty string');
- }
-};
+const STATE_PERSISTENCE_KEY = 'REQUEST_LIST_STATE';
+const SOURCES_PERSISTENCE_KEY = 'REQUEST_LIST_SOURCES';
/**
* Represents a static list of URLs to crawl.
@@ -39,8 +31,8 @@ const ensureUniqueKeyValid = (uniqueKey) => {
* Unlike {@link RequestQueue}, `RequestList` is static but it can contain even millions of URLs.
*
* `RequestList` has an internal state where it stores information about which requests were already handled,
- * which are in progress and which were reclaimed. The state might be automatically persisted to the default
- * key-value store by setting the `persistStateKey` option o that if the Node.js process is restarted,
+ * which are in progress and which were reclaimed. The state may be automatically persisted to the default
+ * key-value store by setting the `stateKeyPrefix` option so that if the Node.js process is restarted,
* the crawling can continue where it left off. For more details, see {@link KeyValueStore}.
*
* **Example usage:**
@@ -56,7 +48,7 @@ const ensureUniqueKeyValid = (uniqueKey) => {
* // Note that all URLs must start with http:// or https://
* { requestsFromUrl: 'http://www.example.com/my-url-list.txt', userData: { isFromUrl: true } },
* ],
- * persistStateKey: 'my-crawling-state'
+ * stateKeyPrefix: 'my-state'
* });
*
* // This call loads and parses the URLs from the remote file.
@@ -91,17 +83,11 @@ const ensureUniqueKeyValid = (uniqueKey) => {
* { method: 'POST', requestsFromUrl: 'http://example.com/urls.txt' },
* ]
* ```
- * @param {String} [options.persistStateKey]
- * Identifies the key in the default key-value store under which the `RequestList` persists its
- * state. State represents a position of the last scraped request in the list. If this is set then `RequestList`
- * persists this state in regular intervals and loads the state from there in case it is restarted due to an error or system reboot.
- *
- * **IMPORTANT:**
- * The state represents only a pointer/index of a request in the list. The full contents of the list are not persisted.
- * Therefore, the user is responsible for either persisting the list on her own or a consistent order of the requests
- * in the list must be preserved. This is especially important when downloading a live list of URLs from a remote resource,
- * since the change in the source URL list would change the resulting `RequestList` on error/restart and the state
- * of crawling will be impossible to restore, resulting in an error.
+ * @param {String} [options.stateKeyPrefix]
+ * Identifies the keys in the default key-value store under which the `RequestList` persists its
+ * initial sources and current state. State represents a position of the last scraped request in the list.
+ * If this is set then `RequestList`persists all of its sources and the state in regular intervals
+ * to key value store and loads the state from there in case it is restarted due to an error or system reboot.
* @param {Object} [options.state]
* The state object that the `RequestList` will be initialized from.
* It is in the form as returned by `RequestList.getState()`, such as follows:
@@ -118,7 +104,7 @@ const ensureUniqueKeyValid = (uniqueKey) => {
* ```
*
* Note that the preferred (and simpler) way to persist the state of crawling of the `RequestList`
- * is to use the `persistStateKey` parameter instead.
+ * is to use the `stateKeyPrefix` parameter instead.
* @param {Boolean} [options.keepDuplicateUrls=false]
* By default, `RequestList` will deduplicate the provided URLs. Default deduplication is based
* on the `uniqueKey` property of passed source {@link Request} objects.
@@ -130,25 +116,26 @@ const ensureUniqueKeyValid = (uniqueKey) => {
* Setting `keepDuplicateUrls` to `true` will append an additional identifier to the `uniqueKey`
* of each request that does not already include a `uniqueKey`. Therefore, duplicate
* URLs will be kept in the list. It does not protect the user from having duplicates in user set
- * `uniqueKey`s however. It is the user's responsibility to ensure uniqueness of their unique keys,
+ * `uniqueKey`s however. It is the user's responsibility to ensure uniqueness of their unique keys
* if they wish to keep more than just a single copy in the `RequestList`.
*/
class RequestList {
constructor(options = {}) {
checkParamOrThrow(options, 'options', 'Object');
- const { sources, persistStateKey, state, keepDuplicateUrls = false } = options;
+ const { sources, persistStateKey, stateKeyPrefix, state, keepDuplicateUrls = false } = options;
+
+ // TODO Deprecation. Remove with 1.0.0.
+ if (persistStateKey) log.warning('RequestList: options.persistStateKey is deprecated. Use options.stateKeyPrefix instead.');
+ if (persistStateKey && stateKeyPrefix) log.warning('RequestList: Using options.stateKeyPrefix instead of options.persistStateKey.');
checkParamOrThrow(sources, 'options.sources', 'Array');
checkParamOrThrow(state, 'options.state', 'Maybe Object');
- checkParamOrThrow(persistStateKey, 'options.persistStateKey', 'Maybe String');
+ checkParamOrThrow(stateKeyPrefix, 'options.persistStateKey', 'Maybe String');
+ checkParamOrThrow(stateKeyPrefix, 'options.stateKeyPrefix', 'Maybe String');
+ if (stateKeyPrefix && !stateKeyPrefix.length) throw new Error('Parameter options.stateKeyPrefix must not be an empty string.');
checkParamOrThrow(keepDuplicateUrls, 'options.keepDuplicateUrls', 'Maybe Boolean');
- // We will initialize everything from this state in this.initialize();
- this.initialStatePromise = persistStateKey && !state
- ? getValue(persistStateKey)
- : Promise.resolve(state);
-
// Array of all requests from all sources, in the order as they appeared in sources.
// All requests in the array have distinct uniqueKey!
this.requests = [];
@@ -168,16 +155,39 @@ class RequestList {
// Note that reclaimedRequests is always a subset of inProgressRequests!
this.reclaimed = {};
- // If this key is set then we persist url list into default key-value store under this key.
+ // TODO Deprecated.
this.persistStateKey = persistStateKey;
- this.isStatePersisted = true;
+
+ // If the stateKeyPrefix is set then we persist url list and state into default key-value store under keys with this prefix.
+ this.shouldPersist = !!stateKeyPrefix;
+ this.stateKey = null;
+ this.sourcesKey = null;
+ if (this.shouldPersist) {
+ this.stateKey = `${stateKeyPrefix}-${STATE_PERSISTENCE_KEY}`;
+ this.sourcesKey = `${stateKeyPrefix}-${SOURCES_PERSISTENCE_KEY}`;
+ }
// If this option is set then all requests will get a pre-generated unique ID and duplicate URLs will be kept in the list.
this.keepDuplicateUrls = keepDuplicateUrls;
+ this.isCurrentStatePersisted = true;
this.isLoading = false;
this.isInitialized = false;
this.sources = sources;
+
+ // We will initialize everything from this state in this.initialize();
+ if (state) {
+ this.initialStatePromise = Promise.resolve([state]);
+ } else if (stateKeyPrefix) {
+ this.initialStatePromise = Promise.all([
+ getValue(this.stateKey),
+ getValue(this.sourcesKey),
+ ]);
+ } else if (persistStateKey) {
+ this.initialStatePromise = Promise.all([getValue(persistStateKey)]);
+ } else {
+ this.initialStatePromise = Promise.resolve([]);
+ }
}
/**
@@ -186,90 +196,125 @@ class RequestList {
*
* @returns {Promise}
*/
- initialize() {
+ async initialize() {
if (this.isLoading) {
throw new Error('RequestList sources are already loading or were loaded.');
}
this.isLoading = true;
+ const [state, sources] = await this.initialStatePromise;
+
+ // If there are no sources, it just means that we've not persisted any (yet).
+ const actualSources = sources || this.sources;
+
// We'll load all sources in sequence to ensure that they get loaded in the right order.
- return Promise
- .mapSeries(this.sources, (source) => {
- // TODO: One promise per each item is too much overheads, we could cluster items into single Promise.
- return source.requestsFromUrl
- ? this._addRequestsFromUrl(source)
- : Promise.resolve(this._addRequest(source));
- })
- .then(() => this.initialStatePromise)
- .then((state) => {
- if (!state) return;
-
- // Restore state
- if (typeof state.nextIndex !== 'number' || state.nextIndex < 0) {
- throw new Error('The state object is invalid: nextIndex must be a non-negative number.');
- }
- if (state.nextIndex > this.requests.length) {
- throw new Error('The state object is not consistent with RequestList: too few requests loaded.');
- }
- if (state.nextIndex < this.requests.length
- && this.requests[state.nextIndex].uniqueKey !== state.nextUniqueKey) {
- throw new Error('The state object is not consistent with RequestList: the order of URLs seems to have changed.');
- }
-
- const deleteFromInProgress = [];
- _.keys(state.inProgress).forEach((uniqueKey) => {
- const index = this.uniqueKeyToIndex[uniqueKey];
- if (typeof index !== 'number') {
- throw new Error('The state object is not consistent with RequestList: unknown uniqueKey is present in the state.');
- }
- if (index >= state.nextIndex) {
- deleteFromInProgress.push(uniqueKey);
- }
- });
-
- // WORKAROUND:
- // It happened to some users that state object contained something like:
- // {
- // "nextIndex": 11308,
- // "nextUniqueKey": "https://www.anychart.com",
- // "inProgress": {
- // "https://www.ams360.com": true,
- // ...
- // "https://www.anychart.com": true,
- // }
- // Which then caused error "The request is not being processed (uniqueKey: https://www.anychart.com)"
- // As a workaround, we just remove all inProgress requests whose index >= nextIndex,
- // since they will be crawled again.
- if (deleteFromInProgress.length) {
- log.warning('RequestList\'s in-progress field is not consistent, skipping invalid in-progress entries', { deleteFromInProgress });
- _.each(deleteFromInProgress, (uniqueKey) => {
- delete state.inProgress[uniqueKey];
- });
- }
-
- this.nextIndex = state.nextIndex;
- this.inProgress = state.inProgress;
-
- // All in-progress requests need to be recrawled
- this.reclaimed = _.clone(this.inProgress);
- })
- .then(() => {
- this.isInitialized = true;
-
- if (!this.persistStateKey) return;
-
- events.on(ACTOR_EVENT_NAMES_EX.PERSIST_STATE, () => {
- if (this.isStatePersisted) return;
-
- return setValue(this.persistStateKey, this.getState())
- .then(() => {
- this.isStatePersisted = true;
- })
- .catch((err) => {
- log.exception(err, 'RequestList: Cannot persist state', { persistStateKey: this.persistStateKey });
- });
- });
+ for (const source of actualSources) {
+ if (source.requestsFromUrl) await this._addRequestsFromUrl(source);
+ else this._addRequest(source);
+ }
+
+ this._restoreState(state);
+ this.isInitialized = true;
+ // TODO refactor after persistStateKey removal.
+ if (this.shouldPersist) await this._persistSources();
+ if (this.shouldPersist || this.persistStateKey) {
+ events.on(ACTOR_EVENT_NAMES_EX.PERSIST_STATE, this.persistState.bind(this));
+ }
+ }
+
+ /**
+ * Persists the current state of the `RequestList` into the default {@link KeyValueStore}.
+ * The state is persisted automatically in regular intervals, but calling this method manually
+ * is useful in cases where you want to have the most current state available after you pause
+ * or stop fetching its requests. For example after you pause or abort a crawl. Or just before
+ * a server migration.
+ *
+ * @return {Promise}
+ */
+ async persistState() {
+ // TODO refactor after persistStateKey removal.
+ if (!this.shouldPersist && !this.persistStateKey) {
+ throw new Error('RequestList: Cannot persist state. options.stateKeyPrefix is not set.');
+ }
+ const key = this.stateKey || this.persistStateKey;
+ if (this.isCurrentStatePersisted) return;
+ try {
+ await setValue(key, this.getState());
+ this.isCurrentStatePersisted = true;
+ } catch (err) {
+ log.exception(err, 'RequestList attempted to persist state, but failed.');
+ }
+ }
+
+ /**
+ * Unlike persistState(), this is used only internally, since the sources
+ * are automatically persisted at RequestList initialization (if the prefix is set),
+ * but there's no reason to persist it again afterwards, because RequestList is immutable.
+ *
+ * @return {Promise}
+ * @ignore
+ */
+ async _persistSources() {
+ return setValue(this.sourcesKey, this.sources);
+ }
+
+ /**
+ * Restores RequestList state from a state object.
+ *
+ * @param {Object} state
+ * @ignore
+ */
+ _restoreState(state) {
+ // If there's no state it means we've not persisted any (yet).
+ if (!state) return;
+ // Restore previous state.
+ if (typeof state.nextIndex !== 'number' || state.nextIndex < 0) {
+ throw new Error('The state object is invalid: nextIndex must be a non-negative number.');
+ }
+ if (state.nextIndex > this.requests.length) {
+ throw new Error('The state object is not consistent with RequestList: too few requests loaded.');
+ }
+ if (state.nextIndex < this.requests.length
+ && this.requests[state.nextIndex].uniqueKey !== state.nextUniqueKey) {
+ throw new Error('The state object is not consistent with RequestList: the order of URLs seems to have changed.');
+ }
+
+ const deleteFromInProgress = [];
+ _.keys(state.inProgress).forEach((uniqueKey) => {
+ const index = this.uniqueKeyToIndex[uniqueKey];
+ if (typeof index !== 'number') {
+ throw new Error('The state object is not consistent with RequestList: unknown uniqueKey is present in the state.');
+ }
+ if (index >= state.nextIndex) {
+ deleteFromInProgress.push(uniqueKey);
+ }
+ });
+
+ // WORKAROUND:
+ // It happened to some users that state object contained something like:
+ // {
+ // "nextIndex": 11308,
+ // "nextUniqueKey": "https://www.anychart.com",
+ // "inProgress": {
+ // "https://www.ams360.com": true,
+ // ...
+ // "https://www.anychart.com": true,
+ // }
+ // Which then caused error "The request is not being processed (uniqueKey: https://www.anychart.com)"
+ // As a workaround, we just remove all inProgress requests whose index >= nextIndex,
+ // since they will be crawled again.
+ if (deleteFromInProgress.length) {
+ log.warning('RequestList\'s in-progress field is not consistent, skipping invalid in-progress entries', { deleteFromInProgress });
+ _.each(deleteFromInProgress, (uniqueKey) => {
+ delete state.inProgress[uniqueKey];
});
+ }
+
+ this.nextIndex = state.nextIndex;
+ this.inProgress = state.inProgress;
+
+ // All in-progress requests need to be recrawled
+ this.reclaimed = _.clone(this.inProgress);
}
/**
@@ -297,14 +342,10 @@ class RequestList {
*
* @returns {Promise<Boolean>}
*/
- isEmpty() {
- return Promise
- .resolve()
- .then(() => {
- this._ensureIsInitialized();
+ async isEmpty() {
+ this._ensureIsInitialized();
- return !getFirstKey(this.reclaimed) && this.nextIndex >= this.requests.length;
- });
+ return !getFirstKey(this.reclaimed) && this.nextIndex >= this.requests.length;
}
/**
@@ -312,14 +353,10 @@ class RequestList {
*
* @returns {Promise<Boolean>}
*/
- isFinished() {
- return Promise
- .resolve()
- .then(() => {
- this._ensureIsInitialized();
+ async isFinished() {
+ this._ensureIsInitialized();
- return !getFirstKey(this.inProgress) && this.nextIndex >= this.requests.length;
- });
+ return !getFirstKey(this.inProgress) && this.nextIndex >= this.requests.length;
}
/**
@@ -332,31 +369,27 @@ class RequestList {
*
* @returns {Promise<Request>}
*/
- fetchNextRequest() {
- return Promise
- .resolve()
- .then(() => {
- this._ensureIsInitialized();
-
- // First return reclaimed requests if any.
- const uniqueKey = getFirstKey(this.reclaimed);
- if (uniqueKey) {
- delete this.reclaimed[uniqueKey];
- const index = this.uniqueKeyToIndex[uniqueKey];
- return this.requests[index];
- }
-
- // Otherwise return next request.
- if (this.nextIndex < this.requests.length) {
- const request = this.requests[this.nextIndex];
- this.inProgress[request.uniqueKey] = true;
- this.nextIndex++;
- this.isStatePersisted = false;
- return request;
- }
-
- return null;
- });
+ async fetchNextRequest() {
+ this._ensureIsInitialized();
+
+ // First return reclaimed requests if any.
+ const uniqueKey = getFirstKey(this.reclaimed);
+ if (uniqueKey) {
+ delete this.reclaimed[uniqueKey];
+ const index = this.uniqueKeyToIndex[uniqueKey];
+ return this.requests[index];
+ }
+
+ // Otherwise return next request.
+ if (this.nextIndex < this.requests.length) {
+ const request = this.requests[this.nextIndex];
+ this.inProgress[request.uniqueKey] = true;
+ this.nextIndex++;
+ this.isCurrentStatePersisted = false;
+ return request;
+ }
+
+ return null;
}
/**
@@ -366,19 +399,15 @@ class RequestList {
*
* @returns {Promise}
*/
- markRequestHandled(request) {
- return Promise
- .resolve()
- .then(() => {
- const { uniqueKey } = request;
-
- ensureUniqueKeyValid(uniqueKey);
- this._ensureInProgressAndNotReclaimed(uniqueKey);
- this._ensureIsInitialized();
-
- delete this.inProgress[uniqueKey];
- this.isStatePersisted = false;
- });
+ async markRequestHandled(request) {
+ const { uniqueKey } = request;
+
+ this._ensureUniqueKeyValid(uniqueKey);
+ this._ensureInProgressAndNotReclaimed(uniqueKey);
+ this._ensureIsInitialized();
+
+ delete this.inProgress[uniqueKey];
+ this.isCurrentStatePersisted = false;
}
/**
@@ -389,62 +418,54 @@ class RequestList {
*
* @returns {Promise}
*/
- reclaimRequest(request) {
- return Promise
- .resolve()
- .then(() => {
- const { uniqueKey } = request;
+ async reclaimRequest(request) {
+ const { uniqueKey } = request;
- ensureUniqueKeyValid(uniqueKey);
- this._ensureInProgressAndNotReclaimed(uniqueKey);
- this._ensureIsInitialized();
+ this._ensureUniqueKeyValid(uniqueKey);
+ this._ensureInProgressAndNotReclaimed(uniqueKey);
+ this._ensureIsInitialized();
- this.reclaimed[uniqueKey] = true;
- });
+ this.reclaimed[uniqueKey] = true;
}
/**
- * Adds all requests from a file string.
+ * Adds all requests from a URL fetched from a remote resource.
*
* @ignore
*/
- _addRequestsFromUrl(source) {
+ async _addRequestsFromUrl(source) {
const sharedOpts = _.omit(source, 'requestsFromUrl', 'regex');
const { requestsFromUrl, regex } = source;
const { downloadListOfUrls } = publicUtils;
- return downloadListOfUrls({
- url: requestsFromUrl,
- urlRegExp: regex,
- })
- .then((urlsArr) => {
- const originalLength = this.requests.length;
-
- if (urlsArr) {
- urlsArr.forEach(url => this._addRequest(_.extend({ url }, sharedOpts)));
-
- const fetchedCount = urlsArr.length;
- const importedCount = this.requests.length - originalLength;
-
- log.info('RequestList: list fetched', {
- requestsFromUrl,
- regex,
- fetchedCount,
- importedCount,
- duplicateCount: fetchedCount - importedCount,
- sample: JSON.stringify(urlsArr.slice(0, 5)),
- });
- } else {
- log.warning('RequestList: list fetched but it is empty', {
- requestsFromUrl,
- regex,
- });
- }
- })
- .catch((err) => {
- log.exception(err, 'RequestList: Cannot fetch a request list', { requestsFromUrl, regex });
- throw new Error(`Cannot fetch a request list from ${requestsFromUrl}: ${err}`);
- });
+ // Download remote resource and parse URLs.
+ let urlsArr;
+ try {
+ urlsArr = await downloadListOfUrls({ url: requestsFromUrl, urlRegExp: regex });
+ } catch (err) {
+ throw new Error(`Cannot fetch a request list from ${requestsFromUrl}: ${err}`);
+ }
+
+ // Skip if resource contained no URLs.
+ if (!urlsArr.length) {
+ return log.warning('RequestList: list fetched, but it is empty.', { requestsFromUrl, regex });
+ }
+
+ // Process downloaded URLs.
+ const originalLength = this.requests.length;
+ urlsArr.forEach(url => this._addRequest(_.extend({ url }, sharedOpts)));
+
+ const fetchedCount = urlsArr.length;
+ const importedCount = this.requests.length - originalLength;
+
+ log.info('RequestList: list fetched.', {
+ requestsFromUrl,
+ regex,
+ fetchedCount,
+ importedCount,
+ duplicateCount: fetchedCount - importedCount,
+ sample: JSON.stringify(urlsArr.slice(0, 5)),
+ });
}
/**
@@ -467,7 +488,7 @@ class RequestList {
}
const { uniqueKey } = request;
- ensureUniqueKeyValid(uniqueKey);
+ this._ensureUniqueKeyValid(uniqueKey);
// Skip requests with duplicate uniqueKey
if (!this.uniqueKeyToIndex.hasOwnProperty(uniqueKey)) { // eslint-disable-line no-prototype-builtins
@@ -478,6 +499,18 @@ class RequestList {
}
}
+ /**
+ * Helper function that validates unique key.
+ * Throws an error if uniqueKey is not a non-empty string.
+ *
+ * @ignore
+ */
+ _ensureUniqueKeyValid(uniqueKey) { // eslint-disable-line class-methods-use-this
+ if (typeof uniqueKey !== 'string' || !uniqueKey) {
+ throw new Error('Request object\'s uniqueKey must be a non-empty string');
+ }
+ }
+
/**
* Checks that request is not reclaimed and throws an error if so.
*
@@ -527,3 +560,48 @@ class RequestList {
}
export default RequestList;
+
+/**
+ * Opens a request list and returns a promise resolving to an instance
+ * of the {@link RequestList} class that is already initialized.
+ *
+ * {@link RequestList} represents a list of URLs to crawl, which is always stored in memory.
+ * To enable picking up where left off after a process restart, the request list sources
+ * are persisted to the key value store at initialization of the list. Then, while crawling,
+ * a small state object is regularly persisted to keep track of the crawling status.
+ *
+ * For more details and code examples, see the {@link RequestList} class.
+ *
+ * @param {string|null} listName
+ * Name of the request list to be opened. It will be used as a prefix for key value store
+ * values that persist request list data, such as `REQUEST_LIST_STATE` or `REQUEST_LIST_SOURCES`.
+ * If `null`, the list will not be persisted and will only be stored in memory. Process restart
+ * will then cause the list to be crawled again from the beginning. We suggest always using a name.
+ * @param {Object[]|string[]} sources
+ * Sources represent the URLs to crawl. It can either be a `string[]` with plain URLs or an `Object[]`.
+ * The objects' contents can either be just plain objects, defining at least the 'url' property
+ * or instances of the {@link Request} class. See the (`new RequestList`)(RequestList#new_RequestList_new)
+ * options for details.
+ * @param {Object} [options]
+ * The (`new RequestList`)(RequestList#new_RequestList_new) options. Note that the listName parameter supersedes
+ * the `stateKeyPrefix` option and the sources parameter supersedes the `sources` option.
+ * @returns {Promise<RequestList>}
+ * @memberof module:Apify
+ * @name openRequestList
+ */
+export const openRequestList = async (listName, sources, options = {}) => {
+ checkParamOrThrow(listName, 'listName', 'String | Null');
+ checkParamOrThrow(sources, 'sources', '[Object | String]');
+ if (!sources.length) throw new Error('Parameter sources must not be an empty array.');
+ checkParamOrThrow(options, 'options', 'Object');
+
+ // Support both an array of strings and array of objects.
+ if (typeof sources[0] === 'string') sources = sources.map(url => ({ url }));
+
+ const rl = new RequestList({
+ ...options,
+ stateKeyPrefix: listName,
+ sources,
+ });
+ return rl.initialize();
+};
diff --git a/test/actor.js b/test/actor.js
index a9a760b7d..5b9c4397c 100644
--- a/test/actor.js
+++ b/test/actor.js
@@ -2,7 +2,6 @@ import path from 'path';
import _ from 'underscore';
import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
-import 'babel-polyfill';
import sinon from 'sinon';
import { delayPromise } from 'apify-shared/utilities';
import { ENV_VARS, ACT_JOB_STATUSES, LOCAL_ENV_VARS } from 'apify-shared/consts';
diff --git a/test/basic_crawler.js b/test/basic_crawler.js
index e4ca74b10..3168ffc85 100644
--- a/test/basic_crawler.js
+++ b/test/basic_crawler.js
@@ -1,7 +1,6 @@
import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
import _ from 'underscore';
-import 'babel-polyfill';
import sinon from 'sinon';
import log from 'apify-shared/log';
import { delayPromise } from 'apify-shared/utilities';
diff --git a/test/dataset.js b/test/dataset.js
index ef60f9af3..7a65e1ed1 100644
--- a/test/dataset.js
+++ b/test/dataset.js
@@ -1,6 +1,5 @@
import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
-import 'babel-polyfill';
import fs from 'fs-extra';
import path from 'path';
import sinon from 'sinon';
diff --git a/test/events.js b/test/events.js
index c9d71290c..445ec9ff4 100644
--- a/test/events.js
+++ b/test/events.js
@@ -1,4 +1,3 @@
-import 'babel-polyfill';
import WebSocket from 'ws';
import sinon from 'sinon';
import { expect } from 'chai';
diff --git a/test/key_value_store.js b/test/key_value_store.js
index 536e2aece..217a5242c 100644
--- a/test/key_value_store.js
+++ b/test/key_value_store.js
@@ -1,6 +1,5 @@
import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
-import 'babel-polyfill';
import sinon from 'sinon';
import path from 'path';
import { ENV_VARS } from 'apify-shared/consts';
diff --git a/test/puppeteer_crawler.js b/test/puppeteer_crawler.js
index e979c172f..7f697904a 100644
--- a/test/puppeteer_crawler.js
+++ b/test/puppeteer_crawler.js
@@ -1,6 +1,5 @@
import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
-import 'babel-polyfill';
import _ from 'underscore';
import log from 'apify-shared/log';
import { ENV_VARS } from 'apify-shared/consts';
diff --git a/test/puppeteer_pool.js b/test/puppeteer_pool.js
index 6abf1d2d5..3385e63f4 100644
--- a/test/puppeteer_pool.js
+++ b/test/puppeteer_pool.js
@@ -3,7 +3,6 @@ import fs from 'fs';
import chaiAsPromised from 'chai-as-promised';
import _ from 'underscore';
import log from 'apify-shared/log';
-import 'babel-polyfill';
import { ENV_VARS } from 'apify-shared/consts';
import * as Apify from '../build/index';
import { launchPuppeteer } from '../build/puppeteer';
diff --git a/test/request_list.js b/test/request_list.js
index 3f0263c40..26b81455f 100644
--- a/test/request_list.js
+++ b/test/request_list.js
@@ -1,9 +1,9 @@
-import 'babel-polyfill';
import _ from 'underscore';
import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
import request from 'request-promise-native';
import sinon from 'sinon';
+import log from 'apify-shared/log';
import { delayPromise } from 'apify-shared/utilities';
import { ACTOR_EVENT_NAMES_EX } from '../build/constants';
import Apify from '../build/index';
@@ -13,6 +13,16 @@ import * as utils from '../build/utils';
chai.use(chaiAsPromised);
describe('Apify.RequestList', () => {
+ let ll;
+ before(() => {
+ ll = log.getLevel();
+ log.setLevel(log.LEVELS.ERROR);
+ });
+
+ after(() => {
+ log.setLevel(ll);
+ });
+
it('should not accept to pages with same uniqueKey', async () => {
const requestList = new Apify.RequestList({
sources: [
@@ -60,7 +70,7 @@ describe('Apify.RequestList', () => {
await expect(requestList.markRequestHandled(requestObj)).to.not.be.rejectedWith();
});
- it('should correctly initialized itself', async () => {
+ it('should correctly initialize itself', async () => {
const sources = [
{ url: 'https://example.com/1' },
{ url: 'https://example.com/2' },
@@ -389,7 +399,7 @@ describe('Apify.RequestList', () => {
expect(requestList.inProgress).to.include(requestList.reclaimed);
});
- it('should correctly persists its state when persistStateKey is set', async () => {
+ it('should correctly persist its state when persistStateKey is set', async () => {
const PERSIST_STATE_KEY = 'some-key';
const mock = sinon.mock(keyValueStore);
@@ -409,11 +419,11 @@ describe('Apify.RequestList', () => {
const requestList = new Apify.RequestList(opts);
await requestList.initialize();
- expect(requestList.isStatePersisted).to.be.eql(true);
+ expect(requestList.isCurrentStatePersisted).to.be.eql(true);
// Fetch one request and check that state is not persisted.
const request1 = await requestList.fetchNextRequest();
- expect(requestList.isStatePersisted).to.be.eql(false);
+ expect(requestList.isCurrentStatePersisted).to.be.eql(false);
// Persist state.
mock.expects('setValue')
@@ -422,24 +432,24 @@ describe('Apify.RequestList', () => {
.returns(Promise.resolve());
Apify.events.emit(ACTOR_EVENT_NAMES_EX.PERSIST_STATE);
await delayPromise(1);
- expect(requestList.isStatePersisted).to.be.eql(true);
+ expect(requestList.isCurrentStatePersisted).to.be.eql(true);
// Do some other changes and persist it again.
const request2 = await requestList.fetchNextRequest();
- expect(requestList.isStatePersisted).to.be.eql(false);
+ expect(requestList.isCurrentStatePersisted).to.be.eql(false);
await requestList.markRequestHandled(request2);
- expect(requestList.isStatePersisted).to.be.eql(false);
+ expect(requestList.isCurrentStatePersisted).to.be.eql(false);
mock.expects('setValue')
.once()
.withArgs(PERSIST_STATE_KEY, requestList.getState())
.returns(Promise.resolve());
Apify.events.emit(ACTOR_EVENT_NAMES_EX.PERSIST_STATE);
await delayPromise(1);
- expect(requestList.isStatePersisted).to.be.eql(true);
+ expect(requestList.isCurrentStatePersisted).to.be.eql(true);
// Reclaim event doesn't change the state.
await requestList.reclaimRequest(request1);
- expect(requestList.isStatePersisted).to.be.eql(true);
+ expect(requestList.isCurrentStatePersisted).to.be.eql(true);
// Now initiate new request list from saved state and check that it's same as state
// of original request list.
@@ -561,7 +571,8 @@ describe('Apify.RequestList', () => {
await requestList.initialize();
expect(requestList.length()).to.be.eql(4);
- const log = sinon.stub(console, 'log');
+ log.setLevel(log.LEVELS.INFO);
+ const logStub = sinon.stub(console, 'log');
requestList = new Apify.RequestList({
sources: sources.concat([
@@ -575,9 +586,10 @@ describe('Apify.RequestList', () => {
await requestList.initialize();
expect(requestList.length()).to.be.eql(6);
- expect(log.called).to.be.eql(true);
- expect(log.getCall(0).args[0]).to.include('Check your sources\' unique keys.');
+ expect(logStub.called).to.be.eql(true);
+ expect(logStub.getCall(0).args[0]).to.include('Check your sources\' unique keys.');
- log.restore();
+ logStub.restore();
+ log.setLevel(log.LEVELS.ERROR);
});
});
diff --git a/test/request_queue.js b/test/request_queue.js
index 9a44b15ec..273a49086 100644
--- a/test/request_queue.js
+++ b/test/request_queue.js
@@ -1,7 +1,6 @@
import chai, { assert, expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
import _ from 'underscore';
-import 'babel-polyfill';
import sinon from 'sinon';
import path from 'path';
import { ENV_VARS } from 'apify-shared/consts';
diff --git a/test/settings_rotator.js b/test/settings_rotator.js
index 5e69d6c59..a4a0595f5 100644
--- a/test/settings_rotator.js
+++ b/test/settings_rotator.js
@@ -1,4 +1,3 @@
-import 'babel-polyfill';
import _ from 'underscore';
import { expect } from 'chai';
import Apify from '../build/index';