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
add options to get/add session to/from the pool by id (#953)
Andrey Bykovf60fde8ae988
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bea3f3b45..0aee7d542 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,7 @@1.1.0 / 2021/03/XX====================+- Add `sessionPool.addSession()` `async` function to add a new session to the session pool (possibly with the provided options, e.g. with specific session id).+- Add optional parameter `sessionId` to `sessionPool.getSession()` to be able to retrieve a session from the session pool with the specific session id.- Fix `Apify.call()` and `Apify.callTask()` output - make it backwards compatible with previous versions of the client.1.0.2 / 2021/03/05diff --git a/src/session_pool/session.js b/src/session_pool/session.jsindex 8ac714395..c073797a9 100644--- a/src/session_pool/session.js+++ b/src/session_pool/session.js@@ -293,7 +293,7 @@ export class Session {* key1=value1; key2=value2 format, ready to be used in* a cookie header or elsewhere.* @param {string} url- * @return {string} - represents `Cookie` header.+ * @return {string} represents `Cookie` header.*/getCookieString(url) {return this.cookieJar.getCookieStringSync(url, {});diff --git a/src/session_pool/session_pool.js b/src/session_pool/session_pool.jsindex f2ec767c6..c722e684e 100644--- a/src/session_pool/session_pool.js+++ b/src/session_pool/session_pool.js@@ -17,7 +17,7 @@ import { ACTOR_EVENT_NAMES_EX } from '../constants';* @typedef SessionPoolOptions* @property {number} [maxPoolSize=1000] - Maximum size of the pool.* Indicates how many sessions are rotated.- * @property {SessionOptions} [sessionOptions] The configuration options for {Session} instances.+ * @property {SessionOptions} [sessionOptions] The configuration options for {@link Session} instances.* @property {string} [persistStateKeyValueStoreId] - Name or Id of `KeyValueStore` where is the `SessionPool` state stored.* @property {string} [persistStateKey="SESSION_POOL_STATE"] - Session pool persists it's state under this key in Key value store.* @property {CreateSession} [createSessionFunction] - Custom function that should return `Session` instance.@@ -28,7 +28,7 @@ import { ACTOR_EVENT_NAMES_EX } from '../constants';/*** Handles the rotation, creation and persistence of user-like sessions.* Creates a pool of {@link Session} instances, that are randomly rotated.- * When some session is marked as blocked. It is removed and new one is created instead.+ * When some session is marked as blocked, it is removed and new one is created instead (the pool never returns an unusable session).* Learn more in the [`Session management guide`](../guides/session-management).** You can create one by calling the {@link Apify.openSessionPool} function.@@ -134,6 +134,7 @@ export class SessionPool extends EventEmitter {this.keyValueStore = null;/** @type {Session[]} */this.sessions = [];+ this.sessionMap = new Map();}/**@@ -169,26 +170,59 @@ export class SessionPool extends EventEmitter {events.on(ACTOR_EVENT_NAMES_EX.PERSIST_STATE, this._listener);}+ /**+ * Adds a new session to the session pool. The pool automatically creates sessions up to the maximum size of the pool,+ * but this allows you to add more sessions once the max pool size is reached.+ * This also allows you to add session with overridden session options (e.g. with specific session id).+ * @param {Session|SessionOptions} [options] - The configuration options for the session being added to the session pool.+ */+ async addSession(options = {}) {+ const { id } = options;+ if (id) {+ const sessionExists = this.sessionMap.has(id);+ if (sessionExists) {+ throw new Error(`Cannot add session with id '${id}' as it already exists in the pool`);+ }+ }++ if (!this._hasSpaceForSession()) {+ this._removeRetiredSessions();+ }++ const newSession = options instanceof Session+ ? options+ : await this.createSessionFunction(this, { sessionOptions: options });+ this.log.debug(`Adding new Session - ${newSession.id}`);++ this._addSession(newSession);+ }+/*** Gets session.- * If there is space for new session, it creates and return new session.+ * If there is space for new session, it creates and returns new session.* If the session pool is full, it picks a session from the pool,* If the picked session is usable it is returned, otherwise it creates and returns a new one.*+ * @param {String} [sessionId] - If provided, it returns the usable session with this id, `undefined` otherwise.* @return {Promise<Session>}*/- async getSession() {+ async getSession(sessionId) {+ if (sessionId) {+ const session = this.sessionMap.get(sessionId);+ if (session && session.isUsable()) return session;+ return;+ }+if (this._hasSpaceForSession()) {return this._createSession();}const pickedSession = this._pickSession();-if (pickedSession.isUsable()) {return pickedSession;}- this._removeSession(pickedSession);+ this._removeRetiredSessions();return this._createSession();}@@ -229,17 +263,18 @@ export class SessionPool extends EventEmitter {}/**- * Removes `Session` instance from `SessionPool`.- * @param {Session} session - Session to be removed+ * Removes retired `Session` instances from `SessionPool`.* @ignore* @protected* @internal*/- _removeSession(session) {- const sessionIndex = this.sessions.findIndex((storedSession) => storedSession.id === session.id);+ _removeRetiredSessions() {+ this.sessions = this.sessions.filter((storedSession) => {+ if (storedSession.isUsable()) return true;- const [removedSession] = this.sessions.splice(sessionIndex, 1);- this.log.debug(`Removed Session - ${removedSession.id}`);+ this.sessionMap.delete(storedSession.id);+ this.log.debug(`Removed Session - ${storedSession.id}`);+ });}/**@@ -251,6 +286,7 @@ export class SessionPool extends EventEmitter {*/_addSession(newSession) {this.sessions.push(newSession);+ this.sessionMap.set(newSession.id, newSession);}/**@@ -267,14 +303,19 @@ export class SessionPool extends EventEmitter {/*** Creates new session without any extra behavior.* @param {SessionPool} sessionPool+ * @param {Object} [options]+ * @param {SessionOptions} [options.sessionOptions] - The configuration options for the session being created* @return {Session} - New session.* @ignore* @protected* @internal*/- _defaultCreateSessionFunction(sessionPool) {+ _defaultCreateSessionFunction(sessionPool, options = {}) {+ ow(options, ow.object.exactShape({ sessionOptions: ow.optional.object }));+ const { sessionOptions = {} } = options;return new Session({...this.sessionOptions,+ ...sessionOptions,sessionPool,});}diff --git a/test/session_pool/session_pool.test.js b/test/session_pool/session_pool.test.jsindex b7dd0ada4..6def80638 100644--- a/test/session_pool/session_pool.test.js+++ b/test/session_pool/session_pool.test.js@@ -116,24 +116,17 @@ describe('SessionPool - testing session pool', () => {expect(isCalled).toBe(true); //eslint-disable-line});- test('should delete picked session when it is usable a create a new one', async () => {+ test('should delete picked session when it is unusable and create a new one', async () => {sessionPool.maxPoolSize = 1;- await sessionPool.getSession();- const session = sessionPool.sessions[0];-- session.errorScore += session.maxErrorScore;- let isCalled = false;- const oldRemove = sessionPool._removeSession; //eslint-disable-line+ await sessionPool.addSession();- sessionPool._removeSession = (session) => { //eslint-disable-line- isCalled = true;- return oldRemove.bind(sessionPool)(session);- };+ const session = await sessionPool.getSession();+ expect(sessionPool.sessions[0].id === session.id).toBe(true);+ session.errorScore += session.maxErrorScore;await sessionPool.getSession();- expect(isCalled).toBe(true); //eslint-disable-line- expect(sessionPool.sessions[0].id === session.id).toBe(false); //eslint-disable-line+ expect(sessionPool.sessions[0].id === session.id).toBe(false);expect(sessionPool.sessions).toHaveLength(1);});});@@ -238,13 +231,17 @@ describe('SessionPool - testing session pool', () => {});});- test('should remove session', async () => {- for (let i = 0; i < 10; i++) {- await sessionPool.getSession();- }- const picked = sessionPool.getSession();- sessionPool._removeSession(picked); // eslint-disable-line- expect(sessionPool.sessions.find((s) => s.id === picked.id)).toEqual(undefined);+ test('should remove retired sessions', async () => {+ sessionPool.maxPoolSize = 1;+ await sessionPool.getSession();++ const session = sessionPool.sessions[0];+ session.errorScore += session.maxErrorScore;+ const { id: retiredSessionId } = session;++ await sessionPool.getSession();++ expect(sessionPool.sessions.find((s) => s.id === retiredSessionId)).toEqual(undefined);});test('should recreate only usable sessions', async () => {@@ -310,4 +307,65 @@ describe('SessionPool - testing session pool', () => {await sessionPool.teardown();expect(events.listenerCount(ACTOR_EVENT_NAMES_EX.PERSIST_STATE)).toEqual(0);});++ test('should be able to create session with provided id', async () => {+ await sessionPool.addSession({ id: 'test-session' });+ const session = sessionPool.sessions[0];+ expect(session.id).toBe('test-session');+ });++ test('should be able to add session instance and create new session with provided sessionOptions with addSession() ', async () => {+ const session = new Apify.Session({ sessionPool, id: 'test-session-instance' });+ await sessionPool.addSession(session);++ await sessionPool.addSession({ id: 'test-session' });++ expect(await sessionPool.getSession('test-session')).toBeDefined();+ expect(await sessionPool.getSession('test-session-instance')).toBeDefined();+ });++ test('should not be able to add session to the pool with id already in the pool', async () => {+ try {+ await sessionPool.addSession({ id: 'test-session' });+ await sessionPool.addSession({ id: 'test-session' });+ } catch (e) {+ expect(e.message).toBe("Cannot add session with id 'test-session' as it already exists in the pool");+ }+ expect.assertions(1);+ });++ test('should be able to retrieve session with provided id', async () => {+ await sessionPool.addSession();+ await sessionPool.addSession({ id: 'test-session' });+ await sessionPool.addSession({ id: 'another-test-session' });++ const session = await sessionPool.getSession('test-session');+ expect(session.id).toBe('test-session');+ });++ test('should correctly populate session array and session map', async () => {+ sessionPool.maxPoolSize = 10;++ for (let i = 0; i < 20; i++) await sessionPool.getSession();++ expect(sessionPool.sessions.length).toEqual(10);+ expect(sessionPool.sessionMap.size).toEqual(10);+ expect(sessionPool.sessions.length).toEqual(sessionPool.sessionMap.size);+ });++ test('should correctly remove retired sessions both from array and session map', async () => {+ sessionPool.maxPoolSize = 10;++ for (let i = 0; i < 10; i++) {+ await sessionPool.addSession({ id: `session_${i}` });+ const session = await sessionPool.getSession(`session_${i}`);+ session.errorScore += session.maxErrorScore;+ }++ await sessionPool.getSession();++ expect(sessionPool.sessions.length).toEqual(1);+ expect(sessionPool.sessionMap.size).toEqual(1);+ expect(sessionPool.sessions.length).toEqual(sessionPool.sessionMap.size);+ });});