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.

refactor!: remove the `EventEmitter` interface from `SessionPool` (#3643)

Jindřich Bär37a0c5788049
diff --git a/docs/upgrading/upgrading_v4.md b/docs/upgrading/upgrading_v4.md
index 31e4ed365..e821304de 100644
--- a/docs/upgrading/upgrading_v4.md
+++ b/docs/upgrading/upgrading_v4.md
@@ -106,9 +106,9 @@ const count = await sessionPool.usableSessionsCount();
const state = await sessionPool.getState();
```
-## Custom `createSessionFunction` receives merged session options
+## `createSessionFunction` signature has changed
-`SessionPool` now merges its pool-wide `sessionOptions` (including the pool-scoped logger) with per-call overrides before invoking `createSessionFunction`. Custom implementations no longer need to spread `pool.sessionOptions` themselves to inherit pool defaults.
+The pool-wide `sessionOptions` are now merged with per-call overrides before `createSessionFunction` is invoked, and the leading `sessionPool` argument is gone — it was only useful to pass to `new Session({ sessionPool })`, and `Session` no longer keeps a back-reference to the pool. The new signature is `(options?: { sessionOptions?: SessionOptions }) => Session | Promise<Session>`.
**Before:**
```typescript
@@ -116,7 +116,7 @@ new SessionPool({
sessionOptions: { maxUsageCount: 5 },
createSessionFunction: async (pool, opts) =>
new Session({
- ...pool.sessionOptions, // had to be spread manually for the logger / pool defaults to apply
+ ...pool.sessionOptions, // had to be spread manually for pool defaults to apply
...opts?.sessionOptions,
sessionPool: pool,
}),
@@ -127,15 +127,18 @@ new SessionPool({
```typescript
new SessionPool({
sessionOptions: { maxUsageCount: 5 },
- createSessionFunction: async (pool, opts) =>
+ createSessionFunction: async (opts) =>
new Session({
...opts?.sessionOptions, // already merged with pool-wide defaults
- sessionPool: pool,
}),
});
```
-If you were already spreading `pool.sessionOptions`, the change is harmless - pool defaults now appear twice in the spread chain, with the later (per-call) one winning, exactly as before.
+## `Session` no longer requires a `sessionPool` reference
+
+`Session` no longer holds a back-reference to its `SessionPool` and no longer emits a `sessionRetired` event when retired. The `sessionPool` constructor option is gone, `SessionPool` is no longer an `EventEmitter`, and the `EVENT_SESSION_RETIRED` constant is no longer exported.
+
+If you previously subscribed to `sessionRetired` on the pool to clean up resources tied to a session, perform the cleanup at the end of your request handler (or via a context-pipeline cleanup hook) by checking `session.isUsable()` instead. `Session.retire()` is now a terminal state — once retired, `isUsable()` returns `false` permanently and cannot be undone by a subsequent `markGood()`.
## `retireOnBlockedStatusCodes` is removed from `Session`
diff --git a/packages/basic-crawler/src/internals/basic-crawler.ts b/packages/basic-crawler/src/internals/basic-crawler.ts
index a0c1acd37..37e6b7346 100644
--- a/packages/basic-crawler/src/internals/basic-crawler.ts
+++ b/packages/basic-crawler/src/internals/basic-crawler.ts
@@ -886,15 +886,13 @@ export class BasicCrawler<
this.sessionPool =
sessionPool ??
new SessionPool({
- createSessionFunction: async (pool, opts) =>
+ createSessionFunction: async (opts) =>
new Session({
...opts?.sessionOptions,
proxyInfo:
opts?.sessionOptions?.proxyInfo ?? (await this.proxyConfiguration?.newProxyInfo()),
- sessionPool: pool,
}),
});
- this.sessionPool.setMaxListeners(20);
this.ownsSessionPool = !sessionPool;
diff --git a/packages/browser-crawler/src/internals/browser-crawler.ts b/packages/browser-crawler/src/internals/browser-crawler.ts
index ede293e63..a2f902ff2 100644
--- a/packages/browser-crawler/src/internals/browser-crawler.ts
+++ b/packages/browser-crawler/src/internals/browser-crawler.ts
@@ -18,7 +18,6 @@ import {
ContextPipeline,
cookieStringToToughCookie,
enqueueLinks,
- EVENT_SESSION_RETIRED,
handleRequestTimeout,
NavigationSkippedError,
RequestState,
@@ -36,7 +35,7 @@ import type {
InferBrowserPluginArray,
LaunchContext,
} from '@crawlee/browser-pool';
-import { BROWSER_CONTROLLER_EVENTS, BrowserPool } from '@crawlee/browser-pool';
+import { BrowserPool } from '@crawlee/browser-pool';
import type { BatchAddRequestsResult, Cookie as CookieObject } from '@crawlee/types';
import type { RobotsTxtFile } from '@crawlee/utils';
import { CLOUDFLARE_RETRY_CSS_SELECTORS, RETRY_CSS_SELECTORS, sleep } from '@crawlee/utils';
@@ -403,9 +402,21 @@ export abstract class BrowserCrawler<
action: this.preparePage.bind(this),
cleanup: async (context: {
page: Page;
+ session: Session;
+ browserController: ProvidedController;
registerDeferredCleanup: BasicCrawlingContext['registerDeferredCleanup'];
}) => {
context.registerDeferredCleanup(async () => {
+ // In non-incognito mode the browser controller carries the session's cookies
+ // and storage across pages. If the session is no longer usable, retire the
+ // controller so its state can't leak into whichever session lands on it next.
+ if (!context.session.isUsable()) {
+ this.browserPool.retireBrowserController(
+ context.browserController as Parameters<
+ BrowserPool<InternalBrowserPoolOptions>['retireBrowserController']
+ >[0],
+ );
+ }
// Puppeteer 25+ can hang `page.close()` indefinitely when the page's navigation was aborted, don't let it block the crawler.
await addTimeoutToPromise(
async () => context.page.close(),
@@ -482,8 +493,6 @@ export abstract class BrowserCrawler<
page as any,
) as ProvidedController;
- this.addSessionRetiredListener(crawlingContext.session, browserControllerInstance);
-
const contextEnqueueLinks = crawlingContext.enqueueLinks;
return {
@@ -680,39 +689,6 @@ export abstract class BrowserCrawler<
request.loadedUrl = await page.url();
}
- private browserSessionIds = new WeakMap<Context['browserController'], Set<string>>();
-
- private addSessionRetiredListener(session: Session, browserController: Context['browserController']): void {
- if (!this.sessionPool) {
- return;
- }
-
- let sessionIds = this.browserSessionIds.get(browserController);
-
- if (sessionIds) {
- sessionIds.add(session.id);
- return;
- }
-
- sessionIds = new Set([session.id]);
- this.browserSessionIds.set(browserController, sessionIds);
-
- const listener = (retired: Session) => {
- if (this.browserSessionIds.get(browserController)?.has(retired.id)) {
- this.browserPool.retireBrowserController(
- browserController as Parameters<
- BrowserPool<InternalBrowserPoolOptions>['retireBrowserController']
- >[0],
- );
- }
- };
-
- this.sessionPool.on(EVENT_SESSION_RETIRED, listener);
- browserController.on(BROWSER_CONTROLLER_EVENTS.BROWSER_CLOSED, () => {
- return this.sessionPool!.removeListener(EVENT_SESSION_RETIRED, listener);
- });
- }
-
/**
* Function for cleaning up after all requests are processed.
* @ignore
diff --git a/packages/core/src/session_pool/events.ts b/packages/core/src/session_pool/events.ts
deleted file mode 100644
index f898bc507..000000000
--- a/packages/core/src/session_pool/events.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-/** @internal */
-export const EVENT_SESSION_RETIRED = 'sessionRetired';
diff --git a/packages/core/src/session_pool/index.ts b/packages/core/src/session_pool/index.ts
index e9b252916..e158567a4 100644
--- a/packages/core/src/session_pool/index.ts
+++ b/packages/core/src/session_pool/index.ts
@@ -1,5 +1,4 @@
export * from './errors.js';
-export * from './events.js';
export * from './session.js';
export * from './session_pool.js';
export * from './consts.js';
diff --git a/packages/core/src/session_pool/session.ts b/packages/core/src/session_pool/session.ts
index 7d7efe3a7..4d5092927 100644
--- a/packages/core/src/session_pool/session.ts
+++ b/packages/core/src/session_pool/session.ts
@@ -1,5 +1,3 @@
-import { EventEmitter } from 'node:events';
-
import type { Cookie as CookieObject, Dictionary, ISession, ProxyInfo, SessionState } from '@crawlee/types';
import ow from 'ow';
import type { Cookie } from 'tough-cookie';
@@ -15,7 +13,6 @@ import {
} from '../cookie_utils.js';
import type { CrawleeLogger } from '../log.js';
import { serviceLocator } from '../service_locator.js';
-import { EVENT_SESSION_RETIRED } from './events.js';
export interface SessionOptions {
/** Id of session used for generating fingerprints. It is used as proxy session name. */
@@ -66,8 +63,12 @@ export interface SessionOptions {
*/
maxUsageCount?: number;
- /** SessionPool instance. Session will emit the `sessionRetired` event on this instance. */
- sessionPool?: import('./session_pool.js').SessionPool;
+ /**
+ * Marks the session as already retired. Used when restoring a previously persisted session
+ * so that `isUsable()` reflects the terminal state regardless of error score or usage count.
+ * @default false
+ */
+ retired?: boolean;
log?: CrawleeLogger;
errorScore?: number;
@@ -91,8 +92,8 @@ export class Session implements ISession {
private _expiresAt: Date;
private _usageCount: number;
private _maxUsageCount: number;
- private sessionPool: import('./session_pool.js').SessionPool;
private _errorScore: number;
+ private _retired = false;
private _proxyInfo?: ProxyInfo;
private _cookieJar: CookieJar;
private log: CrawleeLogger;
@@ -133,14 +134,21 @@ export class Session implements ISession {
return this._proxyInfo;
}
+ /**
+ * `true` once {@apilink Session.retire|`retire()`} has been called. Retirement is terminal:
+ * a retired session is never picked by the pool and cannot be revived via `markGood()`.
+ */
+ get retired() {
+ return this._retired;
+ }
+
/**
* Session configuration.
*/
- constructor(options: SessionOptions) {
+ constructor(options: SessionOptions = {}) {
ow(
options,
ow.object.exactShape({
- sessionPool: ow.object.instanceOf(EventEmitter),
id: ow.optional.string,
cookieJar: ow.optional.object,
proxyInfo: ow.optional.object,
@@ -153,12 +161,12 @@ export class Session implements ISession {
usageCount: ow.optional.number,
errorScore: ow.optional.number,
maxUsageCount: ow.optional.number,
+ retired: ow.optional.boolean,
log: ow.optional.object,
}),
);
const {
- sessionPool,
id = `session_${cryptoRandomObjectId(10)}`,
cookieJar = new CookieJar(),
proxyInfo = undefined,
@@ -170,6 +178,7 @@ export class Session implements ISession {
usageCount = 0,
errorScore = 0,
maxUsageCount = 50,
+ retired = false,
log = serviceLocator.getLogger(),
} = options;
@@ -191,7 +200,7 @@ export class Session implements ISession {
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;
+ this._retired = retired;
}
/**
@@ -221,10 +230,10 @@ export class Session implements ISession {
/**
* Indicates whether the session can be used for next requests.
- * Session is usable when it is not expired, not blocked and the maximum usage count has not be reached.
+ * Session is usable when it is not retired, not expired, not blocked and the maximum usage count has not be reached.
*/
isUsable(): boolean {
- return !this.isBlocked() && !this.isExpired() && !this.isMaxUsageCountReached();
+ return !this._retired && !this.isBlocked() && !this.isExpired() && !this.isMaxUsageCountReached();
}
/**
@@ -258,23 +267,22 @@ export class Session implements ISession {
usageCount: this.usageCount,
maxUsageCount: this.maxUsageCount,
errorScore: this.errorScore,
+ retired: this._retired,
};
}
/**
- * Marks session as blocked and emits event on the `SessionPool`
- * This method should be used if the session usage was unsuccessful
- * and you are sure that it is because of the session configuration and not any external matters.
- * For example when server returns 403 status code.
- * If the session does not work due to some external factors as server error such as 5XX you probably want to use `markBad` method.
+ * Permanently retires the session — `isUsable()` will return `false` from here on,
+ * and no `markGood()` / `markBad()` can revive it. Calling `retire()` again is a no-op.
+ *
+ * Use this when you're confident the session itself is the problem (e.g. a `403` response).
+ * For transient external failures (such as `5XX` responses), use `markBad()` instead.
*/
retire() {
- // mark it as an invalid by increasing the error score count.
+ if (this._retired) return;
this._errorScore += this._maxErrorScore;
this._usageCount += 1;
-
- // emit event so we can retire browser in puppeteer pool
- this.sessionPool.emit(EVENT_SESSION_RETIRED, this);
+ this._retired = true;
}
/**
diff --git a/packages/core/src/session_pool/session_pool.ts b/packages/core/src/session_pool/session_pool.ts
index 44a88c025..0c399f34c 100644
--- a/packages/core/src/session_pool/session_pool.ts
+++ b/packages/core/src/session_pool/session_pool.ts
@@ -1,5 +1,3 @@
-import { EventEmitter } from 'node:events';
-
import type { Dictionary } from '@crawlee/types';
import { AsyncQueue } from '@sapphire/async-queue';
import ow from 'ow';
@@ -22,10 +20,9 @@ export type SessionReuseStrategy = (typeof SESSION_REUSE_STRATEGIES)[number];
*/
export interface CreateSession {
/**
- * @param sessionPool Pool requesting the new session.
- * @param options
+ * @param options.sessionOptions Per-call session options already merged with the pool-wide defaults.
*/
- (sessionPool: SessionPool, options?: { sessionOptions?: SessionOptions }): Session | Promise<Session>;
+ (options?: { sessionOptions?: SessionOptions }): Session | Promise<Session>;
}
export interface SessionPoolOptions {
@@ -56,8 +53,8 @@ export interface SessionPoolOptions {
/**
* Custom function that should return a `Session` instance, or a promise resolving to such instance.
- * Any error thrown from this function will terminate the process.
- * Function receives `SessionPool` instance as a parameter
+ * Any error thrown from this function will terminate the process. Receives `{ sessionOptions }`
+ * already merged from the pool-wide defaults and the per-call overrides.
*/
createSessionFunction?: CreateSession;
@@ -132,7 +129,7 @@ export interface SessionPoolOptions {
*
* @category Scaling
*/
-export class SessionPool extends EventEmitter {
+export class SessionPool {
private static nextId = 0;
readonly id: string;
@@ -155,8 +152,6 @@ export class SessionPool extends EventEmitter {
private roundRobinIndex = 0;
constructor(options: SessionPoolOptions = {}) {
- super();
-
ow(
options,
ow.object.exactShape({
@@ -450,22 +445,15 @@ export class SessionPool extends EventEmitter {
/**
* Creates new session without any extra behavior.
- * @param sessionPool
* @param [options]
* @param [options.sessionOptions] The configuration options for the session being created.
* @returns New session.
*/
- protected async _defaultCreateSessionFunction(
- sessionPool: SessionPool,
- options: { sessionOptions?: SessionOptions } = {},
- ): Promise<Session> {
+ protected async _defaultCreateSessionFunction(options: { sessionOptions?: SessionOptions } = {}): Promise<Session> {
ow(options, ow.object.exactShape({ sessionOptions: ow.optional.object }));
const { sessionOptions = {} } = options;
- return new Session({
- ...sessionOptions,
- sessionPool,
- });
+ return new Session(sessionOptions);
}
/**
@@ -474,7 +462,7 @@ export class SessionPool extends EventEmitter {
*/
private async _invokeCreateSessionFunction(perCallOptions?: SessionOptions): Promise<Session> {
const sessionOptions = { ...this.sessionOptions, ...perCallOptions };
- return this.createSessionFunction(this, { sessionOptions });
+ return this.createSessionFunction({ sessionOptions });
}
/**
@@ -535,7 +523,6 @@ export class SessionPool extends EventEmitter {
});
for (const sessionObject of loadedSessionPool.sessions) {
- sessionObject.sessionPool = this;
sessionObject.createdAt = new Date(sessionObject.createdAt as string);
sessionObject.expiresAt = new Date(sessionObject.expiresAt as string);
const recreatedSession = await this._invokeCreateSessionFunction(sessionObject);
diff --git a/packages/types/src/session.ts b/packages/types/src/session.ts
index 9ff549ba2..1059bfb24 100644
--- a/packages/types/src/session.ts
+++ b/packages/types/src/session.ts
@@ -79,6 +79,7 @@ export interface SessionState {
maxUsageCount: number;
expiresAt: string;
createdAt: string;
+ retired: boolean;
}
/**
diff --git a/test/core/crawlers/browser_crawler.test.ts b/test/core/crawlers/browser_crawler.test.ts
index c743ed914..599221c4a 100644
--- a/test/core/crawlers/browser_crawler.test.ts
+++ b/test/core/crawlers/browser_crawler.test.ts
@@ -793,38 +793,25 @@ describe('BrowserCrawler', () => {
const requestList = await RequestList.open({
sources: [{ url: 'http://example.com/?q=1' }],
});
- let resolve: (value?: unknown) => void;
- const retirementPromise = new Promise((r) => {
- resolve = r;
- });
- let called = false;
- const browserCrawler = new (class extends BrowserCrawlerTest {
- protected override async _navigationHandler(
- ctx: TestCrawlingContext,
- ): Promise<HTTPResponse | null | undefined> {
- browserCrawler.browserPool.on(BROWSER_POOL_EVENTS.BROWSER_RETIRED, () => {
- resolve();
- called = true;
- });
- ctx.session!.retire();
- return ctx.page.goto(ctx.request.url);
- }
- })({
+ let retiredBrowserCount = 0;
+ const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
-
- requestHandler: async () => {
- await retirementPromise;
+ requestHandler: async ({ session }) => {
+ session!.retire();
},
maxRequestRetries: 1,
});
+ browserCrawler.browserPool.on(BROWSER_POOL_EVENTS.BROWSER_RETIRED, () => {
+ retiredBrowserCount += 1;
+ });
await browserCrawler.run();
- expect(called).toBeTruthy();
+ expect(retiredBrowserCount).toBeGreaterThan(0);
} finally {
await localStorageEmulator.destroy();
}
diff --git a/test/core/crawlers/puppeteer_crawler.test.ts b/test/core/crawlers/puppeteer_crawler.test.ts
index 122cc2e22..c0a2955bc 100644
--- a/test/core/crawlers/puppeteer_crawler.test.ts
+++ b/test/core/crawlers/puppeteer_crawler.test.ts
@@ -334,8 +334,8 @@ describe('PuppeteerCrawler', () => {
saveResponseCookies: true,
sessionPool: new SessionPool({
- createSessionFunction: (sessionPool) => {
- const session = new Session({ sessionPool });
+ createSessionFunction: () => {
+ const session = new Session();
session.setCookies(cookies, serverUrl);
return session;
},
diff --git a/test/core/session_pool/session.test.ts b/test/core/session_pool/session.test.ts
index 1854aaf5b..ae3ce6509 100644
--- a/test/core/session_pool/session.test.ts
+++ b/test/core/session_pool/session.test.ts
@@ -1,15 +1,13 @@
-import { EVENT_SESSION_RETIRED, log, Session, SessionPool } from '@crawlee/core';
+import { log, Session } from '@crawlee/core';
import { ResponseWithUrl } from '@crawlee/http-client';
import { entries, sleep } from '@crawlee/utils';
import { CookieJar } from 'tough-cookie';
describe('Session - testing session behaviour', () => {
- let sessionPool: SessionPool;
let session: Session;
beforeEach(() => {
- sessionPool = new SessionPool();
- session = new Session({ sessionPool });
+ session = new Session();
});
test('should markGood session and lower the errorScore', () => {
@@ -24,12 +22,6 @@ describe('Session - testing session behaviour', () => {
expect(session.errorScore).toBe(0.5);
});
- test('should throw error when param sessionPool is not EventEmitter instance', () => {
- const err = 'Expected property object `sessionPool` `{}` to be of type `EventEmitter` in object';
- // @ts-expect-error JS-side validation
- expect(() => new Session({ sessionPool: {} })).toThrow(err);
- });
-
test('should mark session markBad', () => {
session.markBad();
expect(session.errorScore).toBe(1);
@@ -37,7 +29,7 @@ describe('Session - testing session behaviour', () => {
});
test('should expire session', async () => {
- session = new Session({ maxAgeSecs: 1 / 100, sessionPool });
+ session = new Session({ maxAgeSecs: 1 / 100 });
await sleep(101);
expect(session.isExpired()).toBe(true);
expect(session.isUsable()).toBe(false);
@@ -81,14 +73,29 @@ describe('Session - testing session behaviour', () => {
});
test('should retire session', () => {
- let discarded = false;
- sessionPool.on(EVENT_SESSION_RETIRED, (ses) => {
- expect(ses instanceof Session).toBe(true);
- discarded = true;
- });
session.retire();
- expect(discarded).toBe(true);
expect(session.usageCount).toBe(1);
+ expect(session.isUsable()).toBe(false);
+ });
+
+ test('retired session stays unusable even after markGood', () => {
+ session.retire();
+ expect(session.isUsable()).toBe(false);
+
+ session.markGood();
+ expect(session.isUsable()).toBe(false);
+ });
+
+ test('retire() is idempotent', () => {
+ session.retire();
+ const errorScore = session.errorScore;
+ const usageCount = session.usageCount;
+
+ session.retire();
+ session.retire();
+
+ expect(session.errorScore).toBe(errorScore);
+ expect(session.usageCount).toBe(usageCount);
});
test('should retire session after marking bad', () => {
@@ -151,7 +158,7 @@ describe('Session - testing session behaviour', () => {
});
test('should use cookieJar', () => {
- session = new Session({ sessionPool });
+ session = new Session();
expect(session.cookieJar.setCookie).toBeDefined();
});
@@ -162,7 +169,7 @@ describe('Session - testing session behaviour', () => {
{ name: 'cookie2', value: 'your-cookie' },
];
- session = new Session({ sessionPool });
+ session = new Session();
session.setCookies(cookies, url);
expect(session.getCookieString(url)).toBe('cookie1=my-cookie; cookie2=your-cookie');
});
@@ -171,7 +178,7 @@ describe('Session - testing session behaviour', () => {
const url = 'https://example.com';
const cookies = [{ name: 'session_cookie', value: 'session-cookie-value', expires: -1 }];
- session = new Session({ sessionPool });
+ session = new Session();
session.setCookies(cookies, url);
expect(session.getCookieString(url)).toBe('session_cookie=session-cookie-value');
});
@@ -183,7 +190,7 @@ describe('Session - testing session behaviour', () => {
{ name: 'cookie2', value: 'your-cookie', domain: '.example.com' },
];
- session = new Session({ sessionPool });
+ session = new Session();
session.setCookies(cookies, url);
expect(session.getCookieString(url)).toBe('cookie2=your-cookie');
});
@@ -197,14 +204,14 @@ describe('Session - testing session behaviour', () => {
spy: true,
});
- session = new Session({ sessionPool, log: mockedLog } as any);
+ session = new Session({ log: mockedLog } as any);
session.setCookies(cookies, url);
expect(session.getCookieString(url)).toBe('');
expect(mockedLog.warning).toHaveBeenCalledOnce();
});
test('setCookie does not throw on malformed raw cookie string', () => {
- session = new Session({ sessionPool });
+ session = new Session();
expect(() => session.setCookie('garbled!!!@#$%nonsense', 'https://www.example.com')).not.toThrow();
});
@@ -215,7 +222,7 @@ describe('Session - testing session behaviour', () => {
{ name: 'cookie2', value: 'your-cookie', domain: 'example.com' },
];
- session = new Session({ sessionPool });
+ session = new Session();
session.setCookies(cookies, url);
expect(session.getCookieString(url)).toBe('');
expect(session.getCookieString('https://example.com')).toBe('cookie2=your-cookie');
@@ -225,7 +232,6 @@ describe('Session - testing session behaviour', () => {
const url = 'https://www.example.com';
session = new Session({
- sessionPool,
cookieJar: CookieJar.fromJSON(
JSON.stringify({
cookies: [
@@ -255,7 +261,6 @@ describe('Session - testing session behaviour', () => {
const url = 'https://www.example.com';
session = new Session({
- sessionPool,
cookieJar: CookieJar.fromJSON(
JSON.stringify({
cookies: [
@@ -288,7 +293,7 @@ describe('Session - testing session behaviour', () => {
headers.append('set-cookie', 'CSRF=e8b667; Domain=example.com; Secure ');
headers.append('set-cookie', 'id=a3fWa; Expires=Wed, Domain=example.com; 21 Oct 2015 07:28:00 GMT');
- const newSession = new Session({ sessionPool: new SessionPool() });
+ const newSession = new Session();
const url = 'https://example.com';
newSession.setCookiesFromResponse(new ResponseWithUrl('', { headers, url }));
let cookies = newSession.getCookieString(url);
@@ -302,13 +307,33 @@ describe('Session - testing session behaviour', () => {
});
});
+ test('retired state survives a getState() / new Session() round-trip', () => {
+ session.retire();
+
+ const old = session.getState();
+ expect(old.retired).toBe(true);
+
+ // @ts-expect-error Overriding string -> Date
+ old.createdAt = new Date(old.createdAt);
+ // @ts-expect-error Overriding string -> Date
+ old.expiresAt = new Date(old.expiresAt);
+
+ // @ts-expect-error string -> Date for createdAt has been overridden
+ const reinitialized = new Session({ ...old });
+ expect(reinitialized.retired).toBe(true);
+ expect(reinitialized.isUsable()).toBe(false);
+
+ reinitialized.markGood();
+ expect(reinitialized.isUsable()).toBe(false);
+ });
+
test('should correctly persist and init cookieJar', () => {
const headers = new Headers();
headers.append('set-cookie', 'CSRF=e8b667; Domain=example.com; Secure ');
headers.append('set-cookie', 'id=a3fWa; Expires=Wed, Domain=example.com; 21 Oct 2015 07:28:00 GMT');
- const newSession = new Session({ sessionPool: new SessionPool() });
+ const newSession = new Session();
const url = 'https://example.com';
newSession.setCookiesFromResponse(new ResponseWithUrl('', { headers, url }));
@@ -320,7 +345,7 @@ describe('Session - testing session behaviour', () => {
old.expiresAt = new Date(old.expiresAt);
// @ts-expect-error string -> Date for createdAt has been overridden
- const reinitializedSession = new Session({ sessionPool, ...old });
+ const reinitializedSession = new Session({ ...old });
expect(reinitializedSession.getCookieString(url)).toEqual('CSRF=e8b667; id=a3fWa');
});
});
diff --git a/test/core/session_pool/session_pool.test.ts b/test/core/session_pool/session_pool.test.ts
index 2cc1782e5..d1bfa91da 100644
--- a/test/core/session_pool/session_pool.test.ts
+++ b/test/core/session_pool/session_pool.test.ts
@@ -69,8 +69,6 @@ describe('SessionPool - testing session pool', () => {
expect(session.maxAgeSecs).toEqual(sessionPool.sessionOptions.maxAgeSecs);
// @ts-expect-error Accessing private property
expect(session.maxUsageCount).toEqual(sessionPool.sessionOptions.maxUsageCount);
- // @ts-expect-error Accessing private property
- expect(session.sessionPool).toEqual(sessionPool);
});
test('should pick session when pool is full', async () => {
@@ -331,15 +329,17 @@ describe('SessionPool - testing session pool', () => {
});
test('should createSessionFunction work', async () => {
- let isCalled;
- const createSessionFunction = (sessionPool2: SessionPool) => {
+ let isCalled = false;
+ let receivedOptions: { sessionOptions?: object } | undefined;
+ const createSessionFunction = (opts?: { sessionOptions?: object }) => {
isCalled = true;
- expect(sessionPool2 instanceof SessionPool).toBe(true);
- return new Session({ sessionPool: sessionPool2 });
+ receivedOptions = opts;
+ return new Session();
};
const newSessionPool = new SessionPool({ createSessionFunction });
const session = await newSessionPool.getSession();
expect(isCalled).toBe(true);
+ expect(receivedOptions?.sessionOptions).toBeDefined();
expect(session.constructor.name).toBe('Session');
});
@@ -360,7 +360,7 @@ describe('SessionPool - testing session pool', () => {
});
test('should be able to add session instance and create new session with provided sessionOptions with addSession()', async () => {
- const session = new Session({ sessionPool, id: 'test-session-instance' });
+ const session = new Session({ id: 'test-session-instance' });
await sessionPool.addSession(session);
await sessionPool.addSession({ id: 'test-session' });