Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions packages/basic-crawler/src/internals/basic-crawler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1041,8 +1041,8 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContext
try {
await this.autoscaledPool!.run();
} finally {
await this.teardown();
await this.stats.stopCapturing();
await this.teardown();

process.off('SIGINT', sigintHandler);
this.events.off(EventType.MIGRATING, boundPauseOnMigration);
Expand Down Expand Up @@ -1979,10 +1979,15 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContext
* To stop the crawler gracefully (waiting for all running requests to finish), use {@apilink BasicCrawler.stop|`crawler.stop()`} instead.
*/
async teardown(): Promise<void> {
this.events.emit(EventType.PERSIST_STATE, { isMigrating: false });
// When this crawler initialized the event manager, its close() call emits
// the final persistence event after the crawler-specific state has been
// saved. External event managers still need an explicit event here.
if (!this._closeEvents) {
this.events.emit(EventType.PERSIST_STATE, { isMigrating: false });
}

if (this.useSessionPool) {
await this.sessionPool!.teardown();
await this.sessionPool!.teardown({ persistState: this._closeEvents === true });
}

if (this._closeEvents) {
Expand Down
7 changes: 5 additions & 2 deletions packages/core/src/session_pool/session_pool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -384,10 +384,13 @@ export class SessionPool extends EventEmitter {
/**
* Removes listener from `persistState` event.
* This function should be called after you are done with using the `SessionPool` instance.
* @param options - Set `persistState` to false when the final state was already persisted by the event manager.
*/
async teardown(): Promise<void> {
async teardown({ persistState = true }: { persistState?: boolean } = {}): Promise<void> {
this.events.off(EventType.PERSIST_STATE, this._listener);
await this.persistState();
if (persistState) {
await this.persistState();
}
}

/**
Expand Down
48 changes: 47 additions & 1 deletion test/core/crawlers/basic_crawler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {
RequestList,
RequestQueue,
} from '@crawlee/basic';
import { RequestState } from '@crawlee/core';
import { RequestState, SessionPool, Statistics } from '@crawlee/core';
import type { Dictionary } from '@crawlee/utils';
import { RobotsTxtFile, sleep } from '@crawlee/utils';
import express from 'express';
Expand Down Expand Up @@ -1333,6 +1333,52 @@ describe('BasicCrawler', () => {
});

describe('Uses SessionPool', () => {
it('persists statistics and the session pool once when finishing', async () => {
const persistStatistics = vitest.spyOn(Statistics.prototype, 'persistState');
const persistSessionPool = vitest.spyOn(SessionPool.prototype, 'persistState');
const config = new Configuration();
const crawler = new BasicCrawler(
{
useSessionPool: true,
requestHandler: async () => {
persistStatistics.mockClear();
persistSessionPool.mockClear();
},
},
config,
);

await crawler.run(['https://example.com']);

expect(persistStatistics).toHaveBeenCalledTimes(1);
expect(persistSessionPool).toHaveBeenCalledTimes(1);
});

it('persists the session pool once with a shared event manager', async () => {
const persistStatistics = vitest.spyOn(Statistics.prototype, 'persistState');
const persistSessionPool = vitest.spyOn(SessionPool.prototype, 'persistState');
const config = new Configuration();
await config.getEventManager().init();
const crawler = new BasicCrawler(
{
useSessionPool: true,
requestHandler: async () => {
persistStatistics.mockClear();
persistSessionPool.mockClear();
},
},
config,
);

await crawler.run(['https://example.com']);
expect(config.getEventManager().listenerCount(EventType.PERSIST_STATE)).toBe(0);
expect(persistSessionPool).toHaveBeenCalledTimes(1);
await config.getEventManager().close();

expect(persistStatistics).toHaveBeenCalledTimes(1);
expect(persistSessionPool).toHaveBeenCalledTimes(1);
});

it('should use SessionPool when useSessionPool is true ', async () => {
const url = 'https://example.com';
const requestList = await RequestList.open({ sources: [{ url }] });
Expand Down
Loading