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.

feat: added docs and handling of aborting event into basic crawler (#1052)

Jakub Drobník9f9e503497af
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6c5126df3..e0c86f045 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -48,6 +48,7 @@ await dataset.pushData({ myValue: 123 });
- Update `puppeteer` and `playwright` to match stable Chrome (90).
- Fix support for building TypeScript projects that depend on the SDK.
- add `taskTimeoutSecs` to allow control over timeout of `AutoscaledPool` tasks
+- Added new event `aborting` for handling gracefully aborted run from Apify platform.
1.2.1 / 2021/05/14
====================
diff --git a/src/constants.js b/src/constants.js
index 075a134a2..683fa5d22 100644
--- a/src/constants.js
+++ b/src/constants.js
@@ -21,7 +21,7 @@ export const EXIT_CODES = {
/**
* These events are just internal for Apify package, so we don't need them in apify-shared package.
*
- * @type {{CPU_INFO: string, SYSTEM_INFO: string, MIGRATING: string, PERSIST_STATE: string}}
+ * @type {{CPU_INFO: string, SYSTEM_INFO: string, MIGRATING: string, PERSIST_STATE: string, ABORTING: string}}
*/
export const ACTOR_EVENT_NAMES_EX = { ...ACTOR_EVENT_NAMES, PERSIST_STATE: 'persistState' };
diff --git a/src/crawlers/basic_crawler.js b/src/crawlers/basic_crawler.js
index add246fc0..6f272d14e 100644
--- a/src/crawlers/basic_crawler.js
+++ b/src/crawlers/basic_crawler.js
@@ -318,8 +318,9 @@ export class BasicCrawler {
this.isRunningPromise = null;
- // Attach a listener to handle migration events gracefully.
+ // Attach a listener to handle migration and aborting events gracefully.
events.on(ACTOR_EVENT_NAMES.MIGRATING, this._pauseOnMigration.bind(this));
+ events.on(ACTOR_EVENT_NAMES.ABORTING, this._pauseOnMigration.bind(this));
}
/**
diff --git a/test/crawlers/basic_crawler.test.js b/test/crawlers/basic_crawler.test.js
index c171a4e07..acc8a36f3 100644
--- a/test/crawlers/basic_crawler.test.js
+++ b/test/crawlers/basic_crawler.test.js
@@ -56,55 +56,52 @@ describe('BasicCrawler', () => {
expect(await requestList.isEmpty()).toBe(true);
});
- test(
- 'should pause on migration event and persist RequestList state',
- async () => {
- const sources = _.range(500).map((index) => ({ url: `https://example.com/${index + 1}` }));
+ test.each([ACTOR_EVENT_NAMES.MIGRATING, ACTOR_EVENT_NAMES.ABORTING])('should pause on %s event and persist RequestList state', async (event) => {
+ const sources = _.range(500).map((index) => ({ url: `https://example.com/${index + 1}` }));
- let persistResolve;
- const persistPromise = new Promise((res) => { persistResolve = res; });
+ let persistResolve;
+ const persistPromise = new Promise((res) => { persistResolve = res; });
- // Mock the calls to persist sources.
- const mock = sinon.mock(keyValueStore);
- mock.expects('getValue').twice().resolves(null);
- mock.expects('setValue').once().resolves();
+ // Mock the calls to persist sources.
+ const mock = sinon.mock(keyValueStore);
+ mock.expects('getValue').twice().resolves(null);
+ mock.expects('setValue').once().resolves();
- const processed = [];
- const requestList = await Apify.openRequestList('reqList', sources);
- const handleRequestFunction = async ({ request }) => {
- if (request.url.endsWith('200')) Apify.events.emit(ACTOR_EVENT_NAMES.MIGRATING);
- processed.push(_.pick(request, 'url'));
- };
+ const processed = [];
+ const requestList = await Apify.openRequestList('reqList', sources);
+ const handleRequestFunction = async ({ request }) => {
+ if (request.url.endsWith('200')) Apify.events.emit(event);
+ processed.push(_.pick(request, 'url'));
+ };
- const basicCrawler = new Apify.BasicCrawler({
- requestList,
- minConcurrency: 25,
- maxConcurrency: 25,
- handleRequestFunction,
- });
+ const basicCrawler = new Apify.BasicCrawler({
+ requestList,
+ minConcurrency: 25,
+ maxConcurrency: 25,
+ handleRequestFunction,
+ });
- let finished = false;
- // Mock the call to persist state.
- mock.expects('setValue').once().callsFake(async () => { persistResolve(); });
- // The crawler will pause after 200 requests
- const runPromise = basicCrawler.run();
- runPromise.then(() => { finished = true; });
+ let finished = false;
+ // Mock the call to persist state.
+ mock.expects('setValue').once().callsFake(async () => { persistResolve(); });
+ // The crawler will pause after 200 requests
+ const 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;
+ // need to monkeypatch the stats class, otherwise it will never finish
+ basicCrawler.stats.persistState = () => Promise.resolve();
+ await persistPromise;
- expect(finished).toBe(false);
- expect(await requestList.isFinished()).toBe(false);
- expect(await requestList.isEmpty()).toBe(false);
- expect(processed.length).toBe(200);
+ expect(finished).toBe(false);
+ expect(await requestList.isFinished()).toBe(false);
+ expect(await requestList.isEmpty()).toBe(false);
+ expect(processed.length).toBe(200);
- mock.verify();
+ mock.verify();
- // clean up
- await basicCrawler.autoscaledPool._destroy(); // eslint-disable-line no-underscore-dangle
- },
- );
+ // clean up
+ await basicCrawler.autoscaledPool._destroy(); // eslint-disable-line no-underscore-dangle
+ });
test('should retry failed requests', async () => {
const sources = [
diff --git a/website/versioned_docs/version-1.0.2/api/Apify.md b/website/versioned_docs/version-1.0.2/api/Apify.md
index b9f3e7982..e43a35fa1 100644
--- a/website/versioned_docs/version-1.0.2/api/Apify.md
+++ b/website/versioned_docs/version-1.0.2/api/Apify.md
@@ -246,6 +246,8 @@ The following events are emitted:
time to persist their state, in order to avoid repeating all work when the actor restarts. This event is automatically emitted together with the
`migrating` event, in which case the `isMigrating` flag is set to `true`. Otherwise the flag is `false`. Note that the `persistState` event is
provided merely for user convenience, you can achieve the same effect using `setInterval()` and listening for the `migrating` event.
+- `aborting`: `void` Emitted when the actor running on the Apify platform was aborted by user with gracefully abort flag. You can use it to
+ persist the state of the actor graceful abort run.
---