Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.
TypeScript apifyautomationcrawlercrawlingheadlessheadless-chromejavascriptnodejsnpmplaywrightpuppeteerscraperscrapingtypescriptweb-crawlerweb-crawlingweb-scraping
make statistic class persistable on multiple instances (#716)
Paulo Cesar7d11dad1a017
diff --git a/package.json b/package.jsonindex ae72e2005..f30db6272 100644--- a/package.json+++ b/package.json@@ -105,7 +105,7 @@"jsdoc-export-default-interop": "^0.3.1","portastic": "^1.0.1","prettier": "^2.0.5",- "proxy": "^1.0.1",+ "proxy": "^1.0.2","sinon": "^9.0.2","sinon-stub-promise": "^4.0.0","socket.io-client": "^2.3.0",diff --git a/src/crawlers/basic_crawler.js b/src/crawlers/basic_crawler.jsindex c2327b4c5..90f5b7f10 100644--- a/src/crawlers/basic_crawler.js+++ b/src/crawlers/basic_crawler.js@@ -162,6 +162,8 @@ const SAFE_MIGRATION_WAIT_MILLIS = 20000;** await crawler.run();* ```+ * @property {Statistics} stats+ * Contains statistics about the current run** @property {AutoscaledPool} autoscaledPool* A reference to the underlying {@link AutoscaledPool} class that manages the concurrency of the crawler.@@ -302,7 +304,8 @@ class BasicCrawler {await this._loadHandledRequestCount();this.isRunningPromise = this.autoscaledPool.run();- this.stats.startLogging();+ await this.stats.startCapturing();+try {await this.isRunningPromise;} finally {@@ -310,36 +313,53 @@ class BasicCrawler {await this.sessionPool.teardown();}- this.stats.stopLogging();- const finalStats = this.stats.getCurrent();- this.log.info('Final request statistics:', finalStats);+ await this.stats.stopCapturing();+ const finalStats = this.stats.calculate();+ const { requestsFailed, requestsFinished } = this.stats.state;+ this.log.info('Final request statistics:', {+ ...finalStats,+ requestsFinished,+ requestsFailed,+ retryHistogram: this.stats.requestRetryHistogram,+ });}}async _pauseOnMigration() {- await this.autoscaledPool.pause(SAFE_MIGRATION_WAIT_MILLIS)- .catch((err) => {- if (err.message.includes('running tasks did not finish')) {- this.log.error('The crawler was paused due to migration to another host, '- + 'but some requests did not finish in time. Those requests\' results may be duplicated.');- } else {- throw err;- }- });- if (this.requestList) {- if (await this.requestList.isFinished()) return;- await this.requestList.persistState()+ if (this.autoscaledPool) {+ // if run wasn't called, this is going to crash+ await this.autoscaledPool.pause(SAFE_MIGRATION_WAIT_MILLIS).catch((err) => {- if (err.message.includes('Cannot persist state.')) {- this.log.error('The crawler attempted to persist its request list\'s state and failed due to missing or '- + 'invalid config. Make sure to use either Apify.openRequestList() or the "stateKeyPrefix" option of RequestList '- + 'constructor to ensure your crawling state is persisted through host migrations and restarts.');+ if (err.message.includes('running tasks did not finish')) {+ this.log.error('The crawler was paused due to migration to another host, '+ + 'but some requests did not finish in time. Those requests\' results may be duplicated.');} else {- this.log.exception(err, 'An unexpected error occured when the crawler '- + 'attempted to persist its request list\'s state.');+ throw err;}});}++ const requestListPersistPromise = (async () => {+ if (this.requestList) {+ if (await this.requestList.isFinished()) return;+ await this.requestList.persistState()+ .catch((err) => {+ if (err.message.includes('Cannot persist state.')) {+ this.log.error('The crawler attempted to persist its request list\'s state and failed due to missing or '+ + 'invalid config. Make sure to use either Apify.openRequestList() or the "stateKeyPrefix" option of RequestList '+ + 'constructor to ensure your crawling state is persisted through host migrations and restarts.');+ } else {+ this.log.exception(err, 'An unexpected error occured when the crawler '+ + 'attempted to persist its request list\'s state.');+ }+ });+ }+ })();++ await Promise.all([+ requestListPersistPromise,+ this.stats.persistState(),+ ]);}/**diff --git a/src/crawlers/cheerio_crawler.js b/src/crawlers/cheerio_crawler.jsindex c0b5ad90b..acddd5169 100644--- a/src/crawlers/cheerio_crawler.js+++ b/src/crawlers/cheerio_crawler.js@@ -23,7 +23,7 @@ import AutoscaledPool, { AutoscaledPoolOptions } from '../autoscaling/autoscaledimport { HandleFailedRequest } from './basic_crawler';import Request from '../request';import { RequestList } from '../request_list';-import { ProxyConfiguration } from '../proxy_configuration';+import { ProxyConfiguration, ProxyInfo } from '../proxy_configuration';import { RequestQueue } from '../request_queue';import { Session } from '../session_pool/session';import { SessionPoolOptions } from '../session_pool/session_pool';diff --git a/src/crawlers/puppeteer_crawler.js b/src/crawlers/puppeteer_crawler.jsindex 31bf1819d..f3a4d366f 100644--- a/src/crawlers/puppeteer_crawler.js+++ b/src/crawlers/puppeteer_crawler.js@@ -21,7 +21,7 @@ import AutoscaledPool, { AutoscaledPoolOptions } from '../autoscaling/autoscaledimport { LaunchPuppeteerOptions } from '../puppeteer'; // eslint-disable-line no-unused-vars,import/namedimport { Session } from '../session_pool/session'; // eslint-disable-line no-unused-varsimport { SessionPoolOptions } from '../session_pool/session_pool';-import { ProxyConfiguration } from '../proxy_configuration';+import { ProxyConfiguration, ProxyInfo } from '../proxy_configuration';// eslint-enable-line import/no-duplicates/**diff --git a/src/crawlers/statistics.js b/src/crawlers/statistics.jsindex 14bd3e8e5..731182585 100644--- a/src/crawlers/statistics.js+++ b/src/crawlers/statistics.js@@ -1,6 +1,12 @@import { checkParamOrThrow } from 'apify-client/build/utils';-import log from '../utils_log';+import { openKeyValueStore } from '../key_value_store';+import { ACTOR_EVENT_NAMES_EX } from '../constants';+import defaultLog from '../utils_log';+import events from '../events';+/**+ * @private+ */class Job {constructor() {this.lastRunAt = null;@@ -8,12 +14,12 @@ class Job {}run() {- this.lastRunAt = new Date();+ this.lastRunAt = Date.now();return ++this.runs;}finish() {- this.durationMillis = new Date() - this.lastRunAt;+ this.durationMillis = Date.now() - this.lastRunAt;return this.durationMillis;}@@ -24,17 +30,26 @@ class Job {/*** The statistics class provides an interface to collecting and logging run- * statistics of arbitrary jobs. Currently it provides the following information:+ * statistics for requests.*- * - Average run time of successful jobs- * - Number of successful jobs per minute- * - Total number of successful jobs- * - Total number of failed jobs- * - A histogram of retry counts = Number of jobs that finished after N retries.+ * All statistic information is saved on key value store+ * under the key SDK_CRAWLER_STATISTICS_*, persists between+ * migrations and abort/resurrect*- * @ignore+ * @property {StatisticState} state+ * Current statistic state used for doing calculations on {@link Statistics#calculate} calls+ * @property {number} id+ * Statistic instance id+ * @property {number[]} requestRetryHistogram+ * Contains the current retries histogram.+ * Index 0 means 0 retries, index 2, 2 retries,+ * and so on*/-export default class Statistics {+class Statistics {+ /**+ * @param {StatisticsOptions} options+ * @hideconstructor+ */constructor(options = {}) {const {logIntervalSecs = 60,@@ -44,76 +59,298 @@ export default class Statistics {checkParamOrThrow(logIntervalSecs, 'options.logIntervalSecs', 'Number');checkParamOrThrow(logMessage, 'options.logMessage', 'String');-+ this.log = defaultLog.child({ prefix: 'Statistics' });this.logIntervalMillis = logIntervalSecs * 1000;this.logMessage = logMessage;+ this.keyValueStore = null;+ // assign an id while incrementing so it can be saved/restored from KV+ this.id = Statistics.id++;+ this.persistStateKey = `SDK_CRAWLER_STATISTICS_${this.id}`;+ this.listener = this.persistState.bind(this);+ this.requestRetryHistogram = [];- this.jobRetryHistogram = [];- this.finishedJobs = 0;- this.failedJobs = 0;- this.jobsInProgress = new Map();- this.minJobDurationMillis = Infinity;- this.maxJobDurationMillis = 0;- this.totalJobDurationMillis = 0;- this.startedAt = null;- this.logInterval = null;+ /**+ * @private+ * @type {Map<string | number, Job>}+ */+ this.requestsInProgress = new Map();++ // initialize by "resetting"+ this.reset();}+ /**+ * Set the current statistic instance to pristine values+ */+ reset() {+ this.state = {+ requestsFinished: 0,+ requestsFailed: 0,+ requestsRetries: 0,+ requestsFailedPerMinute: 0,+ requestsFinishedPerMinute: 0,+ requestMinDurationMillis: Infinity,+ requestMaxDurationMillis: 0,+ requestTotalFailedDurationMillis: 0,+ requestTotalFinishedDurationMillis: 0,+ crawlerStartedAt: null,+ crawlerFinishedAt: null,+ statsPersistedAt: null,+ crawlerRuntimeMillis: 0,+ };++ this.requestRetryHistogram.length = 0;+ this.requestsInProgress.clear();+ this.instanceStart = Date.now();++ this._teardown();+ }++ /**+ * Starts a job+ *+ * @param {number|string} id+ * @ignore+ */startJob(id) {- if (!this.startedAt) this.startedAt = new Date();- let job = this.jobsInProgress.get(id);+ let job = this.requestsInProgress.get(id);if (!job) job = new Job();job.run();- this.jobsInProgress.set(id, job);+ this.requestsInProgress.set(id, job);}+ /**+ * Mark job as finished and sets the state+ *+ * @param {number|string} id+ * @ignore+ */finishJob(id) {- const job = this.jobsInProgress.get(id);+ const job = this.requestsInProgress.get(id);if (!job) return;const jobDurationMillis = job.finish();- this.finishedJobs++;- this.totalJobDurationMillis += jobDurationMillis;+ this.state.requestsFinished++;+ this.state.requestTotalFinishedDurationMillis += jobDurationMillis;this._saveRetryCountForJob(job);- if (jobDurationMillis < this.minJobDurationMillis) this.minJobDurationMillis = jobDurationMillis;- if (jobDurationMillis > this.maxJobDurationMillis) this.maxJobDurationMillis = jobDurationMillis;- this.jobsInProgress.delete(id);+ if (jobDurationMillis < this.state.requestMinDurationMillis) this.state.requestMinDurationMillis = jobDurationMillis;+ if (jobDurationMillis > this.state.requestMaxDurationMillis) this.state.requestMaxDurationMillis = jobDurationMillis;+ this.requestsInProgress.delete(id);}+ /**+ * Mark job as failed and sets the state+ *+ * @param {number|string} id+ * @ignore+ */failJob(id) {- const job = this.jobsInProgress.get(id);+ const job = this.requestsInProgress.get(id);if (!job) return;- this.failedJobs++;+ this.state.requestTotalFailedDurationMillis += job.finish();+ this.state.requestsFailed++;this._saveRetryCountForJob(job);- this.jobsInProgress.delete(id);+ this.requestsInProgress.delete(id);}- getCurrent() {- const totalMillis = new Date() - this.startedAt;+ /**+ * Calculate the current statistics+ */+ calculate() {+ const {+ requestsFailed,+ requestsFinished,+ requestTotalFailedDurationMillis,+ requestTotalFinishedDurationMillis,+ } = this.state;+ const totalMillis = Date.now() - this.instanceStart;const totalMinutes = totalMillis / 1000 / 60;return {- avgDurationMillis: Math.round(this.totalJobDurationMillis / this.finishedJobs) || Infinity,- perMinute: Math.round(this.finishedJobs / totalMinutes),- finished: this.finishedJobs,- failed: this.failedJobs,- retryHistogram: [...this.jobRetryHistogram],+ requestAvgFailedDurationMillis: Math.round(requestTotalFailedDurationMillis / requestsFailed) || Infinity,+ requestAvgFinishedDurationMillis: Math.round(requestTotalFinishedDurationMillis / requestsFinished) || Infinity,+ requestsFinishedPerMinute: Math.round(requestsFinished / totalMinutes) || 0,+ requestsFailedPerMinute: Math.floor(requestsFailed / totalMinutes) || 0,+ requestTotalDurationMillis: requestTotalFinishedDurationMillis + requestTotalFailedDurationMillis,+ requestsTotal: requestsFailed + requestsFinished,+ crawlerRuntimeMillis: totalMillis,};}- startLogging() {+ /**+ * Initializes the key value store for persisting the statistics,+ * displaying the current state in predefined intervals+ */+ async startCapturing() {+ this.keyValueStore = await openKeyValueStore();++ await this._maybeLoadStatistics();++ if (this.state.crawlerStartedAt === null) {+ this.state.crawlerStartedAt = new Date();+ }++ events.on(ACTOR_EVENT_NAMES_EX.PERSIST_STATE, this.listener);+this.logInterval = setInterval(() => {- log.info(this.logMessage, this.getCurrent());+ this.log.info(this.logMessage, {+ ...this.calculate(),+ retryHistogram: this.requestRetryHistogram,+ });}, this.logIntervalMillis);}- stopLogging() {- clearInterval(this.logInterval);+ /**+ * Stops logging and remove event listeners, then persist+ */+ async stopCapturing() {+ this._teardown();++ this.state.crawlerFinishedAt = new Date();++ await this.persistState();}+ /**+ * @private+ * @param {Job} job+ */_saveRetryCountForJob(job) {const retryCount = job.retryCount();- this.jobRetryHistogram[retryCount] = this.jobRetryHistogram[retryCount]- ? this.jobRetryHistogram[retryCount] + 1+ if (retryCount > 0) this.state.requestsRetries++;+ this.requestRetryHistogram[retryCount] = this.requestRetryHistogram[retryCount]+ ? this.requestRetryHistogram[retryCount] + 1: 1;}++ /**+ * Persist internal state to the key value store+ */+ async persistState() {+ // this might be called before startCapturing was called without using await, should not crash+ if (!this.keyValueStore) {+ return;+ }++ this.log.debug('Persisting state', { persistStateKey: this.persistStateKey });++ await this.keyValueStore.setValue(this.persistStateKey, this.toJSON());+ }++ /**+ * Loads the current statistic from the key value store if any+ * @private+ */+ async _maybeLoadStatistics() {+ // this might be called before startCapturing was called without using await, should not crash+ if (!this.keyValueStore) {+ return;+ }++ /** @type {StatisticPersistedState & StatisticState} */+ const savedState = await this.keyValueStore.getValue(this.persistStateKey);++ if (!savedState) return;++ this.log.debug('Recreating state from KeyValueStore', { persistStateKey: this.persistStateKey });++ this.requestRetryHistogram.push(...savedState.requestRetryHistogram);+ this.state.requestsFinished = savedState.requestsFinished;+ this.state.requestsFailed = savedState.requestsFailed;+ this.state.requestsRetries = savedState.requestsRetries;++ this.state.requestTotalFailedDurationMillis = savedState.requestTotalFailedDurationMillis;+ this.state.requestTotalFinishedDurationMillis = savedState.requestTotalFinishedDurationMillis;+ this.state.requestMinDurationMillis = savedState.requestMinDurationMillis;+ this.state.requestMaxDurationMillis = savedState.requestMaxDurationMillis;+ // persisted state uses ISO date strings+ this.state.crawlerFinishedAt = savedState.crawlerFinishedAt ? new Date(savedState.crawlerFinishedAt) : null;+ this.state.crawlerStartedAt = savedState.crawlerStartedAt ? new Date(savedState.crawlerStartedAt) : null;+ this.state.statsPersistedAt = savedState.statsPersistedAt ? new Date(savedState.statsPersistedAt) : null;+ this.state.crawlerRuntimeMillis = savedState.crawlerRuntimeMillis;+ this.instanceStart = Date.now() - (this.state.statsPersistedAt - savedState.crawlerLastStartTimestamp);++ this.log.debug('Loaded from KeyValueStore');+ }++ /**+ * @private+ */+ _teardown() {+ // this can be called before a call to startCapturing happens (or in a 'finally' block)+ events.removeListener(ACTOR_EVENT_NAMES_EX.PERSIST_STATE, this.listener);++ if (this.logInterval) {+ clearInterval(this.logInterval);+ this.logInterval = null;+ }+ }++ /**+ * Make this class serializable when called with `JSON.stringify(statsInstance)` directly+ * or through `keyValueStore.setValue('KEY', statsInstance)`+ *+ * @returns {StatisticPersistedState | StatisticState}+ */+ toJSON() {+ // merge all the current state information that can be used from the outside+ // without the need to reconstruct for the sake of stats.calculate()+ // omit duplicated information+ return {+ ...this.state,+ crawlerLastStartTimestamp: this.instanceStart,+ crawlerFinishedAt: this.state.crawlerFinishedAt ? new Date(this.state.crawlerFinishedAt).toISOString() : null,+ crawlerStartedAt: this.state.crawlerStartedAt ? new Date(this.state.crawlerStartedAt).toISOString() : null,+ requestRetryHistogram: this.requestRetryHistogram,+ statsId: this.id,+ statsPersistedAt: new Date().toISOString(),+ ...this.calculate(),+ };+ }}++Statistics.id = 0;++export default Statistics;++/**+ * @ignore+ * @typedef StatisticsOptions+ * @property {number} [logIntervalSecs]+ * @property {string} [logMessage]+ */++/**+ * Format of the persisted stats+ *+ * @typedef StatisticPersistedState+ * @property {number[]} requestRetryHistogram+ * @property {number} statsId+ * @property {number} requestAvgFailedDurationMillis+ * @property {number} requestAvgFinishedDurationMillis+ * @property {number} requestsFinishedPerMinute+ * @property {number} requestsFailedPerMinute+ * @property {number} requestTotalDurationMillis+ * @property {number} requestsTotal+ * @property {number} crawlerRuntimeMillis+ * @property {number} crawlerLastStartTimestamp+ * @property {string} statsPersistedAt+ */++/**+ * Contains the statistics state+ *+ * @typedef StatisticState+ * @property {number} requestsFinished+ * @property {number} requestsFailed+ * @property {number} requestsRetries+ * @property {number} requestsFailedPerMinute+ * @property {number} requestsFinishedPerMinute+ * @property {number} requestMinDurationMillis+ * @property {number} requestMaxDurationMillis+ * @property {number} requestTotalFailedDurationMillis+ * @property {number} requestTotalFinishedDurationMillis+ * @property {Date|string|null} crawlerStartedAt+ * @property {Date|string|null} crawlerFinishedAt+ * @property {number} crawlerRuntimeMillis+ * @property {Date|string|null} statsPersistedAt+ */diff --git a/src/request_list.js b/src/request_list.jsindex 3b816a71e..1e7781ab7 100644--- a/src/request_list.js+++ b/src/request_list.js@@ -260,8 +260,9 @@ export class RequestList {// Note that reclaimedRequests is always a subset of inProgress!this.reclaimed = {};- this.persistStateKey = persistStateKey;+ this.persistStateKey = persistStateKey ? `SDK_${persistStateKey}` : persistStateKey;this.persistRequestsKey = persistRequestsKey || persistSourcesKey;+ this.persistRequestsKey = this.persistRequestsKey ? `SDK_${persistRequestsKey}` : this.persistRequestsKey;this.initialState = state;diff --git a/src/session_pool/session_pool.js b/src/session_pool/session_pool.jsindex 88b5c555e..c225cd945 100644--- a/src/session_pool/session_pool.js+++ b/src/session_pool/session_pool.js@@ -94,7 +94,7 @@ export class SessionPool extends EventEmitter {maxPoolSize = 1000,persistStateKeyValueStoreId = null,- persistStateKey = 'SESSION_POOL_STATE',+ persistStateKey = 'SDK_SESSION_POOL_STATE',createSessionFunction = null,sessionOptions = {},diff --git a/test/crawlers/basic_crawler.test.js b/test/crawlers/basic_crawler.test.jsindex 1abaab865..578b49f45 100644--- a/test/crawlers/basic_crawler.test.js+++ b/test/crawlers/basic_crawler.test.js@@ -89,6 +89,9 @@ describe('BasicCrawler', () => {// The crawler will pause after 200 requestsconst runPromise = basicCrawler.run();runPromise.then(() => { finished = true; });++ // need to monkeypatch the stats class, otherwise it will never finish+ basicCrawler.stats.persistState = () => Promise.resolve();await persistPromise;expect(finished).toBe(false);diff --git a/test/crawlers/statistics.test.js b/test/crawlers/statistics.test.jsindex b10272fad..79abf46e0 100644--- a/test/crawlers/statistics.test.js+++ b/test/crawlers/statistics.test.js@@ -1,38 +1,203 @@import sinon from 'sinon';-import log from '../../build/utils_log';import Statistics from '../../build/crawlers/statistics';+import LocalStorageDirEmulator from '../local_storage_dir_emulator';+import events from '../../build/events';+import { ACTOR_EVENT_NAMES_EX } from '../../build/constants';describe('Statistics', () => {const getPerMinute = (jobCount, totalTickMillis) => {return Math.round(jobCount / (totalTickMillis / 1000 / 60));};+ const toISOString = date => new Date(date).toISOString();+let clock;let stats;+ let localStorageEmulator;++ beforeAll(async () => {+ localStorageEmulator = new LocalStorageDirEmulator();+ });- beforeEach(() => {+ beforeEach(async () => {+ await localStorageEmulator.init();clock = sinon.useFakeTimers();stats = new Statistics();});- afterEach(() => {+ afterEach(async () => {+ events.removeAllListeners(ACTOR_EVENT_NAMES_EX.PERSIST_STATE);clock.restore();stats = null;clock = null;});+ afterAll(async () => {+ await localStorageEmulator.destroy();+ });++ describe('persist state', () => {+ // needs to go first for predictability+ test('should increment id by each new consecutive instance', () => {+ expect(stats.id).toEqual(0);+ expect(Statistics.id).toEqual(1);+ expect(stats.persistStateKey).toEqual('SDK_CRAWLER_STATISTICS_0');+ const [n1, n2] = [new Statistics(), new Statistics()];+ expect(n1.id).toEqual(1);+ expect(n2.id).toEqual(2);+ expect(Statistics.id).toEqual(3);+ });++ test('should persist the state to KV and load again', async () => {+ const startedAt = 1000;+ clock.tick(startedAt);+ stats.startJob(0);+ clock.tick(100);+ stats.finishJob(0);++ await stats.startCapturing();+ await stats.persistState();++ const state = await stats.keyValueStore.getValue(stats.persistStateKey);++ expect(state).toEqual({+ crawlerFinishedAt: null,+ crawlerLastStartTimestamp: 0,+ crawlerRuntimeMillis: 1100,+ crawlerStartedAt: toISOString(startedAt + 100),+ requestAvgFailedDurationMillis: null,+ requestAvgFinishedDurationMillis: 100,+ requestMaxDurationMillis: 100,+ requestMinDurationMillis: 100,+ requestTotalDurationMillis: 100,+ requestRetryHistogram: [1],+ requestTotalFailedDurationMillis: 0,+ requestTotalFinishedDurationMillis: 100,+ requestsFailed: 0,+ requestsFailedPerMinute: 0,+ requestsFinished: 1,+ requestsFinishedPerMinute: 55,+ requestsRetries: 0,+ requestsTotal: 1,+ statsId: stats.id,+ statsPersistedAt: toISOString(startedAt + 100),+ });++ await stats.stopCapturing();+ stats.reset();++ expect(stats.toJSON()).toEqual({+ crawlerFinishedAt: null,+ crawlerRuntimeMillis: 0,+ crawlerLastStartTimestamp: 1100,+ crawlerStartedAt: null,+ requestAvgFailedDurationMillis: Infinity,+ requestAvgFinishedDurationMillis: Infinity,+ requestMaxDurationMillis: 0,+ requestMinDurationMillis: Infinity,+ requestRetryHistogram: [],+ requestTotalDurationMillis: 0,+ requestTotalFailedDurationMillis: 0,+ requestTotalFinishedDurationMillis: 0,+ requestsFailed: 0,+ requestsFailedPerMinute: 0,+ requestsFinished: 0,+ requestsFinishedPerMinute: 0,+ requestsRetries: 0,+ requestsTotal: 0,+ statsId: stats.id,+ statsPersistedAt: toISOString(startedAt + 100),+ });++ await stats.startCapturing();++ stats.startJob(1);+ clock.tick(100);+ stats.finishJob(1);++ clock.tick(1000);++ expect(stats.toJSON()).toEqual({+ crawlerRuntimeMillis: 2200,+ crawlerLastStartTimestamp: 0,+ crawlerFinishedAt: toISOString(startedAt + 100),+ crawlerStartedAt: toISOString(startedAt + 100),+ requestAvgFailedDurationMillis: Infinity,+ requestAvgFinishedDurationMillis: 100,+ requestMaxDurationMillis: 100,+ requestMinDurationMillis: 100,+ requestRetryHistogram: [2],+ requestTotalDurationMillis: 200,+ requestTotalFailedDurationMillis: 0,+ requestTotalFinishedDurationMillis: 200,+ requestsFailed: 0,+ requestsFailedPerMinute: 0,+ requestsFinished: 2,+ requestsFinishedPerMinute: 55,+ requestsRetries: 0,+ requestsTotal: 2,+ statsId: stats.id,+ statsPersistedAt: toISOString(startedAt + 1200),+ });++ clock.tick(10000);++ expect(stats.calculate()).toEqual({+ crawlerRuntimeMillis: 12200,+ requestAvgFailedDurationMillis: Infinity,+ requestAvgFinishedDurationMillis: 100,+ requestTotalDurationMillis: 200,+ requestsFailedPerMinute: 0,+ requestsFinishedPerMinute: getPerMinute(2, 12200),+ requestsTotal: 2,+ });+ });++ test('should remove persist state event listener', async () => {+ await stats.startCapturing();+ expect(events.listenerCount(ACTOR_EVENT_NAMES_EX.PERSIST_STATE)).toEqual(1);+ await stats.stopCapturing();++ expect(events.listenerCount(ACTOR_EVENT_NAMES_EX.PERSIST_STATE)).toEqual(0);+ await stats.startCapturing();+ expect(events.listenerCount(ACTOR_EVENT_NAMES_EX.PERSIST_STATE)).toEqual(1);+ stats.reset();++ expect(events.listenerCount(ACTOR_EVENT_NAMES_EX.PERSIST_STATE)).toEqual(0);+ });++ test('on persistState event', async () => {+ stats.startJob(0);+ clock.tick(100);+ stats.finishJob(0);++ await stats.startCapturing(); // keyValueStore is initialized here++ const state = stats.toJSON();+ const spy = sinon.spy(stats.keyValueStore, 'setValue');++ events.emit(ACTOR_EVENT_NAMES_EX.PERSIST_STATE);++ const { retryHistogram, finished, failed, ...rest } = stats.calculate();++ expect(spy.getCall(0).args).toEqual([stats.persistStateKey, { ...state, ...rest }]);+ }, 2000);+ });+test('should finish a job', () => {stats.startJob(0);clock.tick(1);stats.finishJob(0);clock.tick(1);- const current = stats.getCurrent();+ const current = stats.calculate();expect(current).toEqual({- avgDurationMillis: 1,- perMinute: getPerMinute(1, 2),- finished: 1,- failed: 0,- retryHistogram: [1],+ crawlerRuntimeMillis: 2,+ requestAvgFailedDurationMillis: Infinity,+ requestAvgFinishedDurationMillis: 1,+ requestTotalDurationMillis: 1,+ requestsFailedPerMinute: 0,+ requestsFinishedPerMinute: getPerMinute(1, 2),+ requestsTotal: 1,});});@@ -41,14 +206,17 @@ describe('Statistics', () => {clock.tick(0);stats.failJob(0);clock.tick(1);- const current = stats.getCurrent();+ const current = stats.calculate();expect(current).toEqual({- avgDurationMillis: Infinity,- perMinute: 0,- finished: 0,- failed: 1,- retryHistogram: [1],+ crawlerRuntimeMillis: 1,+ requestAvgFailedDurationMillis: Infinity,+ requestAvgFinishedDurationMillis: Infinity,+ requestTotalDurationMillis: 0,+ requestsFailedPerMinute: 60000,+ requestsFinishedPerMinute: 0,+ requestsTotal: 1,});+ expect(stats.requestRetryHistogram).toEqual([1]);});test('should collect retries', () => {@@ -61,14 +229,17 @@ describe('Statistics', () => {stats.finishJob(1);stats.startJob(2);stats.finishJob(2);- const current = stats.getCurrent();+ const current = stats.calculate();expect(current).toEqual({- avgDurationMillis: Infinity,- perMinute: Infinity,- finished: 3,- failed: 0,- retryHistogram: [1, 1, 1],+ crawlerRuntimeMillis: 0,+ requestAvgFailedDurationMillis: Infinity,+ requestAvgFinishedDurationMillis: Infinity,+ requestTotalDurationMillis: 0,+ requestsFailedPerMinute: 0,+ requestsFinishedPerMinute: Infinity,+ requestsTotal: 3,});+ expect(stats.requestRetryHistogram).toEqual([1, 1, 1]);});test('should return correct stats for multiple parallel jobs', () => {@@ -85,48 +256,73 @@ describe('Statistics', () => {stats.finishJob(2); // runtime: 13msclock.tick(10); // since startedAt: 25ms- const current = stats.getCurrent();+ const current = stats.calculate();expect(current).toEqual({- avgDurationMillis: (13 + 3) / 2,- perMinute: getPerMinute(2, 25),- finished: 2,- failed: 1,- retryHistogram: [3],+ crawlerRuntimeMillis: 25,+ requestAvgFailedDurationMillis: 5,+ requestAvgFinishedDurationMillis: (13 + 3) / 2,+ requestTotalDurationMillis: 21,+ requestsFailedPerMinute: 2400,+ requestsFinishedPerMinute: getPerMinute(2, 25),+ requestsTotal: 3,+ });+ expect(stats.state).toMatchObject({+ requestsFailed: 1,+ requestsFinished: 2,});+ expect(stats.requestRetryHistogram).toEqual([3]);});- test('should regularly log stats', () => {+ test('should regularly log stats', async () => {const logged = [];- sinon.stub(log, 'info').callsFake((...args) => {+ sinon.stub(stats.log, 'info').callsFake((...args) => {logged.push(args);});stats.startJob(0);clock.tick(1);stats.finishJob(0);- stats.startLogging();+ await stats.startCapturing();clock.tick(50000);expect(logged).toHaveLength(0);clock.tick(10001);expect(logged).toHaveLength(1);expect(logged[0][0]).toBe('Statistics');expect(logged[0][1]).toEqual({- avgDurationMillis: 1,- perMinute: 1,- finished: 1,- failed: 0,+ crawlerRuntimeMillis: 60001,+ requestAvgFailedDurationMillis: Infinity,+ requestAvgFinishedDurationMillis: 1,+ requestTotalDurationMillis: 1,+ requestsFailedPerMinute: 0,+ requestsFinishedPerMinute: 1,+ requestsTotal: 1,retryHistogram: [1],});- stats.stopLogging();+ await stats.stopCapturing();clock.tick(60001);expect(logged).toHaveLength(1);expect(logged[0][0]).toBe('Statistics');expect(logged[0][1]).toEqual({- avgDurationMillis: 1,- perMinute: 1,- finished: 1,- failed: 0,+ crawlerRuntimeMillis: 60001,+ requestAvgFailedDurationMillis: Infinity,+ requestAvgFinishedDurationMillis: 1,+ requestTotalDurationMillis: 1,+ requestsFailedPerMinute: 0,+ requestsFinishedPerMinute: 1,+ requestsTotal: 1,retryHistogram: [1],});});++ test('should reset stats', async () => {+ await stats.startCapturing();+ stats.startJob(1);+ clock.tick(3);+ stats.finishJob(1);+ expect(stats.state.requestsFinished).toEqual(1);+ expect(stats.requestRetryHistogram).toEqual([1]);+ stats.reset();+ expect(stats.state.requestsFinished).toEqual(0);+ expect(stats.requestRetryHistogram).toEqual([]);+ });});diff --git a/test/request_list.test.js b/test/request_list.test.jsindex 082d8a28f..66e4da2c4 100644--- a/test/request_list.test.js+++ b/test/request_list.test.js@@ -403,11 +403,12 @@ describe('Apify.RequestList', () => {'should correctly persist its state when persistStateKey is set',async () => {const PERSIST_STATE_KEY = 'some-key';+ const SDK_KEY = `SDK_${PERSIST_STATE_KEY}`;const mock = sinon.mock(keyValueStore);mock.expects('getValue').once()- .withArgs(PERSIST_STATE_KEY)+ .withArgs(SDK_KEY).returns(null);const opts = {@@ -431,7 +432,7 @@ describe('Apify.RequestList', () => {// Persist state.mock.expects('setValue').once()- .withArgs(PERSIST_STATE_KEY, requestList.getState())+ .withArgs(SDK_KEY, requestList.getState()).returns(Promise.resolve());Apify.events.emit(ACTOR_EVENT_NAMES_EX.PERSIST_STATE);await utils.sleep(1);@@ -444,7 +445,7 @@ describe('Apify.RequestList', () => {expect(requestList.isStatePersisted).toBe(false);mock.expects('setValue').once()- .withArgs(PERSIST_STATE_KEY, requestList.getState())+ .withArgs(SDK_KEY, requestList.getState()).returns(Promise.resolve());Apify.events.emit(ACTOR_EVENT_NAMES_EX.PERSIST_STATE);await utils.sleep(1);@@ -458,7 +459,7 @@ describe('Apify.RequestList', () => {// of original request list.mock.expects('getValue').once()- .withArgs(PERSIST_STATE_KEY)+ .withArgs(SDK_KEY).returns(Promise.resolve(requestList.getState()));const requestList2 = new Apify.RequestList(optsCopy);await requestList2.initialize();@@ -472,6 +473,7 @@ describe('Apify.RequestList', () => {'should correctly persist its sources when persistRequestsKey is set',async () => {const PERSIST_REQUESTS_KEY = 'some-key';+ const SDK_KEY = `SDK_${PERSIST_REQUESTS_KEY}`;const getValueStub = sinon.stub(keyValueStore, 'getValue');const setValueStub = sinon.stub(keyValueStore, 'setValue');@@ -490,7 +492,7 @@ describe('Apify.RequestList', () => {expect(requestList.areRequestsPersisted).toBe(false);// Expect an attempt to load sources.- getValueStub.withArgs(PERSIST_REQUESTS_KEY)+ getValueStub.withArgs(SDK_KEY).onFirstCall().resolves(null)// See second RequestList below.@@ -500,7 +502,7 @@ describe('Apify.RequestList', () => {});// Expect persist sources.- setValueStub.withArgs(PERSIST_REQUESTS_KEY)+ setValueStub.withArgs(SDK_KEY).callsFake(async (key, value) => {persistedRequests = value;});@@ -535,6 +537,7 @@ describe('Apify.RequestList', () => {'should correctly persist sources from requestsFromUrl if persistRequestsKey is set',async () => {const PERSIST_REQUESTS_KEY = 'some-key';+ const SDK_KEY = `SDK_${PERSIST_REQUESTS_KEY}`;const kvsMock = sinon.mock(keyValueStore);const publicUtilsMock = sinon.mock(utils.publicUtils);@@ -558,13 +561,13 @@ describe('Apify.RequestList', () => {// Expect an attempt to load sources.kvsMock.expects('getValue').once()- .withArgs(PERSIST_REQUESTS_KEY)+ .withArgs(SDK_KEY).resolves(null);// Expect persist sources.kvsMock.expects('setValue').once()- .withArgs(PERSIST_REQUESTS_KEY)+ .withArgs(SDK_KEY).callsFake((key, value) => {persistedRequests = value;});@@ -724,12 +727,13 @@ describe('Apify.RequestList', () => {mock.expects('setValue').atLeast(1).resolves();const name = 'xxx';+ const SDK_KEY = `SDK_${name}`;const sources = [{ url: 'https://example.com' }];const rl = await Apify.openRequestList(name, sources);expect(rl).toBeInstanceOf(Apify.RequestList);- expect(rl.persistStateKey.startsWith(name)).toBe(true);- expect(rl.persistRequestsKey.startsWith(name)).toBe(true);+ expect(rl.persistStateKey.startsWith(SDK_KEY)).toBe(true);+ expect(rl.persistRequestsKey.startsWith(SDK_KEY)).toBe(true);expect(rl.sources).toEqual([]);expect(rl.isInitialized).toBe(true);@@ -741,13 +745,14 @@ describe('Apify.RequestList', () => {mock.expects('setValue').atLeast(1).resolves();const name = 'xxx';+ const SDK_KEY = `SDK_${name}`;const sources = ['https://example.com'];const requests = sources.map(url => new Apify.Request({ url }));const rl = await Apify.openRequestList(name, sources);expect(rl).toBeInstanceOf(Apify.RequestList);- expect(rl.persistStateKey.startsWith(name)).toBe(true);- expect(rl.persistRequestsKey.startsWith(name)).toBe(true);+ expect(rl.persistStateKey.startsWith(SDK_KEY)).toBe(true);+ expect(rl.persistRequestsKey.startsWith(SDK_KEY)).toBe(true);expect(rl.requests).toEqual(requests);expect(rl.isInitialized).toBe(true);@@ -759,6 +764,7 @@ describe('Apify.RequestList', () => {mock.expects('setValue').atLeast(1).resolves();const name = 'xxx';+ const SDK_KEY = `SDK_${name}`;let counter = 0;const sources = [{ url: 'https://example.com' }];const requests = sources.map(({ url }) => new Apify.Request({ url, uniqueKey: `${url}-${counter++}` }));@@ -769,8 +775,8 @@ describe('Apify.RequestList', () => {const rl = await Apify.openRequestList(name, sources, options);expect(rl).toBeInstanceOf(Apify.RequestList);- expect(rl.persistStateKey.startsWith(name)).toBe(true);- expect(rl.persistRequestsKey.startsWith(name)).toBe(true);+ expect(rl.persistStateKey.startsWith(SDK_KEY)).toBe(true);+ expect(rl.persistRequestsKey.startsWith(SDK_KEY)).toBe(true);expect(rl.requests).toEqual(requests);expect(rl.isInitialized).toBe(true);expect(rl.keepDuplicateUrls).toBe(true);