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
feat: store `ProxyInfo` inside `Session` instances (#3199)
Jindřich Bär14ed530b3cec
diff --git a/packages/basic-crawler/src/internals/basic-crawler.ts b/packages/basic-crawler/src/internals/basic-crawler.tsindex 60301f8df..c9ffd54c2 100644--- a/packages/basic-crawler/src/internals/basic-crawler.ts+++ b/packages/basic-crawler/src/internals/basic-crawler.ts@@ -14,6 +14,7 @@ import type {GetUserDataFromRequest,IRequestList,IRequestManager,+ ProxyConfiguration,ProxyInfo,Request,RequestsLike,@@ -384,6 +385,12 @@ export interface BasicCrawlerOptions<* Defaults to a new instance of {@apilink GotScrapingHttpClient}*/httpClient?: BaseHttpClient;++ /**+ * If set, the crawler will be configured for all connections to use+ * the Proxy URLs provided and rotated according to the configuration.+ */+ proxyConfiguration?: ProxyConfiguration;}/**@@ -511,6 +518,12 @@ export class BasicCrawler<*/autoscaledPool?: AutoscaledPool;+ /**+ * A reference to the underlying {@apilink ProxyConfiguration} class that manages the crawler's proxies.+ * Only available if used by the crawler.+ */+ proxyConfiguration?: ProxyConfiguration;+/*** Default {@apilink Router} instance that will be used if we don't specify any {@apilink BasicCrawlerOptions.requestHandler|`requestHandler`}.* See {@apilink Router.addHandler|`router.addHandler()`} and {@apilink Router.addDefaultHandler|`router.addDefaultHandler()`}.@@ -594,6 +607,7 @@ export class BasicCrawler<autoscaledPoolOptions: ow.optional.object,sessionPoolOptions: ow.optional.object,useSessionPool: ow.optional.boolean,+ proxyConfiguration: ow.optional.object.validate(validators.proxyConfiguration),statusMessageLoggingInterval: ow.optional.number,statusMessageCallback: ow.optional.function,@@ -639,6 +653,7 @@ export class BasicCrawler<keepAlive,sessionPoolOptions = {},useSessionPool = true,+ proxyConfiguration,// AutoscaledPool shorthandsminConcurrency,@@ -710,6 +725,7 @@ export class BasicCrawler<}this.httpClient = httpClient ?? new GotScrapingHttpClient();+ this.proxyConfiguration = proxyConfiguration;this.log = log;this.statusMessageLoggingInterval = statusMessageLoggingInterval;this.statusMessageCallback = statusMessageCallback as StatusMessageCallback;@@ -1579,7 +1595,14 @@ export class BasicCrawler<const session = this.useSessionPool? await this._timeoutAndRetry(- this.sessionPool!.getSession.bind(this.sessionPool),+ async () => {+ return await this.sessionPool!.newSession({+ proxyInfo: await this.proxyConfiguration?.newProxyInfo({+ request: request ?? undefined,+ }),+ maxUsageCount: 1,+ });+ },this.internalTimeoutMillis,`Fetching session timed out after ${this.internalTimeoutMillis / 1e3} seconds.`,)@@ -1618,6 +1641,7 @@ export class BasicCrawler<log: this.log,request,session,+ proxyInfo: session?.proxyInfo,enqueueLinks: async (options) => {const requestQueue = await this.getRequestQueue();@@ -1631,7 +1655,7 @@ export class BasicCrawler<},pushData: this.pushData.bind(this),useState: this.useState.bind(this),- sendRequest: createSendRequest(this.httpClient, request, session, () => crawlingContext.proxyInfo?.url),+ sendRequest: createSendRequest(this.httpClient, request!, session),getKeyValueStore: async (idOrName?: string) => KeyValueStore.open(idOrName, { config: this.config }),registerDeferredCleanup: (cleanup) => {deferredCleanup.push(cleanup);diff --git a/packages/basic-crawler/src/internals/send-request.ts b/packages/basic-crawler/src/internals/send-request.tsindex 263089a6c..249a968ae 100644--- a/packages/basic-crawler/src/internals/send-request.ts+++ b/packages/basic-crawler/src/internals/send-request.ts@@ -16,12 +16,7 @@ import type { Method, Response as GotResponse } from 'got-scraping';* @param session The user session associated with the current request.* @param getProxyUrl A function that will return the proxy URL that should be used for handling the request.*/-export function createSendRequest(- httpClient: BaseHttpClient,- originRequest: Request,- session: Session | undefined,- getProxyUrl: () => string | undefined,-) {+export function createSendRequest(httpClient: BaseHttpClient, originRequest: Request, session: Session | undefined) {return async <Response = string>(// TODO the type information here (and in crawler_commons) is outright wrong... for BC - replace this with generic HttpResponse in v4overrideOptions: Partial<HttpRequestOptions> = {},@@ -38,7 +33,7 @@ export function createSendRequest(url: originRequest.url,method: originRequest.method as Method, // Narrow type to omit CONNECTheaders: originRequest.headers,- proxyUrl: getProxyUrl(),+ proxyUrl: session?.proxyInfo?.url,sessionToken: session,responseType: 'text',...overrideOptions,diff --git a/packages/browser-crawler/src/internals/browser-crawler.ts b/packages/browser-crawler/src/internals/browser-crawler.tsindex 23a39653b..f39a3347e 100644--- a/packages/browser-crawler/src/internals/browser-crawler.ts+++ b/packages/browser-crawler/src/internals/browser-crawler.ts@@ -7,7 +7,6 @@ import type {EnqueueLinksOptions,ErrorHandler,LoadedRequest,- ProxyConfiguration,ProxyInfo,Request,RequestHandler,@@ -177,12 +176,6 @@ export interface BrowserCrawlerOptions<browserPoolOptions?: Partial<BrowserPoolOptions> &Partial<BrowserPoolHooks<__BrowserControllerReturn, __LaunchContextReturn>>;- /**- * If set, the crawler will be configured for all connections to use- * the Proxy URLs provided and rotated according to the configuration.- */- proxyConfiguration?: ProxyConfiguration;-/*** Async functions that are sequentially evaluated before the navigation. Good for setting additional cookies* or browser properties before navigation. The function accepts two parameters, `crawlingContext` and `gotoOptions`,@@ -310,12 +303,6 @@ export abstract class BrowserCrawler<ExtendedContext extends Context = Context & ContextExtension,GoToOptions extends Dictionary = Dictionary,> extends BasicCrawler<Context, ContextExtension, ExtendedContext> {- /**- * A reference to the underlying {@apilink ProxyConfiguration} class that manages the crawler's proxies.- * Only available if used by the crawler.- */- proxyConfiguration?: ProxyConfiguration;-/*** A reference to the underlying {@apilink BrowserPool} class that manages the crawler's browsers.*/@@ -367,7 +354,6 @@ export abstract class BrowserCrawler<const {navigationTimeoutSecs = 60,persistCookiesPerSession,- proxyConfiguration,launchContext = {},browserPoolOptions,preNavigationHooks = [],@@ -377,6 +363,7 @@ export abstract class BrowserCrawler<ignoreShadowRoots = false,contextPipelineBuilder,extendContext,+ proxyConfiguration,...basicCrawlerOptions} = options;@@ -514,18 +501,14 @@ export abstract class BrowserCrawler<const useIncognitoPages = this.launchContext?.useIncognitoPages;- if (this.proxyConfiguration) {- const { session } = crawlingContext;-- const proxyInfo = await this.proxyConfiguration.newProxyInfo(session?.id, {- request: crawlingContext.request,- });+ if (crawlingContext.session?.proxyInfo) {+ const proxyInfo = crawlingContext.session.proxyInfo;crawlingContext.proxyInfo = proxyInfo;newPageOptions.proxyUrl = proxyInfo?.url;newPageOptions.proxyTier = proxyInfo?.proxyTier;- if (this.proxyConfiguration.isManInTheMiddle) {+ if (proxyInfo?.ignoreTlsErrors) {/*** @see https://playwright.dev/docs/api/class-browser/#browser-new-context* @see https://github.com/puppeteer/puppeteer/blob/main/docs/api.md@@ -546,6 +529,10 @@ export abstract class BrowserCrawler<const contextEnqueueLinks = crawlingContext.enqueueLinks;+ const session = useIncognitoPages+ ? crawlingContext.session+ : (browserControllerInstance.launchContext.session as Session);+return {page,get response(): Response {@@ -554,10 +541,8 @@ export abstract class BrowserCrawler<);},browserController: browserControllerInstance,- session: useIncognitoPages- ? crawlingContext.session- : (browserControllerInstance.launchContext.session as Session),- proxyInfo: crawlingContext.proxyInfo ?? (browserControllerInstance.launchContext.proxyInfo as ProxyInfo),+ session,+ proxyInfo: session?.proxyInfo,enqueueLinks: async (enqueueOptions: EnqueueLinksOptions = {}) => {return (await browserCrawlerEnqueueLinks({// `contextEnqueueLinks` clamps `limit` by the remaining `maxRequestsPerCrawl` budget itself;@@ -738,18 +723,21 @@ export abstract class BrowserCrawler<const launchContextExtends: { session?: Session; proxyInfo?: ProxyInfo } = {};if (this.sessionPool) {- launchContextExtends.session = await this.sessionPool.getSession();+ launchContextExtends.session = await this.sessionPool.newSession({+ proxyInfo: await this.proxyConfiguration?.newProxyInfo({+ // cannot pass a request here, since session is created on browser launch+ }),+ });}- if (this.proxyConfiguration && !launchContext.proxyUrl) {- const proxyInfo = await this.proxyConfiguration.newProxyInfo(launchContextExtends.session?.id, {- proxyTier: (launchContext.proxyTier as number) ?? undefined,- });+ if (!launchContext.proxyUrl && launchContextExtends.session?.proxyInfo) {+ const proxyInfo = launchContextExtends.session.proxyInfo;+launchContext.proxyUrl = proxyInfo?.url;launchContextExtends.proxyInfo = proxyInfo;// Disable SSL verification for MITM proxies- if (this.proxyConfiguration.isManInTheMiddle) {+ if (proxyInfo?.ignoreTlsErrors) {/*** @see https://playwright.dev/docs/api/class-browser/#browser-new-context* @see https://github.com/puppeteer/puppeteer/blob/main/docs/api.mddiff --git a/packages/core/src/proxy_configuration.ts b/packages/core/src/proxy_configuration.tsindex d2f402db4..cc9ede3ce 100644--- a/packages/core/src/proxy_configuration.ts+++ b/packages/core/src/proxy_configuration.ts@@ -2,12 +2,11 @@ import type { Dictionary } from '@crawlee/types';import ow from 'ow';import log from '@apify/log';-import { cryptoRandomObjectId } from '@apify/utilities';import type { Request } from './request.js';export interface ProxyConfigurationFunction {- (sessionId: string | number, options?: { request?: Request }): string | null | Promise<string | null>;+ (options?: { request?: Request }): string | null | Promise<string | null>;}type UrlList = (string | null)[];@@ -21,7 +20,7 @@ export interface ProxyConfigurationOptions {proxyUrls?: UrlList;/**- * Custom function that allows you to generate the new proxy URL dynamically. It gets the `sessionId` as a parameter and an optional parameter with the `Request` object when applicable.+ * Custom function that allows you to generate the new proxy URL dynamically. It gets an optional parameter with the `Request` object when applicable.* Can return either stringified proxy URL or `null` if the proxy should not be used. Can be asynchronous.** This function is used to generate the URL when {@apilink ProxyConfiguration.newUrl} or {@apilink ProxyConfiguration.newProxyInfo} is called.@@ -69,20 +68,12 @@ export interface TieredProxy {* requestHandler({ proxyInfo }) {* // Getting used proxy URL* const proxyUrl = proxyInfo.url;- *- * // Getting ID of used Session- * const sessionIdentifier = proxyInfo.sessionId;* }* })** ```*/export interface ProxyInfo {- /**- * The identifier of used {@apilink Session}, if used.- */- sessionId?: string;-/*** The URL of the proxy.*/@@ -112,6 +103,13 @@ export interface ProxyInfo {* Proxy tier for the current proxy, if applicable (only for `tieredProxyUrls`).*/proxyTier?: number;++ /**+ * When `true`, the proxy is likely intercepting HTTPS traffic and is able to view and modify its content.+ *+ * @default false+ */+ ignoreTlsErrors?: boolean;}interface TieredProxyOptions {@@ -260,28 +258,18 @@ export class ProxyConfiguration {* the currently used proxy via the requestHandler parameter `proxyInfo`.* Use it if you want to work with a rich representation of a proxy URL.* If you need the URL string only, use {@apilink ProxyConfiguration.newUrl}.- * @param [sessionId]- * Represents the identifier of user {@apilink Session} that can be managed by the {@apilink SessionPool} or- * you can use the Apify Proxy [Session](https://docs.apify.com/proxy#sessions) identifier.- * When the provided sessionId is a number, it's converted to a string. Property sessionId of- * {@apilink ProxyInfo} is always returned as a type string.*- * All the HTTP requests going through the proxy with the same session identifier- * will use the same target proxy server (i.e. the same IP address).- * The identifier must not be longer than 50 characters and include only the following: `0-9`, `a-z`, `A-Z`, `"."`, `"_"` and `"~"`.* @return Represents information about used proxy and its configuration.*/- async newProxyInfo(sessionId?: string | number, options?: TieredProxyOptions): Promise<ProxyInfo | undefined> {- if (typeof sessionId === 'number') sessionId = `${sessionId}`;-+ async newProxyInfo(options?: TieredProxyOptions): Promise<ProxyInfo | undefined> {let url: string | undefined;let tier: number | undefined;if (this.tieredProxyUrls) {- const { proxyUrl, proxyTier } = this._handleTieredUrl(sessionId ?? cryptoRandomObjectId(6), options);+ const { proxyUrl, proxyTier } = this._handleTieredUrl(options);url = proxyUrl ?? undefined;tier = proxyTier;} else {- url = await this.newUrl(sessionId, options);+ url = await this.newUrl(options);}if (!url) return undefined;@@ -289,7 +277,6 @@ export class ProxyConfiguration {const { username, password, port, hostname } = new URL(url);return {- sessionId,url,username: decodeURIComponent(username),password: decodeURIComponent(password),@@ -300,12 +287,11 @@ export class ProxyConfiguration {}/**- * Given a session identifier and a request / proxy tier, this function returns a new proxy URL based on the provided configuration options.- * @param _sessionId Session identifier+ * Given a request / proxy tier, this function returns a new proxy URL based on the provided configuration options.* @param options Options for the tiered proxy rotation* @returns An object with the proxy URL and the proxy tier used.*/- protected _handleTieredUrl(_sessionId: string, options?: TieredProxyOptions): TieredProxy {+ protected _handleTieredUrl(options?: TieredProxyOptions): TieredProxy {if (!this.tieredProxyUrls) throw new Error('Tiered proxy URLs are not set');if (!options || (!options?.request && options?.proxyTier === undefined)) {@@ -368,57 +354,32 @@ export class ProxyConfiguration {}/**- * Returns a new proxy URL based on provided configuration options and the `sessionId` parameter.- * @param [sessionId]- * Represents the identifier of user {@apilink Session} that can be managed by the {@apilink SessionPool} or- * you can use the Apify Proxy [Session](https://docs.apify.com/proxy#sessions) identifier.- * When the provided sessionId is a number, it's converted to a string.+ * Returns a new proxy URL based on provided configuration options.*- * All the HTTP requests going through the proxy with the same session identifier- * will use the same target proxy server (i.e. the same IP address).- * The identifier must not be longer than 50 characters and include only the following: `0-9`, `a-z`, `A-Z`, `"."`, `"_"` and `"~"`.* @return A string with a proxy URL, including authentication credentials and port number.* For example, `http://bob:[email protected]:8000`*/- async newUrl(sessionId?: string | number, options?: TieredProxyOptions): Promise<string | undefined> {- if (typeof sessionId === 'number') sessionId = `${sessionId}`;-+ async newUrl(options?: TieredProxyOptions): Promise<string | undefined> {if (this.newUrlFunction) {- return (await this._callNewUrlFunction(sessionId, { request: options?.request })) ?? undefined;+ return (await this._callNewUrlFunction({ request: options?.request })) ?? undefined;}if (this.tieredProxyUrls) {- return this._handleTieredUrl(sessionId ?? cryptoRandomObjectId(6), options).proxyUrl ?? undefined;+ return this._handleTieredUrl(options).proxyUrl ?? undefined;}- return this._handleCustomUrl(sessionId) ?? undefined;+ return this._handleProxyUrlsList() ?? undefined;}- /**- * Handles custom url rotation with session- */- protected _handleCustomUrl(sessionId?: string): string | null {- let customUrlToUse: string | null;-- if (!sessionId) {- return this.proxyUrls![this.nextCustomUrlIndex++ % this.proxyUrls!.length];- }-- if (this.usedProxyUrls.has(sessionId)) {- customUrlToUse = this.usedProxyUrls.get(sessionId)!;- } else {- customUrlToUse = this.proxyUrls![this.nextCustomUrlIndex++ % this.proxyUrls!.length];- this.usedProxyUrls.set(sessionId, customUrlToUse);- }-- return customUrlToUse;+ protected _handleProxyUrlsList(): string | null {+ return this.proxyUrls![this.nextCustomUrlIndex++ % this.proxyUrls!.length];}/*** Calls the custom newUrlFunction and checks format of its return value*/- protected async _callNewUrlFunction(sessionId?: string, options?: { request?: Request }) {- const proxyUrl = await this.newUrlFunction!(sessionId!, options);+ protected async _callNewUrlFunction(options?: { request?: Request }) {+ const proxyUrl = await this.newUrlFunction!(options);try {if (proxyUrl) {new URL(proxyUrl); // eslint-disable-line no-newdiff --git a/packages/core/src/session_pool/session.ts b/packages/core/src/session_pool/session.tsindex 8bb998a0d..6bb783dda 100644--- a/packages/core/src/session_pool/session.ts+++ b/packages/core/src/session_pool/session.ts@@ -16,6 +16,7 @@ import {toughCookieToBrowserPoolCookie,} from '../cookie_utils.js';import { log as defaultLog } from '../log.js';+import type { ProxyInfo } from '../proxy_configuration.js';import { EVENT_SESSION_RETIRED } from './events.js';/**@@ -24,6 +25,7 @@ import { EVENT_SESSION_RETIRED } from './events.js';export interface SessionState {id: string;cookieJar: SerializedCookieJar;+ proxyInfo?: ProxyInfo;userData: object;errorScore: number;maxErrorScore: number;@@ -89,6 +91,7 @@ export interface SessionOptions {log?: Log;errorScore?: number;cookieJar?: CookieJar;+ proxyInfo?: ProxyInfo;}/**@@ -109,6 +112,7 @@ export class Session {private _maxUsageCount: number;private sessionPool: import('./session_pool.js').SessionPool;private _errorScore: number;+ private _proxyInfo?: ProxyInfo;private _cookieJar: CookieJar;private log: Log;@@ -144,6 +148,10 @@ export class Session {return this._cookieJar;}+ get proxyInfo() {+ return this._proxyInfo;+ }+/*** Session configuration.*/@@ -154,6 +162,7 @@ export class Session {sessionPool: ow.object.instanceOf(EventEmitter),id: ow.optional.string,cookieJar: ow.optional.object,+ proxyInfo: ow.optional.object,maxAgeSecs: ow.optional.number,userData: ow.optional.object,maxErrorScore: ow.optional.number,@@ -171,6 +180,7 @@ export class Session {sessionPool,id = `session_${cryptoRandomObjectId(10)}`,cookieJar = new CookieJar(),+ proxyInfo = undefined,maxAgeSecs = 3000,userData = {},maxErrorScore = 3,@@ -187,6 +197,7 @@ export class Session {this.log = log.child({ prefix: 'Session' });this._cookieJar = (cookieJar.setCookie as unknown) ? cookieJar : CookieJar.fromJSON(JSON.stringify(cookieJar));+ this._proxyInfo = proxyInfo;this.id = id;this.maxAgeSecs = maxAgeSecs;this.userData = userData;@@ -257,6 +268,7 @@ export class Session {return {id: this.id,cookieJar: this.cookieJar.toJSON()!,+ proxyInfo: this._proxyInfo,userData: this.userData,maxErrorScore: this.maxErrorScore,errorScoreDecrement: this.errorScoreDecrement,diff --git a/packages/core/src/session_pool/session_pool.ts b/packages/core/src/session_pool/session_pool.tsindex cfb271922..0abc5aed7 100644--- a/packages/core/src/session_pool/session_pool.ts+++ b/packages/core/src/session_pool/session_pool.ts@@ -47,7 +47,7 @@ export interface SessionPoolOptions {persistStateKey?: string;/**- * Custom function that should return `Session` instance.+ * 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*/@@ -282,6 +282,21 @@ export class SessionPool extends EventEmitter {this._addSession(newSession);}+ /**+ * 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 [options] The configuration options for the session being added to the session pool.+ */+ async newSession(sessionOptions?: SessionOptions): Promise<Session> {+ this._throwIfNotInitialized();++ const newSession = await this.createSessionFunction(this, { sessionOptions });+ this._addSession(newSession);++ return newSession;+ }+/*** Gets session.* If there is space for new session, it creates and returns new session.@@ -437,12 +452,13 @@ export class SessionPool extends EventEmitter {* @param [options.sessionOptions] The configuration options for the session being created.* @returns New session.*/- protected _defaultCreateSessionFunction(+ protected async _defaultCreateSessionFunction(sessionPool: SessionPool,options: { sessionOptions?: SessionOptions } = {},- ): Session {+ ): Promise<Session> {ow(options, ow.object.exactShape({ sessionOptions: ow.optional.object }));const { sessionOptions = {} } = options;+return new Session({...this.sessionOptions,...sessionOptions,diff --git a/packages/http-crawler/src/internals/http-crawler.ts b/packages/http-crawler/src/internals/http-crawler.tsindex 1b00549f1..afc10b919 100644--- a/packages/http-crawler/src/internals/http-crawler.ts+++ b/packages/http-crawler/src/internals/http-crawler.ts@@ -8,7 +8,6 @@ import type {CrawlingContext,ErrorHandler,GetUserDataFromRequest,- ProxyConfiguration,Request,RequestHandler,RequireContextPipeline,@@ -28,9 +27,8 @@ import {RequestState,Router,SessionError,- validators,} from '@crawlee/basic';-import type { HttpResponse, LoadedRequest, ProxyInfo, StreamingHttpResponse } from '@crawlee/core';+import type { HttpResponse, LoadedRequest, StreamingHttpResponse } from '@crawlee/core';import type { Awaitable, Dictionary } from '@crawlee/types';import { type CheerioRoot, RETRY_CSS_SELECTORS } from '@crawlee/utils';import * as cheerio from 'cheerio';@@ -92,13 +90,6 @@ export interface HttpCrawlerOptions<*/ignoreSslErrors?: boolean;- /**- * If set, this crawler will be configured for all connections to use- * [Apify Proxy](https://console.apify.com/proxy) or your own Proxy URLs provided and rotated according to the configuration.- * For more information, see the [documentation](https://docs.apify.com/proxy).- */- proxyConfiguration?: ProxyConfiguration;-/*** Async functions that are sequentially evaluated before the navigation. Good for setting additional cookies* or browser properties before navigation. The function accepts two parameters, `crawlingContext` and `gotOptions`,@@ -341,12 +332,6 @@ export class HttpCrawler<ContextExtension = {},ExtendedContext extends Context = Context & ContextExtension,> extends BasicCrawler<Context, ExtendedContext> {- /**- * A reference to the underlying {@apilink ProxyConfiguration} class that manages the crawler's proxies.- * Only available if used by the crawler.- */- proxyConfiguration?: ProxyConfiguration;-protected preNavigationHooks: InternalHttpHook<CrawlingContext>[];protected postNavigationHooks: ((crawlingContext: CrawlingContextWithReponse) => Awaitable<void>)[];protected persistCookiesPerSession: boolean;@@ -366,7 +351,6 @@ export class HttpCrawler<additionalMimeTypes: ow.optional.array.ofType(ow.string),suggestResponseEncoding: ow.optional.string,forceResponseEncoding: ow.optional.string,- proxyConfiguration: ow.optional.object.validate(validators.proxyConfiguration),persistCookiesPerSession: ow.optional.boolean,additionalHttpErrorStatusCodes: ow.optional.array.ofType(ow.number),@@ -392,7 +376,6 @@ export class HttpCrawler<additionalMimeTypes = [],suggestResponseEncoding,forceResponseEncoding,- proxyConfiguration,persistCookiesPerSession,preNavigationHooks = [],postNavigationHooks = [],@@ -436,7 +419,6 @@ export class HttpCrawler<this.forceResponseEncoding = forceResponseEncoding;this.additionalHttpErrorStatusCodes = new Set([...additionalHttpErrorStatusCodes]);this.ignoreHttpErrorStatusCodes = new Set([...ignoreHttpErrorStatusCodes]);- this.proxyConfiguration = proxyConfiguration;this.preNavigationHooks = preNavigationHooks;this.postNavigationHooks = [({ request, response }) => this._abortDownloadOfBody(request, response!),@@ -452,7 +434,6 @@ export class HttpCrawler<protected buildContextPipeline(): ContextPipeline<CrawlingContext, InternalHttpCrawlingContext> {return ContextPipeline.create<CrawlingContext>()- .compose({ action: this.prepareProxyInfo.bind(this) }).compose({action: this.makeHttpRequest.bind(this),})@@ -460,18 +441,6 @@ export class HttpCrawler<.compose({ action: this.handleBlockedRequestByContent.bind(this) });}- private async prepareProxyInfo(crawlingContext: CrawlingContext) {- const { request, session } = crawlingContext;- let proxyInfo: ProxyInfo | undefined;-- if (this.proxyConfiguration) {- const sessionId = session ? session.id : undefined;- proxyInfo = await this.proxyConfiguration.newProxyInfo(sessionId, { request });- }-- return { proxyInfo };- }-private async makeHttpRequest(crawlingContext: CrawlingContext,): Promise<Omit<CrawlingContextWithReponse, keyof CrawlingContext> & Partial<CrawlingContextWithReponse>> {@@ -787,11 +756,8 @@ export class HttpCrawler<// Delete any possible lowercased header for cookie as they are merged in _applyCookies under the uppercase Cookie headerReflect.deleteProperty(requestOptions.headers!, 'cookie');- // TODO this is incorrect, the check for man in the middle needs to be done- // on individual proxy level, not on the `proxyConfiguration` level,- // because users can use normal + MITM proxies in a single configuration.// Disable SSL verification for MITM proxies- if (this.proxyConfiguration && this.proxyConfiguration.isManInTheMiddle) {+ if (session?.proxyInfo?.ignoreTlsErrors) {requestOptions.https = {...requestOptions.https,rejectUnauthorized: false,diff --git a/test/core/crawlers/browser_crawler.test.ts b/test/core/crawlers/browser_crawler.test.tsindex 0e6057e36..c57a05d94 100644--- a/test/core/crawlers/browser_crawler.test.ts+++ b/test/core/crawlers/browser_crawler.test.ts@@ -1055,8 +1055,7 @@ describe('BrowserCrawler', () => {protected override async _navigationHandler(ctx: TestCrawlingContext,): Promise<HTTPResponse | null | undefined> {- const { session } = ctx;- const proxyInfo = await this.proxyConfiguration!.newProxyInfo(session?.id);+ const proxyInfo = ctx.session?.proxyInfo;if (proxyInfo!.url !== goodProxyUrl) {throw new Error('ERR_PROXY_CONNECTION_FAILED');@@ -1111,8 +1110,7 @@ describe('BrowserCrawler', () => {protected override async _navigationHandler(ctx: TestCrawlingContext,): Promise<HTTPResponse | null | undefined> {- const { session } = ctx;- const proxyInfo = await this.proxyConfiguration!.newProxyInfo(session?.id);+ const proxyInfo = ctx.session?.proxyInfo;numberOfRotations++;@@ -1166,8 +1164,7 @@ describe('BrowserCrawler', () => {protected override async _navigationHandler(ctx: TestCrawlingContext,): Promise<HTTPResponse | null | undefined> {- const { session } = ctx;- const proxyInfo = await this.proxyConfiguration!.newProxyInfo(session?.id);+ const proxyInfo = ctx.session?.proxyInfo;if (proxyInfo!.url.includes('localhost')) {throw new Error(proxyError);diff --git a/test/core/crawlers/cheerio_crawler.test.ts b/test/core/crawlers/cheerio_crawler.test.tsindex 721915a51..5bd545de0 100644--- a/test/core/crawlers/cheerio_crawler.test.ts+++ b/test/core/crawlers/cheerio_crawler.test.ts@@ -764,8 +764,7 @@ describe('CheerioCrawler', () => {const session = sessions[i];expect(typeof proxyInfo.url).toBe('string');expect(typeof session.id).toBe('string');- expect(proxyInfo.sessionId).toBe(session.id);- expect(proxyInfo).toEqual(await proxyConfiguration.newProxyInfo(session.id));+ expect(session.proxyInfo).toBe(proxyInfo);}});@@ -1186,46 +1185,6 @@ describe('CheerioCrawler', () => {'Could not parse cookie header string: sessionid',);});-- test('should use sessionId in proxyUrl when the session pool is enabled', async () => {- const sourcesNew = [{ url: 'http://example.com/?q=1' }];- const requestListNew = await RequestList.open({ sources: sourcesNew });-- const proxyConfiguration = new ProxyConfiguration({ proxyUrls: ['http://localhost:8080'] });- const newUrlSpy = vitest.spyOn(proxyConfiguration, 'newUrl');-- const requestHandler = vi.fn(async () => {});-- const cheerioCrawler = new CheerioCrawler({- requestList: requestListNew,- maxRequestRetries: 0,- maxSessionRotations: 0,- requestHandler,- failedRequestHandler: () => {},- useSessionPool: true,- proxyConfiguration,- preNavigationHooks: [- async (context) => {- context.proxyInfo = undefined;- },- ],- });-- try {- await cheerioCrawler.run();- } catch (e) {- // localhost proxy causes proxy errors, session rotations and finally throws, but we don't care- }-- expect(requestHandler).toHaveBeenCalledOnce();-- const usedSession: Session = ((requestHandler.mock.calls?.[0] as any)[0] as CrawlingContext).session!;-- expect(newUrlSpy).toBeCalledWith(- usedSession!.id,- expect.objectContaining({ request: expect.any(Request) }),- );- });});describe('Crawling context', () => {diff --git a/test/core/proxy_configuration.test.ts b/test/core/proxy_configuration.test.tsindex e70344109..ed16bb93c 100644--- a/test/core/proxy_configuration.test.ts+++ b/test/core/proxy_configuration.test.ts@@ -1,12 +1,10 @@import { ProxyConfiguration, Request } from '@crawlee/core';-const sessionId = 538909250932;-describe('ProxyConfiguration', () => {test('newUrl() should return proxy URL', async () => {const proxyConfiguration = new ProxyConfiguration({ proxyUrls: ['http://proxy.com:1111'] });expect(proxyConfiguration).toBeInstanceOf(ProxyConfiguration);- expect(await proxyConfiguration.newUrl(sessionId)).toBe('http://proxy.com:1111');+ expect(await proxyConfiguration.newUrl()).toBe('http://proxy.com:1111');});test('newProxyInfo() should return ProxyInfo object', async () => {@@ -14,14 +12,13 @@ describe('ProxyConfiguration', () => {const url = 'http://proxy.com:1111';const proxyInfo = {- sessionId: `${sessionId}`,url,hostname: 'proxy.com',username: '',password: '',port: '1111',};- expect(await proxyConfiguration.newProxyInfo(sessionId)).toEqual(proxyInfo);+ expect(await proxyConfiguration.newProxyInfo()).toEqual(proxyInfo);});test('newProxyInfo() works with special characters', async () => {@@ -29,14 +26,13 @@ describe('ProxyConfiguration', () => {const proxyConfiguration = new ProxyConfiguration({ proxyUrls: [url] });const proxyInfo = {- sessionId: `${sessionId}`,url,hostname: 'proxy.com',username: 'user@name',password: 'pass@word',port: '1111',};- expect(await proxyConfiguration.newProxyInfo(sessionId)).toEqual(proxyInfo);+ expect(await proxyConfiguration.newProxyInfo()).toEqual(proxyInfo);});test('should throw on invalid newUrlFunction', async () => {@@ -140,31 +136,6 @@ describe('ProxyConfiguration', () => {expect((await proxyConfiguration.newProxyInfo())!.url).toEqual(proxyUrls[2]);});- test('should rotate custom URLs with sessions correctly', async () => {- const sessions = ['session_01', 'session_02', 'session_03', 'session_04', 'session_05', 'session_06'];- const proxyConfiguration = new ProxyConfiguration({- proxyUrls: ['http://proxy.com:1111', 'http://proxy.com:2222', 'http://proxy.com:3333'],- });-- // @ts-expect-error TODO private property?- const proxyUrls = proxyConfiguration.proxyUrls!;- // should use same proxy URL- expect(await proxyConfiguration.newUrl(sessions[0])).toEqual(proxyUrls[0]);- expect(await proxyConfiguration.newUrl(sessions[0])).toEqual(proxyUrls[0]);- expect(await proxyConfiguration.newUrl(sessions[0])).toEqual(proxyUrls[0]);-- // should rotate different proxies- expect(await proxyConfiguration.newUrl(sessions[1])).toEqual(proxyUrls[1]);- expect(await proxyConfiguration.newUrl(sessions[2])).toEqual(proxyUrls[2]);- expect(await proxyConfiguration.newUrl(sessions[3])).toEqual(proxyUrls[0]);- expect(await proxyConfiguration.newUrl(sessions[4])).toEqual(proxyUrls[1]);- expect(await proxyConfiguration.newUrl(sessions[5])).toEqual(proxyUrls[2]);-- // should remember already used session- expect(await proxyConfiguration.newUrl(sessions[1])).toEqual(proxyUrls[1]);- expect(await proxyConfiguration.newUrl(sessions[3])).toEqual(proxyUrls[0]);- });-test('should throw cannot combine custom methods', async () => {const proxyUrls = ['http://proxy.com:1111', 'http://proxy.com:2222', 'http://proxy.com:3333'];const newUrlFunction = () => {@@ -233,16 +204,16 @@ describe('ProxyConfiguration', () => {// @ts-expect-error protected propertyconst tieredProxyUrls = proxyConfiguration.tieredProxyUrls!;- expect(await proxyConfiguration.newUrl('session-id', { request })).toEqual(tieredProxyUrls[0][0]);- expect(await proxyConfiguration.newUrl('session-id', { request })).toEqual(tieredProxyUrls[1][0]);- expect(await proxyConfiguration.newUrl('session-id', { request })).toEqual(tieredProxyUrls[2][0]);+ expect(await proxyConfiguration.newUrl({ request })).toEqual(tieredProxyUrls[0][0]);+ expect(await proxyConfiguration.newUrl({ request })).toEqual(tieredProxyUrls[1][0]);+ expect(await proxyConfiguration.newUrl({ request })).toEqual(tieredProxyUrls[2][0]);// we still get the same (higher) proxy tier even with a new requestconst request2 = new Request({url: 'http://example.com/another-resource',});- expect(await proxyConfiguration.newUrl('session-id', { request: request2 })).toEqual(tieredProxyUrls[2][0]);+ expect(await proxyConfiguration.newUrl({ request: request2 })).toEqual(tieredProxyUrls[2][0]);});test('upshifts and downshifts properly', async () => {@@ -258,7 +229,7 @@ describe('ProxyConfiguration', () => {let gotToTheHighestProxy = false;for (let i = 0; i < 10; i++) {- const lastProxyUrl = await proxyConfiguration.newUrl('session-id', { request });+ const lastProxyUrl = await proxyConfiguration.newUrl({ request });if (lastProxyUrl === tieredProxyUrls[2][0]) {gotToTheHighestProxy = true;break;@@ -271,7 +242,7 @@ describe('ProxyConfiguration', () => {let gotToTheLowestProxy = false;for (let i = 0; i < 20; i++) {- const lastProxyUrl = await proxyConfiguration.newUrl('session-id', { request });+ const lastProxyUrl = await proxyConfiguration.newUrl({ request });if (lastProxyUrl === tieredProxyUrls[0][0]) {gotToTheLowestProxy = true;break;@@ -294,7 +265,7 @@ describe('ProxyConfiguration', () => {let gotToTheHighestProxy = false;for (let i = 0; i < 10; i++) {- const lastProxyUrl = await proxyConfiguration.newUrl('session-id', { request: failingRequest });+ const lastProxyUrl = await proxyConfiguration.newUrl({ request: failingRequest });if (lastProxyUrl === tieredProxyUrls[2][0]) {gotToTheHighestProxy = true;@@ -307,7 +278,7 @@ describe('ProxyConfiguration', () => {let gotToTheLowestProxy = false;for (let i = 0; i < 100; i++) {- const lastProxyUrl = await proxyConfiguration.newUrl('session-id', {+ const lastProxyUrl = await proxyConfiguration.newUrl({request: new Request({ url: `http://example.com/${i}` }),});diff --git a/test/core/session_pool/session.test.ts b/test/core/session_pool/session.test.tsindex 09439221f..af2641801 100644--- a/test/core/session_pool/session.test.ts+++ b/test/core/session_pool/session.test.ts@@ -1,4 +1,4 @@-import { EVENT_SESSION_RETIRED, ProxyConfiguration, Session, SessionPool } from '@crawlee/core';+import { EVENT_SESSION_RETIRED, Session, SessionPool } from '@crawlee/core';import type { Dictionary } from '@crawlee/utils';import { entries, sleep } from '@crawlee/utils';import { CookieJar } from 'tough-cookie';@@ -148,19 +148,6 @@ describe('Session - testing session behaviour ', () => {});});- test('should be valid proxy session', async () => {- const proxyConfiguration = new ProxyConfiguration({ proxyUrls: ['http://localhost:1234'] });- session = new Session({ sessionPool });- let error;- try {- await proxyConfiguration.newUrl(session.id);- } catch (e) {- error = e;- }-- expect(error).toBeUndefined();- });-test('should use cookieJar', () => {session = new Session({ sessionPool });expect(session.cookieJar.setCookie).toBeDefined();