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: don't double increment session usage count in `BrowserCrawler` (#2908)

Jindřich Bär3107e5511142
diff --git a/packages/browser-crawler/src/internals/browser-crawler.ts b/packages/browser-crawler/src/internals/browser-crawler.ts
index f15c70478..185822fa5 100644
--- a/packages/browser-crawler/src/internals/browser-crawler.ts
+++ b/packages/browser-crawler/src/internals/browser-crawler.ts
@@ -593,8 +593,6 @@ export abstract class BrowserCrawler<
throw e;
}
tryCancel();
-
- if (session) session.markGood();
}
protected _enhanceCrawlingContextWithPageInfo(
diff --git a/packages/core/src/session_pool/session.ts b/packages/core/src/session_pool/session.ts
index 81925c2eb..180dbe8a9 100644
--- a/packages/core/src/session_pool/session.ts
+++ b/packages/core/src/session_pool/session.ts
@@ -101,17 +101,49 @@ export class Session {
readonly id: string;
private maxAgeSecs: number;
userData: Dictionary;
- private maxErrorScore: number;
- private errorScoreDecrement: number;
- private createdAt: Date;
- private expiresAt: Date;
- private usageCount: number;
- private maxUsageCount: number;
+ private _maxErrorScore: number;
+ private _errorScoreDecrement: number;
+ private _createdAt: Date;
+ private _expiresAt: Date;
+ private _usageCount: number;
+ private _maxUsageCount: number;
private sessionPool: import('./session_pool').SessionPool;
- private errorScore: number;
- private cookieJar: CookieJar;
+ private _errorScore: number;
+ private _cookieJar: CookieJar;
private log: Log;
+ get errorScore() {
+ return this._errorScore;
+ }
+
+ get usageCount() {
+ return this._usageCount;
+ }
+
+ get maxErrorScore() {
+ return this._maxErrorScore;
+ }
+
+ get errorScoreDecrement() {
+ return this._errorScoreDecrement;
+ }
+
+ get expiresAt() {
+ return this._expiresAt;
+ }
+
+ get createdAt() {
+ return this._createdAt;
+ }
+
+ get maxUsageCount() {
+ return this._maxUsageCount;
+ }
+
+ get cookieJar() {
+ return this._cookieJar;
+ }
+
/**
* Session configuration.
*/
@@ -154,19 +186,19 @@ export class Session {
this.log = log.child({ prefix: 'Session' });
- this.cookieJar = (cookieJar.setCookie as unknown) ? cookieJar : CookieJar.fromJSON(JSON.stringify(cookieJar));
+ this._cookieJar = (cookieJar.setCookie as unknown) ? cookieJar : CookieJar.fromJSON(JSON.stringify(cookieJar));
this.id = id;
this.maxAgeSecs = maxAgeSecs;
this.userData = userData;
- this.maxErrorScore = maxErrorScore;
- this.errorScoreDecrement = errorScoreDecrement;
+ this._maxErrorScore = maxErrorScore;
+ this._errorScoreDecrement = errorScoreDecrement;
// Internal
- this.expiresAt = expiresAt;
- this.createdAt = createdAt;
- this.usageCount = usageCount; // indicates how many times the session has been used
- this.errorScore = errorScore; // indicates number of markBaded request with the session
- this.maxUsageCount = maxUsageCount;
+ this._expiresAt = expiresAt;
+ this._createdAt = createdAt;
+ this._usageCount = usageCount; // indicates how many times the session has been used
+ this._errorScore = errorScore; // indicates number of markBaded request with the session
+ this._maxUsageCount = maxUsageCount;
this.sessionPool = sessionPool;
}
@@ -208,10 +240,10 @@ export class Session {
* It increases `usageCount` and potentially lowers the `errorScore` by the `errorScoreDecrement`.
*/
markGood() {
- this.usageCount += 1;
+ this._usageCount += 1;
- if (this.errorScore > 0) {
- this.errorScore -= this.errorScoreDecrement;
+ if (this._errorScore > 0) {
+ this._errorScore -= this._errorScoreDecrement;
}
this._maybeSelfRetire();
@@ -245,8 +277,8 @@ export class Session {
*/
retire() {
// mark it as an invalid by increasing the error score count.
- this.errorScore += this.maxErrorScore;
- this.usageCount += 1;
+ this._errorScore += this._maxErrorScore;
+ this._usageCount += 1;
// emit event so we can retire browser in puppeteer pool
this.sessionPool.emit(EVENT_SESSION_RETIRED, this);
@@ -257,8 +289,8 @@ export class Session {
* Should be used when the session has been used unsuccessfully. For example because of timeouts.
*/
markBad() {
- this.errorScore += 1;
- this.usageCount += 1;
+ this._errorScore += 1;
+ this._usageCount += 1;
this._maybeSelfRetire();
}
diff --git a/test/core/crawlers/browser_crawler.test.ts b/test/core/crawlers/browser_crawler.test.ts
index 439a8c57c..acca42c4c 100644
--- a/test/core/crawlers/browser_crawler.test.ts
+++ b/test/core/crawlers/browser_crawler.test.ts
@@ -666,6 +666,34 @@ describe('BrowserCrawler', () => {
expect(called).toBeTruthy();
});
+ test('should increment session usage correctly', async () => {
+ const sessionUsageHistory: number[] = [];
+
+ const browserCrawler = new BrowserCrawlerTest({
+ browserPoolOptions: {
+ browserPlugins: [puppeteerPlugin],
+ },
+ useSessionPool: true,
+ sessionPoolOptions: {
+ maxPoolSize: 1,
+ },
+ requestHandler: async ({ session }) => {
+ sessionUsageHistory.push(session!.usageCount);
+ },
+ });
+
+ await browserCrawler.run([
+ { url: `${serverAddress}/?q=1` },
+ { url: `${serverAddress}/?q=2` },
+ { url: `${serverAddress}/?q=3` },
+ { url: `${serverAddress}/?q=4` },
+ { url: `${serverAddress}/?q=5` },
+ { url: `${serverAddress}/?q=6` },
+ ]);
+
+ expect(sessionUsageHistory).toEqual([0, 1, 2, 3, 4, 5]);
+ });
+
test('should allow using fingerprints from browser pool', async () => {
const requestList = await RequestList.open({
sources: [{ url: `${serverAddress}/?q=1` }],
diff --git a/test/core/crawlers/cheerio_crawler.test.ts b/test/core/crawlers/cheerio_crawler.test.ts
index 29e3379f3..64b830f63 100644
--- a/test/core/crawlers/cheerio_crawler.test.ts
+++ b/test/core/crawlers/cheerio_crawler.test.ts
@@ -909,7 +909,6 @@ describe('CheerioCrawler', () => {
expect(sessions.length).toBe(4);
sessions.forEach((session) => {
// TODO this test is flaky in CI and we need some more info to debug why.
- // @ts-expect-error Accessing private prop
if (session.errorScore !== 1) {
console.log('SESSIONS:');
@@ -950,7 +949,6 @@ describe('CheerioCrawler', () => {
// @ts-expect-error private symbol
crawler.sessionPool.sessions.forEach((session) => {
- // @ts-expect-error Accessing private prop
expect(session.errorScore).toBeGreaterThanOrEqual(session.maxErrorScore);
});
diff --git a/test/core/session_pool/session.test.ts b/test/core/session_pool/session.test.ts
index 656b76748..a56a97368 100644
--- a/test/core/session_pool/session.test.ts
+++ b/test/core/session_pool/session.test.ts
@@ -13,19 +13,14 @@ describe('Session - testing session behaviour ', () => {
});
test('should markGood session and lower the errorScore', () => {
- // @ts-expect-error Private property
expect(session.usageCount).toBe(0);
- // @ts-expect-error Private property
expect(session.errorScore).toBe(0);
session.markGood();
- // @ts-expect-error Private property
expect(session.usageCount).toBe(1);
- // @ts-expect-error Private property
expect(session.errorScore).toBe(0);
// @ts-expect-error Private property
- session.errorScore = 1;
+ session._errorScore = 1;
session.markGood();
- // @ts-expect-error Private property
expect(session.errorScore).toBe(0.5);
});
@@ -37,9 +32,7 @@ describe('Session - testing session behaviour ', () => {
test('should mark session markBad', () => {
session.markBad();
- // @ts-expect-error Private property
expect(session.errorScore).toBe(1);
- // @ts-expect-error Private property
expect(session.usageCount).toBe(1);
});
@@ -52,7 +45,7 @@ describe('Session - testing session behaviour ', () => {
test('should max out session usage', () => {
// @ts-expect-error Private property
- session.maxUsageCount = 1;
+ session._maxUsageCount = 1;
session.markGood();
expect(session.isMaxUsageCountReached()).toBe(true);
expect(session.isUsable()).toBe(false);
@@ -60,7 +53,7 @@ describe('Session - testing session behaviour ', () => {
test('should block session', () => {
// @ts-expect-error Private property
- session.errorScore += session.maxErrorScore;
+ session._errorScore += session.maxErrorScore;
expect(session.isBlocked()).toBe(true);
expect(session.isUsable()).toBe(false);
});
@@ -81,7 +74,6 @@ describe('Session - testing session behaviour ', () => {
test('should markGood session', () => {
session.markGood();
- // @ts-expect-error Private property
expect(session.usageCount).toBe(1);
expect(session.isUsable()).toBe(true);
});
@@ -94,7 +86,6 @@ describe('Session - testing session behaviour ', () => {
});
session.retire();
expect(discarded).toBe(true);
- // @ts-expect-error Private property
expect(session.usageCount).toBe(1);
});
@@ -172,7 +163,6 @@ describe('Session - testing session behaviour ', () => {
test('should use cookieJar', () => {
session = new Session({ sessionPool });
- // @ts-expect-error Private property
expect(session.cookieJar.setCookie).toBeDefined();
});
diff --git a/test/core/session_pool/session_pool.test.ts b/test/core/session_pool/session_pool.test.ts
index cfd9e205d..7ab17395c 100644
--- a/test/core/session_pool/session_pool.test.ts
+++ b/test/core/session_pool/session_pool.test.ts
@@ -135,7 +135,7 @@ describe('SessionPool - testing session pool', () => {
expect(sessionPool.sessions[0].id === session.id).toBe(true);
// @ts-expect-error Overriding private property
- session.errorScore += session.maxErrorScore;
+ session._errorScore += session.maxErrorScore;
await sessionPool.getSession();
// @ts-expect-error private symbol
@@ -274,7 +274,7 @@ describe('SessionPool - testing session pool', () => {
// @ts-expect-error private symbol
const session = sessionPool.sessions[0];
// @ts-expect-error Overriding private property
- session.errorScore += session.maxErrorScore;
+ session._errorScore += session.maxErrorScore;
const { id: retiredSessionId } = session;
await sessionPool.getSession();
@@ -290,7 +290,7 @@ describe('SessionPool - testing session pool', () => {
if (i % 2 === 0) {
// @ts-expect-error Overriding private property
- session.errorScore += session.maxErrorScore;
+ session._errorScore += session.maxErrorScore;
invalidSessionsCount += 1;
}
}
@@ -315,7 +315,6 @@ describe('SessionPool - testing session pool', () => {
const recreatedSession = await loadedSessionPool.getSession();
- // @ts-expect-error Accessing private property
expect(recreatedSession.maxUsageCount).toEqual(66);
});
@@ -426,7 +425,7 @@ describe('SessionPool - testing session pool', () => {
await sessionPool.addSession({ id: `session_${i}` });
const session = await sessionPool.getSession(`session_${i}`);
// @ts-expect-error Overriding private property
- session.errorScore += session.maxErrorScore;
+ session._errorScore += session.maxErrorScore;
}
await sessionPool.getSession();