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
refactor!: Split off ConcurrencySystem from AutoscaledPool (#3917)
Jan Buchar2e700109c9a3
diff --git a/docs/guides/scaling_crawlers.mdx b/docs/guides/scaling_crawlers.mdxindex e296cc909..178073cf0 100644--- a/docs/guides/scaling_crawlers.mdx+++ b/docs/guides/scaling_crawlers.mdx@@ -10,7 +10,7 @@ import CodeBlock from '@theme/CodeBlock';import MinMaxConcurrencySource from '!!raw-loader!./scaling_crawlers_minMaxConcurrency.ts';import MaxRequestsPerMinuteSource from '!!raw-loader!./scaling_crawlers_maxRequestsPerMinute.ts';-import AutoscaledPoolOptionsSource from '!!raw-loader!./scaling_crawlers_autoscaledPoolOptions.ts';+import ConcurrencySystemSource from '!!raw-loader!./scaling_crawlers_concurrencySystem.ts';As we build our crawler, we might want to control how many requests we do to the website at a time. Crawlee provides several options to fine tune how many parallel requests should be made at any time, how many requests should be done per minute, and how should scaling work based on the available system resources.@@ -45,7 +45,7 @@ It's recommended to leave it at the default value that is provided and letting t## Advanced options-While the options above should be enough for most users, if we wanted to get super deep into the configuration of the autoscaling pool (the internal utility in Crawlee that helps us allow crawlers to scale up and down), we can do so through the <ApiLink to="cheerio-crawler/interface/CheerioCrawlerOptions#autoscaledPoolOptions">`autoscaledPoolOptions`</ApiLink> object available on crawler options.+While the options above should be enough for most users, if we wanted to get super deep into the configuration of autoscaling (the internal machinery in Crawlee that helps us allow crawlers to scale up and down), we can do so by injecting a pre-configured <ApiLink to="core/class/ConcurrencySystem">`ConcurrencySystem`</ApiLink> through the <ApiLink to="cheerio-crawler/interface/CheerioCrawlerOptions#concurrencySystem">`concurrencySystem`</ApiLink> crawler option. All the fine-grained scaling configuration lives on that instance (see <ApiLink to="core/interface/ConcurrencySystemOptions">`ConcurrencySystemOptions`</ApiLink>).:::danger Complex options up ahead!@@ -53,47 +53,45 @@ This section is super advanced and, unless you test the changes extensively and:::-With that warning aside, if we're feeling adventurous, this is how we would pass these options when using a crawler:+With that warning aside, this is how we pass those options. One thing to watch: the `minConcurrency`/`maxConcurrency`/`maxRequestsPerMinute` shortcuts cannot be combined with an injected system — they configure the default one it replaces, so set those limits on the instance instead.<CodeBlock language="js">- {AutoscaledPoolOptionsSource}+ {ConcurrencySystemSource}</CodeBlock>-### `desiredConcurrency`--This option specifies the amount of requests that should be running in parallel at the start of the crawler, assuming there are so many available. It defaults to the same value as `minConcurrency`.+:::tip Capping the combined concurrency of several crawlers-### `desiredConcurrencyRatio`+Injecting the *same* `ConcurrencySystem` instance into several crawlers makes them share a single concurrency budget, capping their combined parallelism instead of letting each crawler scale independently.-The minimum ratio of concurrency to reach before more scaling up is allowed (a number between `0` and `1`). By default, it is set to `0.95`.+The budget is shared, not divided: slots go to whoever asks first, so a crawler that fills it early keeps refilling it as its own requests finish, and one that starts later may get a much smaller share of it. If a crawler needs a guaranteed slice, give it its own instance — or implement <ApiLink to="core/interface/IConcurrencySystem">`IConcurrencySystem`</ApiLink>, whose allocation methods are told which crawler is asking, and allocate however we see fit.-We can think of this as the point where the autoscaling pool can attempt to scale up (or down), monitor if there's any changes, and correct them if necessary.+:::-### `scaleUpStepRatio` and `scaleDownStepRatio`+### `desiredConcurrency`-These values define the fractional amount of desired concurrency to be added or subtracted as the autoscaling pool scales up or down. Both of these values default to `0.05`.+This option specifies the amount of requests that should be running in parallel at the start of the crawler, assuming there are so many available. It defaults to the same value as `minConcurrency`.-Every time the autoscaled pool attempts to scale up or down, this value will be added or subtracted from the current concurrency, and, based on the [`desiredConcurrencyRatio`](#desiredconcurrencyratio) and [`maxConcurrency`](#minconcurrency-and-maxconcurrency), determines how many requests can run concurrently.+### `desiredConcurrencyRatio`-### `maybeRunIntervalSecs`+The minimum ratio of concurrency to reach before more scaling up is allowed (a number between `0` and `1`). By default, it is set to `0.9`.-Indicates how often the autoscaling pool should check if more requests can be started and, if that's true, starts a new request if there are any available. This value is represented in seconds, and defaults to `0.5`.+We can think of this as the point where the concurrency system can attempt to scale up (or down), monitor if there's any changes, and correct them if necessary.-:::info+### `scaleUpStepRatio` and `scaleDownStepRatio`-Changing this has no effect for requests that are fired immediately after the previous ones are finished. However, it will influence how fast new requests will be started after the autoscaled pool scales up.+These values define the fractional amount of desired concurrency to be added or subtracted as the concurrency system scales up or down. Both of these values default to `0.05`.-:::+Every time the concurrency system attempts to scale up or down, this value will be added or subtracted from the current concurrency, and, based on the [`desiredConcurrencyRatio`](#desiredconcurrencyratio) and [`maxConcurrency`](#minconcurrency-and-maxconcurrency), determines how many requests can run concurrently.### `loggingIntervalSecs`-This option lets us control how often the autoscaled pool should log its current state (the current concurrency ratio, desired ratios, if the system is overloaded and so on).+This option lets us control how often the concurrency system should log its current state (the current concurrency ratio, desired ratios, if the system is overloaded and so on).We can disable logging altogether by setting this to `null`. By default, it is set to `60` seconds.### `autoscaleIntervalSecs`-This option lets us control how often the autoscaling pool should check if it can and should scale up or down. This value is represented in seconds, and defaults to `10`.+This option lets us control how often the concurrency system should check if it can and should scale up or down. This value is represented in seconds, and defaults to `10`.:::tip@@ -118,3 +116,52 @@ This controls how many total requests can be made per minute. It counts the amouThis option can be set by specifying [`maxRequestsPerMinute`](#maxrequestsperminute) in your crawler options too, as it is a shortcut for visibility and ease of access.:::++## Load signals++Whether the machine counts as overloaded is decided by *load signals*. Four are built in — memory, event loop, CPU and the storage client's rate-limit errors — and each is configured by its own bag under <ApiLink to="core/interface/ConcurrencySystemOptions#loadSignals">`loadSignals`</ApiLink>, carrying both its limits and the `overloadedRatio` at which it fires. If any signal reports overload, the system is overloaded and concurrency is held down.++A signal we don't want watched at all can be switched **off** with `false`, which stops it being collected as well as evaluated (its entry in the reported status then simply reads as not overloaded):++```ts+const concurrencySystem = new ConcurrencySystem({+ loadSignals: {+ // Our storage backend reports no rate-limit statistics, so stop polling it every second.+ client: false,+ eventLoop: { maxBlockedMillis: 100 },+ },+});+```++We can also watch resources of our own by implementing <ApiLink to="core/interface/LoadSignal">`LoadSignal`</ApiLink> — navigation timeouts or proxy health, say — and passing them in `loadSignals.custom`. The <ApiLink to="core/class/SnapshotStore">`SnapshotStore`</ApiLink> helper does the time-windowed bookkeeping for us:++```ts+const store = new SnapshotStore();++const proxyHealth: LoadSignal = {+ name: 'proxyHealth',+ overloadedRatio: 0.3,+ async start({ maxSampleWindowMillis }) {+ // Retain exactly the window we will be sampled over, and drop anything measured before a restart.+ store.useSampleWindow(maxSampleWindowMillis);+ store.clear();+ // ...start measuring, calling store.push() per measurement+ },+ async stop() { /* ...stop measuring */ },+ getSample: (sampleDurationMillis) => store.getSample(sampleDurationMillis),+};++const concurrencySystem = new ConcurrencySystem({ loadSignals: { custom: [proxyHealth] } });+```++Each built-in is a public class too — `MemoryLoadSignal`, `EventLoopLoadSignal`, `CpuLoadSignal`, `ClientLoadSignal` — taking exactly the bag its `loadSignals` key accepts. Constructing one directly is how we *wrap* a built-in rather than reimplement it (to hold its overload verdict for a while after the resource recovers, say): switch the original off with `cpu: false`, and pass a signal that delegates to the instance we built in `custom`.++:::info Signal names are the keys of the reported status++A signal's `name` is the key its verdict appears under in the reported status, so two signals cannot share one — a duplicate throws at construction time. That is why taking over a built-in name (`memInfo`, `eventLoopInfo`, `cpuInfo`, `clientInfo`) requires switching that built-in off.++:::++### `snapshotHistorySecs` and `currentHistorySecs`++Signals are not read as a single instantaneous measurement but averaged over a window, and there are two: `currentHistorySecs` (default `5`) is the short window that gates whether one more request may start, while `snapshotHistorySecs` (default `30`) is the longer window autoscaling decisions are based on. Dispatch therefore reacts to spikes quickly while scaling stays stable. Both apply to every signal alike, built-in or custom, and signals size their snapshot retention to the wider of the two — so raising `snapshotHistorySecs` is what costs memory.diff --git a/docs/guides/scaling_crawlers_autoscaledPoolOptions.ts b/docs/guides/scaling_crawlers_autoscaledPoolOptions.tsdeleted file mode 100644index 5d8f53c4d..000000000--- a/docs/guides/scaling_crawlers_autoscaledPoolOptions.ts+++ /dev/null@@ -1,8 +0,0 @@-import { CheerioCrawler } from 'crawlee';--const crawler = new CheerioCrawler({- // Pass in advanced options by providing them in the autoscaledPoolOptions- autoscaledPoolOptions: {- // ...- },-});diff --git a/docs/guides/scaling_crawlers_concurrencySystem.ts b/docs/guides/scaling_crawlers_concurrencySystem.tsnew file mode 100644index 000000000..76f1041dd--- /dev/null+++ b/docs/guides/scaling_crawlers_concurrencySystem.ts@@ -0,0 +1,19 @@+import { CheerioCrawler, ConcurrencySystem } from 'crawlee';++// Advanced scaling options live on a pre-configured ConcurrencySystem+const concurrencySystem = new ConcurrencySystem({+ // ...+});++const crawler = new CheerioCrawler({+ concurrencySystem,+ // ...+});++// An injected system's lifecycle is owned by us, not the crawler+await concurrencySystem.start();+try {+ await crawler.run(['https://crawlee.dev']);+} finally {+ await concurrencySystem.stop();+}diff --git a/docs/public-api/crawlee-basic.api.md b/docs/public-api/crawlee-basic.api.mdindex 5d8358fb4..5957bd99f 100644--- a/docs/public-api/crawlee-basic.api.md+++ b/docs/public-api/crawlee-basic.api.md@@ -9,7 +9,7 @@ import type { AddRequestsBatchedResult } from '@crawlee/core';import { AnyPredicate } from 'ow';import { ArrayPredicate } from 'ow';import { AutoscaledPool } from '@crawlee/core';-import { AutoscaledPoolOptions } from '@crawlee/core';+import type { AutoscaledPoolPredicateOptions } from '@crawlee/core';import type { Awaitable } from '@crawlee/types';import type { BaseHttpClient } from '@crawlee/types';import { BasePredicate } from 'ow';@@ -18,6 +18,8 @@ import { BooleanPredicate } from 'ow';import { Cheerio } from '@crawlee/utils';import { CheerioAPI } from '@crawlee/utils';import { CheerioRoot } from '@crawlee/utils';+import { ConcurrencySystem } from '@crawlee/core';+import { ConcurrencySystemOptions } from '@crawlee/core';import type { Configuration } from '@crawlee/core';import { ContextPipeline } from '@crawlee/core';import type { CrawleeLogger } from '@crawlee/core';@@ -30,6 +32,7 @@ import type { EnqueueLinksOptions } from '@crawlee/core';import type { EventManager } from '@crawlee/core';import type { FinalStatistics } from '@crawlee/core';import type { GetUserDataFromRequest } from '@crawlee/core';+import { IConcurrencySystem } from '@crawlee/core';import { IProxyConfiguration } from '@crawlee/core';import { IRequestLoader } from '@crawlee/core';import { IRequestManager } from '@crawlee/core';@@ -78,6 +81,7 @@ export class BasicCrawler<Context extends CrawlingContext = CrawlingContext, Conget contextPipeline(): ContextPipeline<CrawlingContext, ExtendedContext>;// (undocumented)protected static readonly CRAWLEE_STATE_KEY = "CRAWLEE_STATE";+ protected createDefaultConcurrencySystem(options: ConcurrencySystemOptions): ConcurrencySystem;// (undocumented)protected readonly errorHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;exportData<Data>(path: string, format?: 'json' | 'csv', options?: DatasetExportOptions): Promise<Data[]>;@@ -133,6 +137,7 @@ export class BasicCrawler<Context extends CrawlingContext = CrawlingContext, ConmaxRequestsPerCrawl: NumberPredicate & BasePredicate<number | undefined>;maxCrawlDepth: NumberPredicate & BasePredicate<number | undefined>;autoscaledPoolOptions: ObjectPredicate<object> & BasePredicate<object | undefined>;+ concurrencySystem: ObjectPredicate<object> & BasePredicate<object | undefined>;sessionPool: ObjectPredicate<object> & BasePredicate<object | undefined>;proxyConfiguration: ObjectPredicate<object> & BasePredicate<object | undefined>;statusMessageLoggingInterval: NumberPredicate & BasePredicate<number | undefined>;@@ -181,8 +186,9 @@ export class BasicCrawler<Context extends CrawlingContext = CrawlingContext, Con// @public (undocumented)export interface BasicCrawlerOptions<Context extends CrawlingContext = CrawlingContext, ContextExtension = Dictionary<never>, ExtendedContext extends Context = Context & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<Context['request']>>> {additionalHttpErrorStatusCodes?: number[];- autoscaledPoolOptions?: AutoscaledPoolOptions;+ autoscaledPoolOptions?: AutoscaledPoolPredicateOptions;blockedStatusCodes?: number[];+ concurrencySystem?: IConcurrencySystem;configuration?: Configuration;contextPipelineBuilder?: () => ContextPipeline<CrawlingContext, Context>;errorHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;diff --git a/docs/public-api/crawlee-browser.api.md b/docs/public-api/crawlee-browser.api.mdindex 4e6525bda..9544d84fc 100644--- a/docs/public-api/crawlee-browser.api.md+++ b/docs/public-api/crawlee-browser.api.md@@ -86,6 +86,7 @@ export abstract class BrowserCrawler<Page extends CommonPage = CommonPage, RespomaxRequestsPerCrawl: NumberPredicate & BasePredicate<number | undefined>;maxCrawlDepth: NumberPredicate & BasePredicate<number | undefined>;autoscaledPoolOptions: ObjectPredicate<object> & BasePredicate<object | undefined>;+ concurrencySystem: ObjectPredicate<object> & BasePredicate<object | undefined>;sessionPool: ObjectPredicate<object> & BasePredicate<object | undefined>;statusMessageLoggingInterval: NumberPredicate & BasePredicate<number | undefined>;statusMessageCallback: Predicate<Function> & BasePredicate<Function | undefined>;diff --git a/docs/public-api/crawlee-core.api.md b/docs/public-api/crawlee-core.api.mdindex 84c4de257..af1b87dc7 100644--- a/docs/public-api/crawlee-core.api.md+++ b/docs/public-api/crawlee-core.api.md@@ -85,39 +85,30 @@ export class AutoscaledPool {abort(): Promise<void>;get currentConcurrency(): number;get desiredConcurrency(): number;- set desiredConcurrency(value: number);- get maxConcurrency(): number;- set maxConcurrency(value: number);- get minConcurrency(): number;- set minConcurrency(value: number);notify(): Promise<void>;pause(timeoutSecs?: number): Promise<void>;resume(): void;run(): Promise<void>;+ get system(): IConcurrencySystem;}// @public (undocumented)-export interface AutoscaledPoolOptions {- autoscaleIntervalSecs?: number;- desiredConcurrency?: number;- desiredConcurrencyRatio?: number;- isFinishedFunction?: () => Promise<boolean>;- isTaskReadyFunction?: () => Promise<boolean>;+export interface AutoscaledPoolOptions extends AutoscaledPoolPredicateOptions {+ concurrencySystem: IConcurrencySystem;+ consumer: ConcurrencyConsumer;// (undocumented)log?: CrawleeLogger;- loggingIntervalSecs?: number | null;- maxConcurrency?: number;- maxTasksPerMinute?: number;maybeRunIntervalSecs?: number;- minConcurrency?: number;runTaskFunction?: () => Promise<unknown>;- scaleDownStepRatio?: number;- scaleUpStepRatio?: number;- snapshotterOptions?: SnapshotterOptions;- systemStatusOptions?: SystemStatusOptions;taskTimeoutSecs?: number;}+// @public+export interface AutoscaledPoolPredicateOptions {+ isFinishedFunction?: () => Promise<boolean>;+ isTaskReadyFunction?: () => Promise<boolean>;+}+export { Awaitable }// @public@@ -167,24 +158,26 @@ export interface ClientInfo {limitRatio: number;}-// @public (undocumented)-export interface ClientLoadSignalOptions {+// @public+export class ClientLoadSignal implements LoadSignal {+ constructor(options?: ClientLoadSignalOptions);// (undocumented)- client: StorageBackend;+ getSample(sampleDurationMillis?: number): LoadSnapshot[];// (undocumented)- clientSnapshotIntervalSecs?: number;+ readonly name = "clientInfo";// (undocumented)- maxClientErrors?: number;+ readonly overloadedRatio: number;// (undocumented)- overloadedRatio?: number;+ start(context: LoadSignalStartContext): Promise<void>;// (undocumented)- snapshotHistoryMillis?: number;+ stop(): Promise<void>;}-// @public (undocumented)-export interface ClientSnapshot extends LoadSnapshot {- // (undocumented)- rateLimitErrorCount: number;+// @public+export interface ClientLoadSignalOptions {+ maxErrors?: number;+ overloadedRatio?: number;+ snapshotIntervalSecs?: number;}// @public@@ -193,6 +186,49 @@ export const coerceBoolean: z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodBoo// @public (undocumented)export const coerceNumber: z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodNumber>;+// @public+export interface ConcurrencyConsumer {+ readonly id: string;+}++// @public+export class ConcurrencySystem implements IConcurrencySystem {+ constructor(options?: ConcurrencySystemOptions);+ // (undocumented)+ get currentConcurrency(): number;+ get desiredConcurrency(): number;+ set desiredConcurrency(value: number);+ getCurrentStatus(): SystemInfo;+ hasCapacityForTask(_consumer?: ConcurrencyConsumer): boolean;+ get isRunning(): boolean;+ get maxConcurrency(): number;+ set maxConcurrency(value: number);+ get minConcurrency(): number;+ set minConcurrency(value: number);+ registerTaskEnd(_consumer?: ConcurrencyConsumer): void;+ start(): Promise<void>;+ stop(): Promise<void>;+ tryRegisterTaskStart(consumer?: ConcurrencyConsumer): boolean;+}++// @public (undocumented)+export interface ConcurrencySystemOptions {+ autoscaleIntervalSecs?: number;+ currentHistorySecs?: number;+ desiredConcurrency?: number;+ desiredConcurrencyRatio?: number;+ loadSignals?: LoadSignalsOptions;+ // (undocumented)+ log?: CrawleeLogger;+ loggingIntervalSecs?: number | null;+ maxConcurrency?: number;+ maxTasksPerMinute?: number;+ minConcurrency?: number;+ scaleDownStepRatio?: number;+ scaleUpStepRatio?: number;+ snapshotHistorySecs?: number;+}+// @public (undocumented)export interface ConfigField<T extends z.ZodType = z.ZodType> {// (undocumented)@@ -251,25 +287,24 @@ export class ContextPipelineInterruptedError extends Error {export { Cookie }-// @public (undocumented)-export interface CpuLoadSignalOptions {+// @public+export class CpuLoadSignal implements LoadSignal {+ constructor(options?: CpuLoadSignalOptions);// (undocumented)- configuration: Configuration;+ getSample(sampleDurationMillis?: number): LoadSnapshot[];// (undocumented)- overloadedRatio?: number;+ readonly name = "cpuInfo";// (undocumented)- snapshotHistoryMillis?: number;-}--// @public (undocumented)-export interface CpuSnapshot extends LoadSnapshot {+ readonly overloadedRatio: number;// (undocumented)- ticks?: {- idle: number;- total: number;- };+ start(context: LoadSignalStartContext): Promise<void>;// (undocumented)- usedRatio: number;+ stop(): Promise<void>;+}++// @public+export interface CpuLoadSignalOptions {+ overloadedRatio?: number;}// @public (undocumented)@@ -306,27 +341,6 @@ export interface CrawlingContext<UserData extends Dictionary = Dictionary> extensendRequest: (requestOverrides?: Partial<HttpRequestOptions>, optionsOverrides?: SendRequestOptions) => Promise<Response>;}-// @public-export function createClientLoadSignal(options: ClientLoadSignalOptions): Omit<LoadSignal, "getSample"> & {- store: SnapshotStore<ClientSnapshot>;- handle: (cb: () => unknown) => void;- getSample(sampleDurationMillis?: number): ClientSnapshot[];-};--// @public-export function createCpuLoadSignal(options: CpuLoadSignalOptions): Omit<LoadSignal, "getSample"> & {- store: SnapshotStore<CpuSnapshot>;- handle: (payload: SystemInfo) => void;- getSample(sampleDurationMillis?: number): CpuSnapshot[];-};--// @public-export function createEventLoopLoadSignal(options?: EventLoopLoadSignalOptions): Omit<LoadSignal, "getSample"> & {- store: SnapshotStore<EventLoopSnapshot>;- handle: (cb: () => unknown) => void;- getSample(sampleDurationMillis?: number): EventLoopSnapshot[];-};-// @publicexport interface CreateSession {// (undocumented)@@ -572,24 +586,25 @@ export interface ErrorTrackerOptions {}// @public-export function evaluateLoadSignalSample(sample: LoadSnapshot[], overloadedRatio: number): ClientInfo;--// @public (undocumented)-export interface EventLoopLoadSignalOptions {+export class EventLoopLoadSignal implements LoadSignal {+ constructor(options?: EventLoopLoadSignalOptions);// (undocumented)- eventLoopSnapshotIntervalSecs?: number;+ getSample(sampleDurationMillis?: number): LoadSnapshot[];// (undocumented)- maxBlockedMillis?: number;+ readonly name = "eventLoopInfo";// (undocumented)- overloadedRatio?: number;+ readonly overloadedRatio: number;+ // (undocumented)+ start(context: LoadSignalStartContext): Promise<void>;// (undocumented)- snapshotHistoryMillis?: number;+ stop(): Promise<void>;}-// @public (undocumented)-export interface EventLoopSnapshot extends LoadSnapshot {- // (undocumented)- exceededMillis: number;+// @public+export interface EventLoopLoadSignalOptions {+ maxBlockedMillis?: number;+ overloadedRatio?: number;+ snapshotIntervalSecs?: number;}// @public (undocumented)@@ -710,6 +725,16 @@ export type GlobObject = {glob: string;} & Pick<RequestOptions, 'method' | 'payload' | 'label' | 'userData' | 'headers'>;+// @public+export interface IConcurrencySystem {+ readonly currentConcurrency: number;+ readonly desiredConcurrency: number;+ hasCapacityForTask(consumer: ConcurrencyConsumer): boolean;+ readonly isRunning: boolean;+ registerTaskEnd(consumer: ConcurrencyConsumer): void;+ tryRegisterTaskStart(consumer: ConcurrencyConsumer): boolean;+}+// @publicexport interface IProxyConfiguration {newProxyInfo(options?: NewUrlOptions): Promise<ProxyInfo | undefined>;@@ -821,10 +846,24 @@ export interface LoadSignal {getSample(sampleDurationMillis?: number): LoadSnapshot[];readonly name: string;readonly overloadedRatio: number;- start(): Promise<void>;+ start(context: LoadSignalStartContext): Promise<void>;stop(): Promise<void>;}+// @public+export interface LoadSignalsOptions {+ client?: ClientLoadSignalOptions | false;+ cpu?: CpuLoadSignalOptions | false;+ custom?: LoadSignal[];+ eventLoop?: EventLoopLoadSignalOptions | false;+ memory?: MemoryLoadSignalOptions | false;+}++// @public+export interface LoadSignalStartContext {+ maxSampleWindowMillis: number;+}+// @publicexport interface LoadSnapshot {// (undocumented)@@ -866,38 +905,23 @@ export const MAX_POOL_SIZE = 1000;// @publicexport class MemoryLoadSignal implements LoadSignal {- constructor(options: MemoryLoadSignalOptions);- getMemorySnapshots(): MemorySnapshot[];+ constructor(options?: MemoryLoadSignalOptions);// (undocumented)- getSample(sampleDurationMillis?: number): MemorySnapshot[];+ getSample(sampleDurationMillis?: number): LoadSnapshot[];// (undocumented)readonly name = "memInfo";// (undocumented)readonly overloadedRatio: number;// (undocumented)- start(): Promise<void>;+ start(context: LoadSignalStartContext): Promise<void>;// (undocumented)stop(): Promise<void>;}-// @public (undocumented)+// @publicexport interface MemoryLoadSignalOptions {- // (undocumented)- configuration: Configuration;- // (undocumented)- log?: CrawleeLogger;- // (undocumented)- maxUsedMemoryRatio?: number;- // (undocumented)+ maxUsedRatio?: number;overloadedRatio?: number;- // (undocumented)- snapshotHistoryMillis?: number;-}--// @public (undocumented)-export interface MemorySnapshot extends LoadSnapshot {- // (undocumented)- usedBytes?: number;}// @public (undocumented)@@ -1601,69 +1625,11 @@ export interface SnapshotResult {// @publicexport class SnapshotStore<T extends LoadSnapshot = LoadSnapshot> {- constructor(historyMillis?: number);- static fromEvent<T extends LoadSnapshot, E>(options: {- name: string;- overloadedRatio: number;- events: EventManager;- event: EventTypeName;- snapshotHistoryMillis?: number;- handler: (store: SnapshotStore<T>, payload: E) => void;- }): Omit<LoadSignal, 'getSample'> & {- store: SnapshotStore<T>;- handle: (payload: E) => void;- getSample(sampleDurationMillis?: number): T[];- };- static fromInterval<T extends LoadSnapshot>(options: {- name: string;- overloadedRatio: number;- intervalMillis: number;- snapshotHistoryMillis?: number;- handler: (store: SnapshotStore<T>, intervalCallback: () => unknown) => void;- }): Omit<LoadSignal, 'getSample'> & {- store: SnapshotStore<T>;- handle: (cb: () => unknown) => void;- getSample(sampleDurationMillis?: number): T[];- };+ clear(): void;getAll(): T[];getSample(sampleDurationMillis?: number): T[];push(snapshot: T, now?: Date): void;-}--// @public-export class Snapshotter {- constructor(options?: SnapshotterOptions);- // (undocumented)- readonly client: StorageBackend;- // (undocumented)- get clientSnapshots(): ClientSnapshot[];- // (undocumented)- readonly configuration: Configuration;- // (undocumented)- get cpuSnapshots(): CpuSnapshot[];- // (undocumented)- get eventLoopSnapshots(): EventLoopSnapshot[];- getClientSample(sampleDurationMillis?: number): ClientSnapshot[];- getCpuSample(sampleDurationMillis?: number): CpuSnapshot[];- getEventLoopSample(sampleDurationMillis?: number): EventLoopSnapshot[];- getLoadSignals(): LoadSignal[];- getMemorySample(sampleDurationMillis?: number): MemorySnapshot[];- // (undocumented)- readonly log: CrawleeLogger;- // (undocumented)- get memorySnapshots(): MemorySnapshot[];- start(): Promise<void>;- stop(): Promise<void>;-}--// @public (undocumented)-export interface SnapshotterOptions {- clientSnapshotIntervalSecs?: number;- eventLoopSnapshotIntervalSecs?: number;- maxBlockedMillis?: number;- maxClientErrors?: number;- maxUsedMemoryRatio?: number;- snapshotHistorySecs?: number;+ useSampleWindow(maxSampleWindowMillis: number): void;}// @public (undocumented)@@ -1807,24 +1773,6 @@ export interface SystemInfo {memTotalBytes?: number;}-// @public-export class SystemStatus {- constructor(options?: SystemStatusOptions);- getCurrentStatus(): SystemInfo;- getHistoricalStatus(): SystemInfo;-}--// @public (undocumented)-export interface SystemStatusOptions {- currentHistorySecs?: number;- loadSignals?: LoadSignal[];- maxClientOverloadedRatio?: number;- maxCpuOverloadedRatio?: number;- maxEventLoopOverloadedRatio?: number;- maxMemoryOverloadedRatio?: number;- snapshotter?: Snapshotter;-}-export { tryAbsoluteURL }// @public (undocumented)diff --git a/docs/public-api/crawlee-http.api.md b/docs/public-api/crawlee-http.api.mdindex 09bf5f072..ec72d8014 100644--- a/docs/public-api/crawlee-http.api.md+++ b/docs/public-api/crawlee-http.api.md@@ -9,9 +9,11 @@ import { ArrayPredicate } from 'ow';import type { Awaitable } from '@crawlee/types';import { BasePredicate } from 'ow';import { BasicCrawler } from '@crawlee/basic';-import type { BasicCrawlerOptions } from '@crawlee/basic';+import { BasicCrawlerOptions } from '@crawlee/basic';import { BooleanPredicate } from 'ow';import { CheerioRoot } from '@crawlee/utils';+import { ConcurrencySystem } from '@crawlee/basic';+import type { ConcurrencySystemOptions } from '@crawlee/basic';import { ContextPipeline } from '@crawlee/basic';import type { CrawlingContext } from '@crawlee/basic';import type { CrawlingContext as CrawlingContext_2 } from '@crawlee/core';@@ -91,11 +93,15 @@ export type FileDownloadHook<UserData extends Dictionary = any> = InternalHttpHo// @public (undocumented)export type FileDownloadRequestHandler<UserData extends Dictionary = any> = RequestHandler<FileDownloadCrawlingContext<UserData>>;+// @public+export const HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS: ConcurrencySystemOptions;+// @publicexport class HttpCrawler<Context extends InternalHttpCrawlingContext<any, any> = InternalHttpCrawlingContext, ContextExtension = Dictionary<never>, ExtendedContext extends Context = Context & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<Context['request']>>> extends BasicCrawler<Context, ContextExtension, ExtendedContext, Routes> {constructor(options?: HttpCrawlerOptions<Context, ContextExtension, ExtendedContext> & RequireContextPipeline<InternalHttpCrawlingContext, Context>);// (undocumented)protected buildContextPipeline(): ContextPipeline<CrawlingContext, InternalHttpCrawlingContext>;+ protected createDefaultConcurrencySystem(options: ConcurrencySystemOptions): ConcurrencySystem;// (undocumented)protected isRequestBlocked(crawlingContext: InternalHttpCrawlingContext): Promise<string | false>;// (undocumented)@@ -121,6 +127,7 @@ export class HttpCrawler<Context extends InternalHttpCrawlingContext<any, any> =maxRequestsPerCrawl: NumberPredicate & BasePredicate<number | undefined>;maxCrawlDepth: NumberPredicate & BasePredicate<number | undefined>;autoscaledPoolOptions: ObjectPredicate<object> & BasePredicate<object | undefined>;+ concurrencySystem: ObjectPredicate<object> & BasePredicate<object | undefined>;sessionPool: ObjectPredicate<object> & BasePredicate<object | undefined>;proxyConfiguration: ObjectPredicate<object> & BasePredicate<object | undefined>;statusMessageLoggingInterval: NumberPredicate & BasePredicate<number | undefined>;diff --git a/docs/public-api/crawlee-jsdom.api.md b/docs/public-api/crawlee-jsdom.api.mdindex bdeb78cec..671aded46 100644--- a/docs/public-api/crawlee-jsdom.api.md+++ b/docs/public-api/crawlee-jsdom.api.md@@ -84,6 +84,7 @@ export class JSDOMCrawler<ContextExtension = Dictionary<never>, ExtendedContextmaxRequestsPerCrawl: NumberPredicate & BasePredicate<number | undefined>;maxCrawlDepth: NumberPredicate & BasePredicate<number | undefined>;autoscaledPoolOptions: ObjectPredicate<object> & BasePredicate<object | undefined>;+ concurrencySystem: ObjectPredicate<object> & BasePredicate<object | undefined>;sessionPool: ObjectPredicate<object> & BasePredicate<object | undefined>;proxyConfiguration: ObjectPredicate<object> & BasePredicate<object | undefined>;statusMessageLoggingInterval: NumberPredicate & BasePredicate<number | undefined>;diff --git a/docs/public-api/crawlee-playwright.api.md b/docs/public-api/crawlee-playwright.api.mdindex 19ab6bcfb..ee2b305ad 100644--- a/docs/public-api/crawlee-playwright.api.md+++ b/docs/public-api/crawlee-playwright.api.md@@ -299,6 +299,7 @@ export class PlaywrightCrawler<ContextExtension = Dictionary_2<never>, ExtendedCmaxRequestsPerCrawl: NumberPredicate & BasePredicate<number | undefined>;maxCrawlDepth: NumberPredicate & BasePredicate<number | undefined>;autoscaledPoolOptions: ObjectPredicate<object> & BasePredicate<object | undefined>;+ concurrencySystem: ObjectPredicate<object> & BasePredicate<object | undefined>;sessionPool: ObjectPredicate<object> & BasePredicate<object | undefined>;statusMessageLoggingInterval: NumberPredicate & BasePredicate<number | undefined>;statusMessageCallback: Predicate<Function> & BasePredicate<Function | undefined>;diff --git a/docs/public-api/crawlee-puppeteer.api.md b/docs/public-api/crawlee-puppeteer.api.mdindex 81157a736..216462bb5 100644--- a/docs/public-api/crawlee-puppeteer.api.md+++ b/docs/public-api/crawlee-puppeteer.api.md@@ -214,6 +214,7 @@ export class PuppeteerCrawler<ContextExtension = Dictionary<never>, ExtendedContmaxRequestsPerCrawl: NumberPredicate & BasePredicate<number | undefined>;maxCrawlDepth: NumberPredicate & BasePredicate<number | undefined>;autoscaledPoolOptions: ObjectPredicate<object> & BasePredicate<object | undefined>;+ concurrencySystem: ObjectPredicate<object> & BasePredicate<object | undefined>;sessionPool: ObjectPredicate<object> & BasePredicate<object | undefined>;statusMessageLoggingInterval: NumberPredicate & BasePredicate<number | undefined>;statusMessageCallback: Predicate<Function> & BasePredicate<Function | undefined>;diff --git a/docs/public-api/crawlee-stagehand.api.md b/docs/public-api/crawlee-stagehand.api.mdindex f35f7c262..4b8379989 100644--- a/docs/public-api/crawlee-stagehand.api.md+++ b/docs/public-api/crawlee-stagehand.api.md@@ -111,6 +111,7 @@ export class StagehandCrawler<ContextExtension = Dictionary<never>, ExtendedContmaxRequestsPerCrawl: NumberPredicate & BasePredicate<number | undefined>;maxCrawlDepth: NumberPredicate & BasePredicate<number | undefined>;autoscaledPoolOptions: ObjectPredicate<object> & BasePredicate<object | undefined>;+ concurrencySystem: ObjectPredicate<object> & BasePredicate<object | undefined>;sessionPool: ObjectPredicate<object> & BasePredicate<object | undefined>;statusMessageLoggingInterval: NumberPredicate & BasePredicate<number | undefined>;statusMessageCallback: Predicate<Function> & BasePredicate<Function | undefined>;diff --git a/docs/upgrading/upgrading_v4.md b/docs/upgrading/upgrading_v4.mdindex d034e0031..7c46eec0d 100644--- a/docs/upgrading/upgrading_v4.md+++ b/docs/upgrading/upgrading_v4.md@@ -52,7 +52,7 @@ The change spans, among others:- **`BasicCrawler`** — `unexpectedStop`, `requestHandlerTimeoutMillis`, `sameDomainDelayMillis`, `domainAccessedTime`, `handledRequestsCount`, `statusMessageLoggingInterval`, `statusMessageCallback`, `ignoreHttpErrorStatusCodes`, `autoscaledPoolOptions`, `respectRobotsTxtFile`, and the helpers `buildBasicContextPipeline`, `validateRequestUserData`, `pauseOnMigration`, `fetchNextRequest`, `delayRequest`, `handleRequest`, `timeoutAndRetry`, `isTaskReadyFunction`, `defaultIsFinishedFunction`, `requestFunctionErrorHandler`, `handleFailedRequestHandler`, `canRequestBeRetried`- **`HttpCrawler`** — `preNavigationHooks`, `postNavigationHooks`, `saveResponseCookies`, `navigationTimeoutMillis`, `ignoreSslErrors`, `suggestResponseEncoding`, `forceResponseEncoding`, `supportedMimeTypes`, and the helpers `requestFunction`, `parseResponse`, `getRequestOptions`, `encodeResponse`, `extendSupportedMimeTypes`, `handleRequestTimeout`-- **`AutoscaledPool`** — `autoscale`, `maybeRunTask`, `incrementTasksDonePerSecond`, `maybeFinish`, `destroy`, `scaleUp`, `scaleDown`, `isOverMaxRequestLimit`+- **`AutoscaledPool`** — `maybeRunTask`, `maybeFinish`, `destroy` (the scaling internals `autoscale`, `scaleUp`, `scaleDown`, `incrementTasksDonePerSecond` and `isOverMaxRequestLimit` are private too, but they now live on the `ConcurrencySystem` the pool delegates to — see [below](#autoscaling-split-into-autoscaledpool--concurrencysystem))- **`SessionPool`** — all pool internals (`log`, `maxPoolSize`, `createSessionFunction`, `keyValueStore`, `sessions`, `sessionMap`, `sessionOptions`, `persistStateKey`, `persistStateKeyValueStoreId`, `events`, `persistenceOptions`, `sessionReuseStrategy`, and the helpers `ensureInitialized`, `maybeLoadSessionPool`, `registerSession`, `createSession`, `hasSpaceForSession`, `pickSession`, `removeRetiredSessions`, `getRandomIndex`, `defaultCreateSessionFunction`)- **`Session`** — `maybeSelfRetire` (`userData` is now `readonly`)- **`RequestList`** — all `_`-prefixed helpers (`addFetchedRequests`, `addPersistedRequests`, `addRequest`, `addRequestsFromSources`, `ensureInProgress`, `ensureIsInitialized`, `ensureUniqueKeyValid`, `fetchRequestsFromUrl`, `getPersistedState`, `loadStateAndPersistedRequests`, `persistRequests`, `restoreState`)@@ -112,7 +112,7 @@ The browser *launchers* (`PlaywrightLauncher`, `PuppeteerLauncher`) keep their `- `BasicCrawler._tagUserHandlerError` (protected) - internal error-tagging helper, no longer part of the crawler surface- `BasicCrawler.handledRequestsCount` setter (`@deprecated`) - the throw-on-assign guard is gone; the getter is now internal-only and the count is derived from `this.stats`- `PlaywrightPlugin._containerProxyServer` (public) - was an unused, never-populated field-- `Snapshotter._snapshotMemory`, `Snapshotter._memoryOverloadWarning`, `Snapshotter._snapshotEventLoop`, `Snapshotter._snapshotCpu`, `Snapshotter._snapshotClient`, `Snapshotter._pruneSnapshots` (all `@deprecated` protected stubs) - snapshotting is handled by the individual load signals, use `Snapshotter.getMemorySample()` / `getEventLoopSample()` / `getCpuSample()` / `getClientSample()` instead+- `Snapshotter._snapshotMemory`, `Snapshotter._memoryOverloadWarning`, `Snapshotter._snapshotEventLoop`, `Snapshotter._snapshotCpu`, `Snapshotter._snapshotClient`, `Snapshotter._pruneSnapshots` (all `@deprecated` protected stubs) - snapshotting is now handled by the individual load signals, and the `Snapshotter` itself is internal to `ConcurrencySystem`; there is no longer a public API for reading raw resource snapshots- `FileDownloadOptions.streamHandler` - streaming should now be handled directly in the `requestHandler` instead- `playwrightUtils.registerUtilsToContext` and `puppeteerUtils.registerUtilsToContext` - this is now added to the context via `ContextPipeline` composition- `context.blockResources` and `context.cacheResponses` — no longer attached to the crawling context. The functionality is still available as deprecated functions, accessible both via the `puppeteerUtils` namespace (`puppeteerUtils.blockResources`, `puppeteerUtils.cacheResponses`) and as top-level exports from `@crawlee/puppeteer` (`import { blockResources, cacheResponses } from '@crawlee/puppeteer'`). Unlike the old context helpers, these take an explicit `page` argument — e.g. `await blockResources(page)`. Both are `@deprecated` and will be removed in a future release, so migrate away from them.@@ -1200,6 +1200,216 @@ If you rely on Crawlee's default configuration (one browser context per session,The `log` property exposed throughout the public API (on the crawling context, `AutoscaledPool`, `Statistics`, `EventManager`, `SessionOptions`, `Dataset`, etc.) is now typed as the `CrawleeLogger` interface (from `@crawlee/types`) rather than the concrete `Log` class from `@apify/log`. If you consume it structurally — calling `log.info(...)`, `log.debug(...)`, `log.child(...)` — nothing changes. You only need to act if you explicitly annotated a variable or parameter with the `Log` type from `@apify/log` and assigned `context.log` to it; type it as `CrawleeLogger` instead.+## Autoscaling split into `AutoscaledPool` + `ConcurrencySystem`++Everything that decides whether there is free compute for one more task — snapshotting, the system-status evaluation, the concurrency budget and the scaling logic — moved out of `AutoscaledPool` into a new `ConcurrencySystem`. The pool keeps only the task loop.++The point is sharing: inject one instance into several pools (and therefore several crawlers) to cap their **combined** concurrency against a single budget, instead of letting each scale independently and oversubscribe the host. The option is typed as `IConcurrencySystem`, a minimal read-only contract, so an alternative governor can be substituted; `ConcurrencySystem` is the canonical implementation and the one crawlers build by default.++:::info Who starts and stops it++Whoever *builds* a `ConcurrencySystem` owns its lifecycle. Crawlers do that for the default system they build per run. One **you** supply is yours to `start()` and `stop()`, because no crawler can know when the last borrower has finished. Forgetting to start it makes `run()` **throw**; stopping it while a pool is still running only **warns**. Read `isRunning` to check whether a system handed to you was already started by its owner.++:::++Every migration below has the same shape — build, start, run, stop:++```typescript+import { CheerioCrawler, ConcurrencySystem } from 'crawlee';++const concurrencySystem = new ConcurrencySystem({ maxConcurrency: 20 });+await concurrencySystem.start();++// One crawler, or several: a shared instance caps their combined concurrency.+const a = new CheerioCrawler({ concurrencySystem, requestHandler });+const b = new CheerioCrawler({ concurrencySystem, requestHandler });++try {+ await Promise.all([a.run(), b.run()]);+} finally {+ await concurrencySystem.stop();+}+```++The `AutoscaledPool` migration below spells it out once more at the pool level; the crawler examples elide it, to keep the actual change in focus.++### `AutoscaledPool` requires a `concurrencySystem` and a `consumer`, and no longer takes scaling options++All scaling and load-monitoring options were **removed** from `AutoscaledPoolOptions` and now live on `ConcurrencySystemOptions`: `minConcurrency`, `maxConcurrency`, `desiredConcurrency`, `desiredConcurrencyRatio`, `scaleUpStepRatio`, `scaleDownStepRatio`, `loggingIntervalSecs`, `autoscaleIntervalSecs`, and `maxTasksPerMinute`, plus the load-signal configuration described [below](#load-signal-options-restructured). The `snapshotterOptions` and `systemStatusOptions` bags are both gone. In their place, `AutoscaledPoolOptions` gained a **required** `concurrencySystem`, plus a **required** `consumer` — the pool's identity (`{ id }`), which it presents to the governor on every capacity query and booking so that a shared one can tell several pools' tasks apart. Crawlers pass their own identity, so this only concerns pools you build yourself.++**Before:**+```typescript+const pool = new AutoscaledPool({+ minConcurrency: 5,+ maxConcurrency: 50,+ maxTasksPerMinute: 120,+ runTaskFunction: async () => { /* ... */ },+ isTaskReadyFunction: async () => true,+ isFinishedFunction: async () => false,+});+await pool.run();+```++**After:**+```typescript+import { AutoscaledPool, ConcurrencySystem } from '@crawlee/core';++const concurrencySystem = new ConcurrencySystem({+ minConcurrency: 5,+ maxConcurrency: 50,+ maxTasksPerMinute: 120,+});+await concurrencySystem.start();++const pool = new AutoscaledPool({+ concurrencySystem,+ consumer: { id: 'my-pool' },+ runTaskFunction: async () => { /* ... */ },+ isTaskReadyFunction: async () => true,+ isFinishedFunction: async () => false,+});++try {+ await pool.run();+} finally {+ await concurrencySystem.stop();+}+```++The pool's concurrency accessors are now read-only telemetry: `desiredConcurrency` and `currentConcurrency` remain as getters, while the `minConcurrency`/`maxConcurrency` accessors and every setter were **removed**. Runtime tuning happens on the `ConcurrencySystem` instead — which means building it yourself, since the system a crawler builds for itself is not reachable for reconfiguration:++```typescript+const concurrencySystem = new ConcurrencySystem({ maxConcurrency: 50 });++const crawler = new CheerioCrawler({+ concurrencySystem,+ requestHandler,+ errorHandler: async ({ response }) => {+ if (response?.status === 429) concurrencySystem.maxConcurrency = 10;+ },+});+```++One behavioral consequence: `pool.pause()` no longer suspends autoscaling, because the autoscaling interval belongs to the `ConcurrencySystem`, which knows nothing about its borrowers' pause state — deliberately, since other pools sharing it may still need scaling. A paused pool's system keeps evaluating (and possibly scaling down) the desired concurrency and keeps emitting its periodic state log. Scaling *up* stays effectively blocked, as the current concurrency drains below the ratio required for a scale-up. To silence the system during a long pause, `stop()` it (if you own it) and `start()` it again before resuming; a restart discards the snapshots taken before it, so the pause is not mistaken for load.++### `BasicCrawlerOptions.autoscaledPoolOptions` no longer carries concurrency config++`autoscaledPoolOptions` now accepts **only** the task-loop predicates `isFinishedFunction` and `isTaskReadyFunction` (its type changed from `AutoscaledPoolOptions` to `AutoscaledPoolPredicateOptions`). Concurrency configuration goes through either the `minConcurrency` / `maxConcurrency` / `maxRequestsPerMinute` shortcuts (which configure the crawler's default `ConcurrencySystem`), or — for anything finer — a supplied `concurrencySystem`.++Note that this narrowing also drops three options that did *not* move to the `ConcurrencySystem`: `maybeRunIntervalSecs`, `taskTimeoutSecs` and `log` are still `AutoscaledPoolOptions`, but a crawler no longer forwards them, so they can only be set by driving an `AutoscaledPool` yourself. If you were tuning the crawler's task-loop cadence through `autoscaledPoolOptions`, there is no replacement.++**Before:**+```typescript+const crawler = new CheerioCrawler({+ autoscaledPoolOptions: {+ desiredConcurrency: 10,+ maxTasksPerMinute: 120,+ systemStatusOptions: { currentHistorySecs: 10 },+ },+ requestHandler,+});+```++**After:**+```typescript+const concurrencySystem = new ConcurrencySystem({+ desiredConcurrency: 10,+ maxTasksPerMinute: 120,+ currentHistorySecs: 10,+});++const crawler = new CheerioCrawler({ concurrencySystem, requestHandler });+```++The shortcuts cannot be combined with a supplied `concurrencySystem` — they configure the default system that a supplied one replaces, so the crawler constructor **throws** rather than dropping a limit you asked for. For the common case, the shortcuts are all you need and no `ConcurrencySystem` is involved:++```typescript+const crawler = new CheerioCrawler({+ minConcurrency: 5,+ maxConcurrency: 50,+ maxRequestsPerMinute: 120,+ requestHandler,+});+```++A supplied system also replaces the default *wholesale*, including any crawler-specific tuning that default carried. `HttpCrawler` and its subclasses (`CheerioCrawler`, `JSDOMCrawler`, …) ship a preset — a higher `desiredConcurrency` and a relaxed event loop signal — exported as `HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS`; spread it in to keep it:++```typescript+import { ConcurrencySystem, HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS } from 'crawlee';++const concurrencySystem = new ConcurrencySystem({+ ...HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS,+ maxConcurrency: 50,+});+```++## Load-signal options restructured++The per-resource load-signal configuration was consolidated. It used to be spread across flat `SnapshotterOptions` fields, the `max*OverloadedRatio` options on `SystemStatusOptions`, and a separate `loadSignals` array — three places, two of them named after classes that are now internal. All of it now lives in a single `loadSignals` bag on `ConcurrencySystemOptions`: one options bag per built-in signal (each carrying its own limits *and* its `overloadedRatio`), plus `custom` for your own implementations.++**Before:**+```typescript+new AutoscaledPool({+ snapshotterOptions: {+ maxUsedMemoryRatio: 0.8,+ eventLoopSnapshotIntervalSecs: 2,+ maxBlockedMillis: 100,+ clientSnapshotIntervalSecs: 1,+ maxClientErrors: 3,+ snapshotHistorySecs: 60,+ },+ systemStatusOptions: {+ maxMemoryOverloadedRatio: 0.2,+ maxEventLoopOverloadedRatio: 0.7,+ maxCpuOverloadedRatio: 0.4,+ maxClientOverloadedRatio: 0.3,+ currentHistorySecs: 10,+ loadSignals: [myProxyHealthSignal],+ },+ // ...+});+```++**After:**+```typescript+new ConcurrencySystem({+ loadSignals: {+ memory: { maxUsedRatio: 0.8, overloadedRatio: 0.2 },+ eventLoop: { snapshotIntervalSecs: 2, maxBlockedMillis: 100, overloadedRatio: 0.7 },+ cpu: { overloadedRatio: 0.4 },+ client: { snapshotIntervalSecs: 1, maxErrors: 3, overloadedRatio: 0.3 },+ custom: [myProxyHealthSignal],+ },+ // the two evaluation windows are policy, alongside the scaling options+ snapshotHistorySecs: 60,+ currentHistorySecs: 10,+});+```++In detail: the four `max*OverloadedRatio` options of `SystemStatusOptions` were **removed** (each signal now owns its overload ratio, set in its own bag), custom signals moved from `systemStatusOptions.loadSignals` to `loadSignals.custom`, and the two evaluation windows — `snapshotHistorySecs` (autoscaling) and `currentHistorySecs` (task gating) — are plain options on `ConcurrencySystemOptions`, since they apply to every signal alike rather than to any one of them.++Two related capabilities are new, and covered in the [scaling guide](../guides/scaling-crawlers#load-signals): a built-in signal can be switched **off** with `false`, and each built-in is also a public class (`MemoryLoadSignal`, `EventLoopLoadSignal`, `CpuLoadSignal`, `ClientLoadSignal`) you can construct to wrap or adapt.++A duplicate signal name now **throws**, where naming a custom signal after a built-in (`memInfo`, `eventLoopInfo`, `cpuInfo`, `clientInfo`) used to look like an override but never was one: the built-in kept running and kept holding concurrency down, while your signal only overwrote its field in the reported `SystemInfo`. To take a built-in's place, switch it off:++```typescript+new ConcurrencySystem({+ loadSignals: {+ // Without `memory: false`, this throws — the built-in memory signal is still enabled.+ memory: false,+ custom: [myMemorySignal], // free to take over the vacated `memInfo` field+ },+});+```++`Snapshotter` and `SystemStatus` are no longer public API, along with `SnapshotterOptions` and `SystemStatusOptions` — they are implementation details of the `ConcurrencySystem`, which is now the only supported entry point to load monitoring; read the resulting `SystemInfo` through `ConcurrencySystem.getCurrentStatus()`. Still public: the configuration types, the four built-in signal classes, and the extension surface (`LoadSignal`, `SnapshotStore`, `LoadSignalStartContext`). The concrete snapshot types the built-ins produce are *not* — `getSample()` returns plain `LoadSnapshot` values.++### Both evaluation windows are now requested from every signal++Overload is evaluated over two windows: `currentHistorySecs` (default 5s) gates whether another task may start, and `snapshotHistorySecs` (default 30s) drives autoscaling. The long one used to be implicit — `getHistoricalStatus()` asked each signal for *everything it had retained*, so a custom signal keeping five minutes of snapshots silently made autoscaling reason over five minutes of history for that resource while the built-ins used 30 seconds. Both are now requested explicitly from every signal, and `LoadSignal.start()` receives the wider of the two as `maxSampleWindowMillis` so retention can be sized to match.++You are affected if a custom signal retains **more** history than `snapshotHistorySecs` (its stale snapshots no longer influence scaling), or if its `getSample()` ignores the `sampleDurationMillis` argument, in which case it still contributes everything it has. On the API side, `snapshotHistoryMillis` was removed from the per-signal option types and `SnapshotStore` lost both its constructor argument and the `fromInterval`/`fromEvent` factories; call `useSampleWindow(maxSampleWindowMillis)` and `clear()` from your `start()` instead, as a store that is never given a window retains everything. The [scaling guide](../guides/scaling-crawlers#load-signals) has a worked example.+## Stagehand type narrowingsA few Stagehand-specific option types were tightened:diff --git a/packages/basic-crawler/README.md b/packages/basic-crawler/README.mdindex e2a789779..cf8a445a2 100644--- a/packages/basic-crawler/README.md+++ b/packages/basic-crawler/README.md@@ -11,7 +11,7 @@ If both [`requestList`](https://crawlee.dev/js/api/basic-crawler/interface/BasicThe crawler finishes if there are no more [Request](https://crawlee.dev/js/api/core/class/Request) objects to crawl.-New requests are only dispatched when there is enough free CPU and memory available, using the functionality provided by the [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) class. All [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) configuration options can be passed to the [`autoscaledPoolOptions`](https://crawlee.dev/js/api/basic-crawler/interface/BasicCrawlerOptions#autoscaledPoolOptions) parameter of the `BasicCrawler` constructor. For user convenience, the [`minConcurrency`](https://crawlee.dev/js/api/core/interface/AutoscaledPoolOptions#minConcurrency) and [`maxConcurrency`](https://crawlee.dev/js/api/core/interface/AutoscaledPoolOptions#maxConcurrency) options of the underlying [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) constructor are available directly in the `BasicCrawler` constructor.+New requests are only dispatched when there is enough free CPU and memory available, using the functionality provided by the [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) class. Concurrency is tuned via the [`minConcurrency`](https://crawlee.dev/js/api/basic-crawler/interface/BasicCrawlerOptions#minConcurrency), [`maxConcurrency`](https://crawlee.dev/js/api/basic-crawler/interface/BasicCrawlerOptions#maxConcurrency) and [`maxRequestsPerMinute`](https://crawlee.dev/js/api/basic-crawler/interface/BasicCrawlerOptions#maxRequestsPerMinute) options of the `BasicCrawler` constructor, or, for finer control, by injecting a pre-configured [`concurrencySystem`](https://crawlee.dev/js/api/basic-crawler/interface/BasicCrawlerOptions#concurrencySystem) — see `ConcurrencySystem`.## Example usagediff --git a/packages/basic-crawler/src/internals/basic-crawler.ts b/packages/basic-crawler/src/internals/basic-crawler.tsindex 0d299535b..a5c9186db 100644--- a/packages/basic-crawler/src/internals/basic-crawler.ts+++ b/packages/basic-crawler/src/internals/basic-crawler.ts@@ -5,6 +5,8 @@ import type {AddRequestsBatchedOptions,AddRequestsBatchedResult,AutoscaledPoolOptions,+ AutoscaledPoolPredicateOptions,+ ConcurrencySystemOptions,Configuration,CrawleeLogger,CrawlingContext,@@ -14,6 +16,7 @@ import type {EventStatusMessageData,FinalStatistics,GetUserDataFromRequest,+ IConcurrencySystem,IProxyConfiguration,IRequestLoader,IRequestManager,@@ -33,6 +36,7 @@ import {AutoscaledPool,bindMethodsToServiceLocator,BLOCKED_STATUS_CODES,+ ConcurrencySystem,ContextPipeline,ContextPipelineCleanupError,ContextPipelineInitializationError,@@ -82,7 +86,7 @@ import type {import { isAsyncIterable, isIterable, RobotsTxtFile, ROTATE_PROXY_ERRORS } from '@crawlee/utils';import { stringify } from 'csv-stringify/sync';import { ensureDir, writeJSON } from 'fs-extra/esm';-import ow from 'ow';+import ow, { ArgumentError } from 'ow';import { getDomain } from 'tldts';import type { ReadonlyDeep, SetRequired } from 'type-fest';@@ -307,17 +311,36 @@ export interface BasicCrawlerOptions<maxCrawlDepth?: number;/**- * Custom options passed to the underlying {@apilink AutoscaledPool} constructor.- * > *NOTE:* The {@apilink AutoscaledPoolOptions.runTaskFunction|`runTaskFunction`}- * option is provided by the crawler and cannot be overridden.- * However, we can provide custom implementations of {@apilink AutoscaledPoolOptions.isFinishedFunction|`isFinishedFunction`}- * and {@apilink AutoscaledPoolOptions.isTaskReadyFunction|`isTaskReadyFunction`}.+ * Lets you override the task-loop predicates (`isFinishedFunction`, `isTaskReadyFunction`) of the crawler's+ * underlying {@apilink AutoscaledPool}. The `runTaskFunction` is owned by the crawler and cannot be overridden.+ *+ * Concurrency is configured elsewhere — through the `minConcurrency`/`maxConcurrency`/`maxRequestsPerMinute`+ * shortcuts, or a {@apilink BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} for finer control.*/- autoscaledPoolOptions?: AutoscaledPoolOptions;+ autoscaledPoolOptions?: AutoscaledPoolPredicateOptions;++ /**+ * A pre-configured concurrency governor — the component that decides whether there is free compute for one more+ * task. Typically a {@apilink ConcurrencySystem}, though any {@apilink IConcurrencySystem} is accepted. All+ * scaling configuration (min/max/desired concurrency, scaling ratios, `maxTasksPerMinute`, snapshotter tuning)+ * lives on the instance itself.+ *+ * Inject the *same* instance into several concurrent crawlers to cap their **combined** concurrency against a+ * single budget. Each crawler still builds and drives its own {@apilink AutoscaledPool}; only the load/scaling+ * accounting is shared.+ *+ * Mutually exclusive with the `minConcurrency`/`maxConcurrency`/`maxRequestsPerMinute` shortcuts, which configure+ * the default system this one replaces — combining the two throws.+ *+ * You own a supplied system's lifecycle: `start()` it before `run()` (which throws otherwise) and `stop()` it once+ * every crawler borrowing it has finished. The crawler does neither on your behalf.+ */+ concurrencySystem?: IConcurrencySystem;/*** Sets the minimum concurrency (parallelism) for the crawl. Shortcut for the- * AutoscaledPool {@apilink AutoscaledPoolOptions.minConcurrency|`minConcurrency`} option.+ * {@apilink ConcurrencySystemOptions.minConcurrency|`minConcurrency`} option of the crawler's default+ * {@apilink ConcurrencySystem}.* > *WARNING:* If we set this value too high with respect to the available system memory and CPU, our crawler will run extremely slow or crash.* If not sure, it's better to keep the default value and the concurrency will scale up automatically.*/@@ -325,14 +348,16 @@ export interface BasicCrawlerOptions</*** Sets the maximum concurrency (parallelism) for the crawl. Shortcut for the- * AutoscaledPool {@apilink AutoscaledPoolOptions.maxConcurrency|`maxConcurrency`} option.+ * {@apilink ConcurrencySystemOptions.maxConcurrency|`maxConcurrency`} option of the crawler's default+ * {@apilink ConcurrencySystem}.*/maxConcurrency?: number;/*** The maximum number of requests per minute the crawler should run.* By default, this is set to `Infinity`, but we can pass any positive, non-zero integer.- * Shortcut for the AutoscaledPool {@apilink AutoscaledPoolOptions.maxTasksPerMinute|`maxTasksPerMinute`} option.+ * Shortcut for the {@apilink ConcurrencySystemOptions.maxTasksPerMinute|`maxTasksPerMinute`} option of the+ * crawler's default {@apilink ConcurrencySystem}.*/maxRequestsPerMinute?: number;@@ -514,11 +539,10 @@ export interface BasicCrawlerOptions<** New requests are only dispatched when there is enough free CPU and memory available,* using the functionality provided by the {@apilink AutoscaledPool} class.- * All {@apilink AutoscaledPool} configuration options can be passed to the {@apilink BasicCrawlerOptions.autoscaledPoolOptions|`autoscaledPoolOptions`}- * parameter of the `BasicCrawler` constructor.- * For user convenience, the {@apilink AutoscaledPoolOptions.minConcurrency|`minConcurrency`} and- * {@apilink AutoscaledPoolOptions.maxConcurrency|`maxConcurrency`} options of the- * underlying {@apilink AutoscaledPool} constructor are available directly in the `BasicCrawler` constructor.+ * Concurrency is tuned via the {@apilink BasicCrawlerOptions.minConcurrency|`minConcurrency`},+ * {@apilink BasicCrawlerOptions.maxConcurrency|`maxConcurrency`} and+ * {@apilink BasicCrawlerOptions.maxRequestsPerMinute|`maxRequestsPerMinute`} shortcuts, or, for finer control, by+ * injecting a pre-configured {@apilink BasicCrawlerOptions.concurrencySystem|`concurrencySystem`}.** **Example usage:***@@ -627,11 +651,24 @@ export class BasicCrawler<private requestManagerTimeoutsApplied = false;/**- * A reference to the underlying {@apilink AutoscaledPool} class that manages the concurrency of the crawler.+ * Resolves the governor for one run: either the injected+ * {@apilink BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} (borrowed) or a freshly built default with+ * the concurrency shortcuts folded in (owned, so the crawler starts and stops it).+ */+ private readonly resolveConcurrencySystem: () => OwnedOrInjected<IConcurrencySystem, ConcurrencySystem>;++ /** As resolved by `_init()`. Absent until the first run, so a `teardown()` before it is a no-op. */+ private concurrencySystemDep?: OwnedOrInjected<IConcurrencySystem, ConcurrencySystem>;++ /**+ * A reference to the underlying {@apilink AutoscaledPool} class that runs the crawler's task loop.* > *NOTE:* This property is only initialized after calling the {@apilink BasicCrawler.run|`crawler.run()`} function.- * We can use it to change the concurrency settings on the fly,- * to pause the crawler by calling {@apilink AutoscaledPool.pause|`autoscaledPool.pause()`}+ * We can use it to pause the crawler by calling {@apilink AutoscaledPool.pause|`autoscaledPool.pause()`}* or to abort it by calling {@apilink AutoscaledPool.abort|`autoscaledPool.abort()`}.+ *+ * The pool only exposes read-only concurrency telemetry. To tune concurrency at runtime, keep a reference to a+ * {@apilink ConcurrencySystem} and inject it via+ * {@apilink BasicCrawlerOptions.concurrencySystem|`concurrencySystem`}.*/autoscaledPool?: AutoscaledPool;@@ -708,7 +745,13 @@ export class BasicCrawler<protected blockedStatusCodes = new Set<number>();protected readonly additionalHttpErrorStatusCodes: Set<number>;private ignoreHttpErrorStatusCodes: Set<number>;- private autoscaledPoolOptions: AutoscaledPoolOptions;+ /**+ * The resolved task-loop options for the crawler's own {@apilink AutoscaledPool} — the crawler-owned+ * `runTaskFunction`, the (possibly user-overridden) ready/finished predicates and cadence/logging. Concurrency+ * configuration lives on the {@apilink ConcurrencySystem} instead, and the pool's `consumer` identity is the+ * crawler's own, so neither is settable here.+ */+ private autoscaledPoolOptions: Omit<AutoscaledPoolOptions, 'concurrencySystem' | 'consumer'>;protected readonly httpClient: BaseHttpClient;protected readonly retryOnBlocked: boolean;private respectRobotsTxtFile: boolean | { userAgent?: string };@@ -740,6 +783,7 @@ export class BasicCrawler<maxRequestsPerCrawl: ow.optional.number,maxCrawlDepth: ow.optional.number,autoscaledPoolOptions: ow.optional.object,+ concurrencySystem: ow.optional.object,sessionPool: ow.optional.object.validate(validators.sessionPool),proxyConfiguration: ow.optional.object.validate(validators.proxyConfiguration),@@ -791,6 +835,7 @@ export class BasicCrawler<maxRequestsPerCrawl,maxCrawlDepth,autoscaledPoolOptions = {},+ concurrencySystem,keepAlive,sessionPool,proxyConfiguration,@@ -825,6 +870,21 @@ export class BasicCrawler<id,} = options;+ // All concurrency configuration lives on the `ConcurrencySystem`, so the shortcuts have nowhere to go once+ // one is supplied - and silently dropping a `maxConcurrency` the user asked for is how crawls end up+ // hammering a site.+ if (+ concurrencySystem !== undefined &&+ (minConcurrency !== undefined || maxConcurrency !== undefined || maxRequestsPerMinute !== undefined)+ ) {+ throw new ArgumentError(+ 'The `minConcurrency`/`maxConcurrency`/`maxRequestsPerMinute` shortcuts cannot be combined with ' ++ '`concurrencySystem` - they configure the default `ConcurrencySystem` that a supplied one ' ++ 'replaces. Pass them to the `ConcurrencySystem` constructor instead.',+ this.constructor,+ );+ }+// Create per-crawler service locator if custom services were provided.// This wraps every method on the crawler instance so that calls to the global `serviceLocator`// (via AsyncLocalStorage) resolve to this scoped instance instead.@@ -966,10 +1026,7 @@ export class BasicCrawler<isFinishedFunction = async () => false;}- const basicCrawlerAutoscaledPoolConfiguration: Partial<AutoscaledPoolOptions> = {- minConcurrency: minConcurrency ?? autoscaledPoolOptions?.minConcurrency,- maxConcurrency: maxConcurrency ?? autoscaledPoolOptions?.maxConcurrency,- maxTasksPerMinute: maxRequestsPerMinute ?? autoscaledPoolOptions?.maxTasksPerMinute,+ const basicCrawlerAutoscaledPoolConfiguration: Partial<typeof this.autoscaledPoolOptions> = {runTaskFunction: async () => {const source = this.requestManager;if (!source) throw new Error('Request provider is not initialized!');@@ -1095,11 +1152,33 @@ export class BasicCrawler<};this.autoscaledPoolOptions = { ...autoscaledPoolOptions, ...basicCrawlerAutoscaledPoolConfiguration };++ this.resolveConcurrencySystem = () =>+ OwnedOrInjected.resolve<IConcurrencySystem, ConcurrencySystem>(concurrencySystem, () =>+ this.createDefaultConcurrencySystem({+ minConcurrency,+ maxConcurrency,+ maxTasksPerMinute: maxRequestsPerMinute,+ log: this.log,+ }),+ );} finally {serviceLocatorScope.exitScope();}}+ /**+ * Builds the crawler-owned default {@apilink ConcurrencySystem} from the resolved+ * `minConcurrency`/`maxConcurrency`/`maxRequestsPerMinute` shortcuts. Not called when a+ * {@apilink BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} was injected.+ *+ * Subclasses may override this to tune the default system (e.g. {@apilink HttpCrawler} raises the starting+ * concurrency and relaxes the event loop signal) while still honouring the user's shortcuts.+ */+ protected createDefaultConcurrencySystem(options: ConcurrencySystemOptions): ConcurrencySystem {+ return new ConcurrencySystem(options);+ }+/*** Determines if the given HTTP status code is an error status code given* the default behaviour and user-set preferences.@@ -1407,8 +1486,20 @@ export class BasicCrawler<await this.addRequests(requests, addRequestsOptions);}- await this._init();- await this.stats.startCapturing();+ try {+ await this._init();+ await this.stats.startCapturing();+ } catch (error) {+ // Clean up here before propagating, otherwise a failed startup would leave the process hanging.+ await this.teardown().catch((teardownError) => {+ this.log.exception(teardownError as Error, 'Cleaning up after a failed crawler startup failed.');+ });++ // The run never began, so let the instance be run again instead of leaving it wedged as `running`.+ this.running = false;+ throw error;+ }+const periodicLogger = this.getPeriodicLogger();this.setStatusMessage('Starting the crawler.', { level: 'INFO' });@@ -1841,7 +1932,17 @@ export class BasicCrawler<this._ownsEventManager = true;}- this.autoscaledPool = new AutoscaledPool(this.autoscaledPoolOptions);+ // An owned governor is rebuilt (and started) for every run, so it always starts from a clean slate — stale+ // resource snapshots or a previous run's scaled desired concurrency would otherwise distort this run's+ // scaling. An injected one is long-lived and its lifecycle belongs to the caller.+ this.concurrencySystemDep = this.resolveConcurrencySystem();+ await this.concurrencySystemDep.ifOwned((system) => system.start());++ this.autoscaledPool = new AutoscaledPool({+ ...this.autoscaledPoolOptions,+ concurrencySystem: this.concurrencySystemDep.value,+ consumer: this.identity,+ });await this.getRequestManager();}@@ -2353,6 +2454,7 @@ export class BasicCrawler<}await this.autoscaledPool?.abort();+ await this.concurrencySystemDep?.ifOwned((system) => system.stop());}protected _getCookieHeaderFromRequest(request: Request) {diff --git a/packages/browser-crawler/README.md b/packages/browser-crawler/README.mdindex 904d7a553..03b632235 100644--- a/packages/browser-crawler/README.md+++ b/packages/browser-crawler/README.md@@ -13,6 +13,6 @@ The crawler finishes when there are no more [Request](https://crawlee.dev/js/api`BrowserCrawler` opens a new browser page (i.e. tab or window) for each [Request](https://crawlee.dev/js/api/core/class/Request) object to crawl and then calls the function provided by user as the [`requestHandler`](https://crawlee.dev/js/api/browser-crawler/interface/BrowserCrawlerOptions#requestHandler) option.New pages are only opened when there is enough free CPU and memory available, using the functionality provided by the [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) class.-All [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) configuration options can be passed to the [`autoscaledPoolOptions`](https://crawlee.dev/js/api/browser-crawler/interface/BrowserCrawlerOptions#autoscaledPoolOptions) parameter of the `BrowserCrawler` constructor. For user convenience, the [`minConcurrency`](https://crawlee.dev/js/api/core/interface/AutoscaledPoolOptions#minConcurrency) and [`maxConcurrency`](https://crawlee.dev/js/api/core/interface/AutoscaledPoolOptions#maxConcurrency) options of the underlying [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) constructor are available directly in the `BrowserCrawler` constructor.+Concurrency is tuned via the [`minConcurrency`](https://crawlee.dev/js/api/browser-crawler/interface/BrowserCrawlerOptions#minConcurrency), [`maxConcurrency`](https://crawlee.dev/js/api/browser-crawler/interface/BrowserCrawlerOptions#maxConcurrency) and [`maxRequestsPerMinute`](https://crawlee.dev/js/api/browser-crawler/interface/BrowserCrawlerOptions#maxRequestsPerMinute) options of the `BrowserCrawler` constructor, or, for finer control, by injecting a pre-configured [`concurrencySystem`](https://crawlee.dev/js/api/browser-crawler/interface/BrowserCrawlerOptions#concurrencySystem) — see `ConcurrencySystem`.> *NOTE:* the pool of browser instances is internally managed by the [BrowserPool](https://crawlee.dev/js/api/browser-pool/class/BrowserPool) class.diff --git a/packages/browser-crawler/src/internals/browser-crawler.ts b/packages/browser-crawler/src/internals/browser-crawler.tsindex 6d206340e..5e65013e3 100644--- a/packages/browser-crawler/src/internals/browser-crawler.ts+++ b/packages/browser-crawler/src/internals/browser-crawler.ts@@ -321,11 +321,9 @@ export interface BrowserCrawlerOptions<** New pages are only opened when there is enough free CPU and memory available,* using the functionality provided by the {@apilink AutoscaledPool} class.- * All {@apilink AutoscaledPool} configuration options can be passed to the {@apilink BrowserCrawlerOptions.autoscaledPoolOptions|`autoscaledPoolOptions`}- * parameter of the `BrowserCrawler` constructor.- * For user convenience, the {@apilink AutoscaledPoolOptions.minConcurrency|`minConcurrency`} and- * {@apilink AutoscaledPoolOptions.maxConcurrency|`maxConcurrency`} options of the- * underlying {@apilink AutoscaledPool} constructor are available directly in the `BrowserCrawler` constructor.+ * Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the+ * `BrowserCrawler` constructor, or, for finer control, by injecting a pre-configured+ * {@apilink ConcurrencySystem|`concurrencySystem`}.** > *NOTE:* the pool of browser instances is internally managed by the {@apilink BrowserPool} class.*diff --git a/packages/cheerio-crawler/README.md b/packages/cheerio-crawler/README.mdindex d98911284..ea62f7cbb 100644--- a/packages/cheerio-crawler/README.md+++ b/packages/cheerio-crawler/README.md@@ -24,7 +24,7 @@ preNavigationHooks: [By default, `CheerioCrawler` only processes web pages with the `text/html` and `application/xhtml+xml` MIME content types (as reported by the `Content-Type` HTTP header), and skips pages with other content types. If you want the crawler to process other content types, use the [CheerioCrawlerOptions.additionalMimeTypes](https://crawlee.dev/js/api/cheerio-crawler/interface/CheerioCrawlerOptions#additionalMimeTypes) constructor option. Beware that the parsing behavior differs for HTML, XML, JSON and other types of content. For more details, see [CheerioCrawlerOptions.requestHandler](https://crawlee.dev/js/api/cheerio-crawler/interface/CheerioCrawlerOptions#requestHandler).-New requests are only dispatched when there is enough free CPU and memory available, using the functionality provided by the [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) class. All [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) configuration options can be passed to the `autoscaledPoolOptions` parameter of the `CheerioCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency` [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) options are available directly in the `CheerioCrawler` constructor.+New requests are only dispatched when there is enough free CPU and memory available, using the functionality provided by the [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) class. Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the `CheerioCrawler` constructor, or, for finer control, by injecting a pre-configured `concurrencySystem` — see `ConcurrencySystem`.## Example usagediff --git a/packages/cheerio-crawler/src/internals/cheerio-crawler.ts b/packages/cheerio-crawler/src/internals/cheerio-crawler.tsindex 1f3febb97..e75fab875 100644--- a/packages/cheerio-crawler/src/internals/cheerio-crawler.ts+++ b/packages/cheerio-crawler/src/internals/cheerio-crawler.ts@@ -150,9 +150,9 @@ export type CheerioRequestHandler<** New requests are only dispatched when there is enough free CPU and memory available,* using the functionality provided by the {@apilink AutoscaledPool} class.- * All {@apilink AutoscaledPool} configuration options can be passed to the `autoscaledPoolOptions`- * parameter of the `CheerioCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency`- * {@apilink AutoscaledPool} options are available directly in the `CheerioCrawler` constructor.+ * Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the+ * `CheerioCrawler` constructor, or, for finer control, by injecting a pre-configured+ * {@apilink ConcurrencySystem|`concurrencySystem`}.** **Example usage:***diff --git a/packages/core/src/autoscaling/autoscaled_pool.ts b/packages/core/src/autoscaling/autoscaled_pool.tsindex 3acb0ca04..3bd842c6c 100644--- a/packages/core/src/autoscaling/autoscaled_pool.ts+++ b/packages/core/src/autoscaling/autoscaled_pool.ts@@ -4,22 +4,17 @@ import { addTimeoutToPromise } from '@apify/timeout';import type { BetterIntervalID } from '@apify/utilities';import { betterClearInterval, betterSetInterval } from '@apify/utilities';+import type { ConcurrencyConsumer, IConcurrencySystem } from './concurrency_system.js';import { CriticalError } from '../errors.js';import type { CrawleeLogger } from '../log.js';import { serviceLocator } from '../service_locator.js';-import type { LoadSignal } from './load_signal.js';-import type { SnapshotterOptions } from './snapshotter.js';-import { Snapshotter } from './snapshotter.js';-import type { SystemInfo, SystemStatusOptions } from './system_status.js';-import { SystemStatus } from './system_status.js';--export interface AutoscaledPoolOptions {- /**- * A function that performs an asynchronous resource-intensive task.- * The function must either be labeled `async` or return a promise.- */- runTaskFunction?: () => Promise<unknown>;+/**+ * The task-readiness predicates a consumer may supply to steer an {@apilink AutoscaledPool}'s run loop — the parts of+ * the loop a higher-level driver (e.g. a crawler) legitimately overrides, as opposed to the crawler-owned+ * `runTaskFunction`.+ */+export interface AutoscaledPoolPredicateOptions {/*** A function that indicates whether `runTaskFunction` should be called.* This function is called every time there is free capacity for a new task and it should@@ -36,48 +31,30 @@ export interface AutoscaledPoolOptions {* To abort a run, use the {@apilink AutoscaledPool.abort} method.*/isFinishedFunction?: () => Promise<boolean>;+}+export interface AutoscaledPoolOptions extends AutoscaledPoolPredicateOptions {/**- * The minimum number of tasks running in parallel.+ * The governor that decides whether there is free compute for one more task. Typically a+ * {@apilink ConcurrencySystem}, but any {@apilink IConcurrencySystem} works. Share a single instance across+ * multiple pools (and therefore multiple crawlers) to cap their *combined* concurrency against one budget.*- * *WARNING:* If you set this value too high with respect to the available system memory and CPU, your code might run extremely slow or crash.- * If you're not sure, just keep the default value and the concurrency will scale up automatically.- * @default 1- */- minConcurrency?: number;-- /**- * The maximum number of tasks running in parallel.- * @default 200- */- maxConcurrency?: number;-- /**- * The desired number of tasks that should be running parallel on the start of the pool,- * if there is a large enough supply of them.- * By default, it is `minConcurrency`.- */- desiredConcurrency?: number;-- /**- * Minimum level of desired concurrency to reach before more scaling up is allowed.- * @default 0.90+ * All concurrency/scaling/snapshotter configuration lives on the governor — the pool only owns the task loop and+ * its cadence.*/- desiredConcurrencyRatio?: number;+ concurrencySystem: IConcurrencySystem;/**- * Defines the fractional amount of desired concurrency to be added with each scaling up.- * The minimum scaling step is one.- * @default 0.05+ * Who this pool is, presented to the governor on every capacity query and booking so that a shared one can tell+ * several pools apart. Worth naming meaningfully — a governor that allocates per consumer reports this `id`.*/- scaleUpStepRatio?: number;+ consumer: ConcurrencyConsumer;/**- * Defines the amount of desired concurrency to be subtracted with each scaling down.- * The minimum scaling step is one.- * @default 0.05+ * A function that performs an asynchronous resource-intensive task.+ * The function must either be labeled `async` or return a promise.*/- scaleDownStepRatio?: number;+ runTaskFunction?: () => Promise<unknown>;/*** Indicates how often the pool should call the `runTaskFunction()` to start a new task, in seconds.@@ -86,69 +63,30 @@ export interface AutoscaledPoolOptions {*/maybeRunIntervalSecs?: number;- /**- * Specifies a period in which the instance logs its state, in seconds.- * Set to `null` to disable periodic logging.- * @default 60- */- loggingIntervalSecs?: number | null;-- /**- * Defines in seconds how often the pool should attempt to adjust the desired concurrency- * based on the latest system status. Setting it lower than 1 might have a severe impact on performance.- * We suggest using a value from 5 to 20.- * @default 10- */- autoscaleIntervalSecs?: number;-/*** Timeout in which the `runTaskFunction` needs to finish, given in seconds.* @default 0*/taskTimeoutSecs?: number;- /**- * Options to be passed down to the {@apilink Snapshotter} constructor. This is useful for fine-tuning- * the snapshot intervals and history.- */- snapshotterOptions?: SnapshotterOptions;-- /**- * Options to be passed down to the {@apilink SystemStatus} constructor. This is useful for fine-tuning- * the system status reports. If a custom snapshotter is set in the options, it will be used- * by the pool.- */- systemStatusOptions?: SystemStatusOptions;-- /**- * The maximum number of tasks per minute the pool can run.- * By default, this is set to `Infinity`, but you can pass any positive, non-zero integer.- */- maxTasksPerMinute?: number;-log?: CrawleeLogger;}/*** Manages a pool of asynchronous resource-intensive tasks that are executed in parallel.- * The pool only starts new tasks if there is enough free CPU and memory available- * and the Javascript event loop is not blocked.- *- * The information about the CPU and memory usage is obtained by the {@apilink Snapshotter} class,- * which makes regular snapshots of system resources that may be either local- * or from the Apify cloud infrastructure in case the process is running on the Apify platform.- * Meaningful data gathered from these snapshots is provided to `AutoscaledPool` by the {@apilink SystemStatus} class.+ * The pool only starts new tasks while its {@apilink IConcurrencySystem|concurrency system} reports free capacity —+ * that governor is what monitors CPU, memory and event loop load and autoscales the concurrency budget.** Before running the pool, you need to implement the following three functions:- * {@apilink AutoscaledPoolOptions.runTaskFunction},- * {@apilink AutoscaledPoolOptions.isTaskReadyFunction} and- * {@apilink AutoscaledPoolOptions.isFinishedFunction}.+ * {@apilink AutoscaledPoolOptions.runTaskFunction|`runTaskFunction`},+ * {@apilink AutoscaledPoolPredicateOptions.isTaskReadyFunction|`isTaskReadyFunction`} and+ * {@apilink AutoscaledPoolPredicateOptions.isFinishedFunction|`isFinishedFunction`}.** The auto-scaled pool is started by calling the {@apilink AutoscaledPool.run} function.- * The pool periodically queries the {@apilink AutoscaledPoolOptions.isTaskReadyFunction} function- * for more tasks, managing optimal concurrency, until the function resolves to `false`. The pool then queries- * the {@apilink AutoscaledPoolOptions.isFinishedFunction}. If it resolves to `true`, the run finishes after all running tasks complete.- * If it resolves to `false`, it assumes there will be more tasks available later and keeps periodically querying for tasks.+ * The pool periodically queries `isTaskReadyFunction` for more tasks, managing optimal concurrency, until the function+ * resolves to `false`. The pool then queries `isFinishedFunction`. If it resolves to `true`, the run finishes after all+ * running tasks complete. If it resolves to `false`, it assumes there will be more tasks available later and keeps+ * periodically querying for tasks.* If any of the tasks throws then the {@apilink AutoscaledPool.run} function rejects the promise with an error.** The pool evaluates whether it should start a new task every time one of the tasks finishes@@ -157,8 +95,12 @@ export interface AutoscaledPoolOptions {* **Example usage:**** ```javascript+ * const concurrencySystem = new ConcurrencySystem({ maxConcurrency: 50 });+ * await concurrencySystem.start();+ ** const pool = new AutoscaledPool({- * maxConcurrency: 50,+ * concurrencySystem,+ * consumer: { id: 'my-pool' },* runTaskFunction: async () => {* // Run some resource-intensive asynchronous operation here.* },@@ -173,7 +115,11 @@ export interface AutoscaledPoolOptions {* }* });*- * await pool.run();+ * try {+ * await pool.run();+ * } finally {+ * await concurrencySystem.stop();+ * }* ```* @category Scaling*/@@ -181,39 +127,28 @@ export class AutoscaledPool {private readonly log: CrawleeLogger;// Configurable properties.- private readonly desiredConcurrencyRatio: number;- private readonly scaleUpStepRatio: number;- private readonly scaleDownStepRatio: number;private readonly maybeRunIntervalMillis: number;- private readonly loggingIntervalMillis: number;- private readonly autoscaleIntervalMillis: number;private readonly taskTimeoutMillis: number;private readonly runTaskFunction: () => Promise<unknown>;private readonly isFinishedFunction: () => Promise<boolean>;private readonly isTaskReadyFunction: () => Promise<boolean>;- private readonly maxTasksPerMinute: number;++ private readonly concurrencySystem: IConcurrencySystem;+ private readonly consumer: ConcurrencyConsumer;// Internal properties.- private _minConcurrency: number;- private _maxConcurrency: number;- private _desiredConcurrency: number;- private _currentConcurrency = 0;private isStopped = false;- private lastLoggingTime?: number;private resolve: ((val?: unknown) => void) | null = null;private reject: ((reason?: unknown) => void) | null = null;- private snapshotter: Snapshotter;-- /** Additional SystemStatus loadSignals - tracked here for initialization and cleanup */- private loadSignals: LoadSignal[];-- private systemStatus: SystemStatus;- private autoscaleInterval!: BetterIntervalID;private maybeRunInterval!: BetterIntervalID;private queryingIsTaskReady!: boolean;private queryingIsFinished!: boolean;- private tasksDonePerSecondInterval?: BetterIntervalID;- private _tasksPerMinute: number[] = Array.from({ length: 60 }, () => 0);++ /**+ * This pool's *own* in-flight task count, as opposed to {@apilink AutoscaledPool.currentConcurrency}, which is the+ * (possibly shared) governor's total. `pause()` and `maybeFinish()` care only about this pool draining.+ */+ private ownConcurrency = 0;constructor(options: AutoscaledPoolOptions) {ow(@@ -222,20 +157,11 @@ export class AutoscaledPool {runTaskFunction: ow.function,isFinishedFunction: ow.function,isTaskReadyFunction: ow.function,- maxConcurrency: ow.optional.number.integer.greaterThanOrEqual(1),- minConcurrency: ow.optional.number.integer.greaterThanOrEqual(1),- desiredConcurrency: ow.optional.number.integer.greaterThanOrEqual(1),- desiredConcurrencyRatio: ow.optional.number.greaterThan(0).lessThan(1),- scaleUpStepRatio: ow.optional.number.greaterThan(0).lessThan(1),- scaleDownStepRatio: ow.optional.number.greaterThan(0).lessThan(1),maybeRunIntervalSecs: ow.optional.number.greaterThan(0),- loggingIntervalSecs: ow.any(ow.number.greaterThan(0), ow.nullOrUndefined),- autoscaleIntervalSecs: ow.optional.number.greaterThan(0),taskTimeoutSecs: ow.optional.number.greaterThanOrEqual(0),- systemStatusOptions: ow.optional.object,- snapshotterOptions: ow.optional.object,log: ow.optional.object,- maxTasksPerMinute: ow.optional.number.integerOrInfinite.greaterThanOrEqual(1),+ concurrencySystem: ow.object,+ consumer: ow.object.partialShape({ id: ow.string.nonEmpty }),}),);@@ -243,143 +169,85 @@ export class AutoscaledPool {runTaskFunction,isFinishedFunction,isTaskReadyFunction,- maxConcurrency = 200,- minConcurrency = 1,- desiredConcurrency,- desiredConcurrencyRatio = 0.9,- scaleUpStepRatio = 0.05,- scaleDownStepRatio = 0.05,maybeRunIntervalSecs = 0.5,- loggingIntervalSecs = 60,taskTimeoutSecs = 0,- autoscaleIntervalSecs = 10,- systemStatusOptions,- snapshotterOptions,log = serviceLocator.getLogger(),- maxTasksPerMinute = Infinity,+ concurrencySystem,+ consumer,} = options;this.log = log.child({ prefix: 'AutoscaledPool' });// Configurable properties.- this.desiredConcurrencyRatio = desiredConcurrencyRatio;- this.scaleUpStepRatio = scaleUpStepRatio;- this.scaleDownStepRatio = scaleDownStepRatio;this.maybeRunIntervalMillis = maybeRunIntervalSecs * 1000;- this.loggingIntervalMillis = loggingIntervalSecs! * 1000;- this.autoscaleIntervalMillis = autoscaleIntervalSecs * 1000;this.taskTimeoutMillis = taskTimeoutSecs * 1000;this.runTaskFunction = runTaskFunction;this.isFinishedFunction = isFinishedFunction;this.isTaskReadyFunction = isTaskReadyFunction;- this.maxTasksPerMinute = maxTasksPerMinute;++ this.concurrencySystem = concurrencySystem;+ this.consumer = consumer;// Internal properties.- this._minConcurrency = minConcurrency;- this._maxConcurrency = maxConcurrency;- this._desiredConcurrency = Math.min(desiredConcurrency ?? minConcurrency, maxConcurrency);- this._currentConcurrency = 0;this.isStopped = false;this.resolve = null;this.reject = null;- this.autoscale = this.autoscale.bind(this);this.maybeRunTask = this.maybeRunTask.bind(this);- this.incrementTasksDonePerSecond = this.incrementTasksDonePerSecond.bind(this);-- // Create instances with correct options.- const ssoCopy = { ...systemStatusOptions };- ssoCopy.snapshotter ??= new Snapshotter({- ...snapshotterOptions,- log: this.log,- });- this.snapshotter = ssoCopy.snapshotter;- this.loadSignals = ssoCopy.loadSignals ?? [];- this.systemStatus = new SystemStatus(ssoCopy);}/**- * Gets the minimum number of tasks running in parallel.- */- get minConcurrency(): number {- return this._minConcurrency;- }-- /**- * Sets the minimum number of tasks running in parallel.+ * The governor backing this pool, as supplied to the constructor — exposed as the read-only+ * {@apilink IConcurrencySystem} contract.*- * *WARNING:* If you set this value too high with respect to the available system memory and CPU, your code might run extremely slow or crash.- * If you're not sure, just keep the default value and the concurrency will scale up automatically.- */- set minConcurrency(value: number) {- ow(value, ow.optional.number.integer.greaterThanOrEqual(1));- this._minConcurrency = value;- }-- /**- * Gets the maximum number of tasks running in parallel.+ * This and the two getters below are telemetry only: concurrency is configured and tuned on the concrete+ * {@apilink ConcurrencySystem} its owner holds, never through the pool.*/- get maxConcurrency(): number {- return this._maxConcurrency;+ get system(): IConcurrencySystem {+ return this.concurrencySystem;}- /**- * Sets the maximum number of tasks running in parallel.- */- set maxConcurrency(value: number) {- ow(value, ow.optional.number.integer.greaterThanOrEqual(1));- this._maxConcurrency = value;- }-- /**- * Gets the desired concurrency for the pool,- * which is an estimated number of parallel tasks that the system can currently support.- */+ /** The estimated number of parallel tasks the governor can currently support. */get desiredConcurrency(): number {- return this._desiredConcurrency;- }-- /**- * Sets the desired concurrency for the pool, i.e. the number of tasks that should be running- * in parallel if there's large enough supply of tasks.- */- set desiredConcurrency(value: number) {- ow(value, ow.optional.number.integer.greaterThanOrEqual(1));- this._desiredConcurrency = value;+ return this.concurrencySystem.desiredConcurrency;}/**- * Gets the number of parallel tasks currently running in the pool.+ * The number of parallel tasks currently booked against the governor. When it is shared, this counts every+ * borrowing pool's tasks, not just this one's.*/get currentConcurrency(): number {- return this._currentConcurrency;+ return this.concurrencySystem.currentConcurrency;}/*** Runs the auto-scaled pool. Returns a promise that gets resolved or rejected once* all the tasks are finished or one of them fails.+ *+ * Throws if the {@apilink IConcurrencySystem|concurrency system} it borrows was never started — the pool assumes+ * a running governor and cannot start one it does not own.*/async run(): Promise<void> {+ // Checked here, on an awaited path — the capacity queries inside the task loop run from intervals and+ // `setImmediate`, where a throw would become an unhandled rejection and hang `run()` forever.+ if (!this.concurrencySystem.isRunning) {+ throw new CriticalError(+ 'The ConcurrencySystem this AutoscaledPool borrows has not been started, so system load would not be ' ++ 'monitored and the concurrency would never be adjusted. Whoever creates a ConcurrencySystem owns ' ++ 'its lifecycle: call `await concurrencySystem.start()` before running the pools or crawlers that ' ++ 'use it, and `await concurrencySystem.stop()` once they are all done.',+ );+ }+const poolPromise = new Promise((resolve, reject) => {this.resolve = resolve;this.reject = reject;});- await this.snapshotter.start();- await Promise.all(this.loadSignals.map((s) => s.start()));-- // This interval checks the system status and updates the desired concurrency accordingly.- this.autoscaleInterval = betterSetInterval(this.autoscale, this.autoscaleIntervalMillis);-// This is here because if we scale down to let's say 1, then after each promise is finished// this.maybeRunTask() doesn't trigger another one. So if that 1 instance gets stuck it results// in the crawler getting stuck and even after scaling up it never triggers another promise.this.maybeRunInterval = betterSetInterval(this.maybeRunTask, this.maybeRunIntervalMillis);- if (this.maxTasksPerMinute !== Infinity) {- // Start the interval that resets the counter of tasks per minute.- this.tasksDonePerSecondInterval = betterSetInterval(this.incrementTasksDonePerSecond, 1000);- }-try {await poolPromise;} finally {@@ -417,6 +285,10 @@ export class AutoscaledPool {** The promise returned from the {@apilink AutoscaledPool.run} function will not resolve* when `.pause()` is invoked (unlike abort, which resolves it).+ *+ * > *NOTE:* Pausing the pool does not suspend the (possibly shared) {@apilink ConcurrencySystem} — its+ * autoscaling and resource monitoring keep running, since other pools borrowing it may still be active. To silence+ * it during a long pause, its owner can `stop()` and `start()` it again.*/async pause(timeoutSecs?: number): Promise<void> {if (this.isStopped) return;@@ -437,7 +309,7 @@ export class AutoscaledPool {}interval = setInterval(() => {- if (this._currentConcurrency <= 0) {+ if (this.ownConcurrency <= 0) {// Clean up timeout and interval to prevent process hanging.if (timeout) clearTimeout(timeout);clearInterval(interval);@@ -489,20 +361,14 @@ export class AutoscaledPool {this.log.perf('Task will not run. Waiting for a ready task.');return done();}- // - we would exceed desired concurrency.- if (this._currentConcurrency >= this._desiredConcurrency) {- this.log.perf('Task will not run. Desired concurrency achieved.');- return done();- }- // - system is overloaded now and we are at or above minConcurrency- const currentStatus = this.systemStatus.getCurrentStatus();- const { isSystemIdle } = currentStatus;- if (!isSystemIdle && this._currentConcurrency >= this._minConcurrency) {- this.log.perf(- 'Task will not be run. System is overloaded.',- currentStatus as unknown as Record<string, unknown>,- );- return done();+ // - the budget has room for us.+ if (!this.concurrencySystem.hasCapacityForTask(this.consumer)) {+ done();+ // A shared governor's budget can stay saturated by another pool indefinitely, so we still have to be able+ // to notice that *this* pool has run out of work — `maybeFinish()` is the only thing that ever resolves+ // `run()`. It no-ops while this pool has tasks of its own in flight, which is every case in which an+ // unshared governor reports no capacity.+ return this.maybeFinish();}// - a task is ready.this.queryingIsTaskReady = true;@@ -529,18 +395,16 @@ export class AutoscaledPool {return this.maybeFinish();}- // - we have already reached the maximum tasks per minute- // we need to check this *after* checking if a task is ready to prevent hanging the pool- // for an extra minute if there are no more tasks- if (this.isOverMaxRequestLimit) {- this.log.perf('Task will not run. Maximum tasks per minute reached.');+ // - the budget still has room. Re-checked atomically, because another pool sharing the governor may have taken+ // the last free slot while we awaited `isTaskReadyFunction` above.+ if (!this.concurrencySystem.tryRegisterTaskStart(this.consumer)) {return done();}+ this.ownConcurrency++;+try {// Everything's fine. Run task.- this._currentConcurrency++;- this._tasksPerMinute[0]++;// Try to run next task to build up concurrency,// but defer it so it doesn't create a cycle.setImmediate(this.maybeRunTask);@@ -562,8 +426,8 @@ export class AutoscaledPool {}this.log.perf('Task finished.');- this._currentConcurrency--;- // Run task after the previous one finished.+ // Run task after the previous one finished. Only on success: a failed task rejects the pool, and+ // nudging the loop afterwards could start work on an already destroyed pool.setImmediate(this.maybeRunTask);} catch (e) {const err = e as Error;@@ -579,95 +443,14 @@ export class AutoscaledPool {}this.reject(err);}+ } finally {+ this.concurrencySystem.registerTaskEnd(this.consumer);+ this.ownConcurrency--;}return undefined;}- /**- * Gets called every autoScaleIntervalSecs and evaluates the current system status.- * If the system IS NOT overloaded and the settings allow it, it scales up.- * If the system IS overloaded and the settings allow it, it scales down.- */- private autoscale(intervalCallback: () => void) {- // Don't scale if paused.- if (this.isStopped) return intervalCallback();-- // Don't scale if we've hit the maximum requests per minute- if (this.isOverMaxRequestLimit) return intervalCallback();-- // Only scale up if:- // - system has not been overloaded lately.- const systemStatus = this.systemStatus.getHistoricalStatus();- const { isSystemIdle } = systemStatus;- // - we're not already at max concurrency.- const weAreNotAtMax = this._desiredConcurrency < this._maxConcurrency;- // - current concurrency reaches at least the given ratio of desired concurrency.- const minCurrentConcurrency = Math.floor(this._desiredConcurrency * this.desiredConcurrencyRatio);- const weAreReachingDesiredConcurrency = this._currentConcurrency >= minCurrentConcurrency;-- if (isSystemIdle && weAreNotAtMax && weAreReachingDesiredConcurrency) this.scaleUp(systemStatus);-- // Always scale down if:- // - the system has been overloaded lately.- const isSystemOverloaded = !isSystemIdle;- // - we're over min concurrency.- const weAreNotAtMin = this._desiredConcurrency > this._minConcurrency;-- if (isSystemOverloaded && weAreNotAtMin) this.scaleDown(systemStatus);-- // On periodic intervals, print comprehensive log information- if (this.loggingIntervalMillis > 0) {- const now = Date.now();-- if (this.lastLoggingTime == null) {- this.lastLoggingTime = now;- } else if (now > this.lastLoggingTime + this.loggingIntervalMillis) {- this.lastLoggingTime = now;- this.log.info('state', {- currentConcurrency: this._currentConcurrency,- desiredConcurrency: this._desiredConcurrency,- systemStatus,- });- }- }-- // Start a new interval cycle.- return intervalCallback();- }-- /**- * Scales the pool up by increasing- * the desired concurrency by the scaleUpStepRatio.- *- * @param systemStatus for logging- */- private scaleUp(systemStatus: SystemInfo): void {- const step = Math.ceil(this._desiredConcurrency * this.scaleUpStepRatio);- this._desiredConcurrency = Math.min(this._maxConcurrency, this._desiredConcurrency + step);- this.log.debug('scaling up', {- oldConcurrency: this._desiredConcurrency - step,- newConcurrency: this._desiredConcurrency,- systemStatus,- });- }-- /**- * Scales the pool down by decreasing- * the desired concurrency by the scaleDownStepRatio.- *- * @param systemStatus for logging- */- private scaleDown(systemStatus: SystemInfo): void {- const step = Math.ceil(this._desiredConcurrency * this.scaleDownStepRatio);- this._desiredConcurrency = Math.max(this._minConcurrency, this._desiredConcurrency - step);- this.log.debug('scaling down', {- oldConcurrency: this._desiredConcurrency + step,- newConcurrency: this._desiredConcurrency,- systemStatus,- });- }-/*** If there are no running tasks and this.isFinishedFunction() returns true then closes* the pool and resolves the pool's promise returned by the run() method.@@ -676,7 +459,7 @@ export class AutoscaledPool {*/private async maybeFinish(): Promise<void> {if (this.queryingIsFinished) return;- if (this._currentConcurrency > 0) return;+ if (this.ownConcurrency > 0) return;this.queryingIsFinished = true;try {@@ -701,26 +484,6 @@ export class AutoscaledPool {this.resolve = null;this.reject = null;- betterClearInterval(this.autoscaleInterval);betterClearInterval(this.maybeRunInterval);- if (this.tasksDonePerSecondInterval) betterClearInterval(this.tasksDonePerSecondInterval);- if (this.snapshotter) await this.snapshotter.stop();- await Promise.all(this.loadSignals.map((s) => s.stop()));- }-- private incrementTasksDonePerSecond(intervalCallback: () => void) {- this._tasksPerMinute.unshift(0);-- this._tasksPerMinute.pop();-- return intervalCallback();- }-- private get isOverMaxRequestLimit() {- if (this.maxTasksPerMinute === Infinity) {- return false;- }-- return this._tasksPerMinute.reduce((acc, curr) => acc + curr, 0) >= this.maxTasksPerMinute;}}diff --git a/packages/core/src/autoscaling/client_load_signal.ts b/packages/core/src/autoscaling/client_load_signal.tsindex d5d92f0a5..1dd21c5d9 100644--- a/packages/core/src/autoscaling/client_load_signal.ts+++ b/packages/core/src/autoscaling/client_load_signal.ts@@ -1,60 +1,122 @@import type { StorageBackend } from '@crawlee/types';-import type { LoadSnapshot } from './load_signal.js';+import type { BetterIntervalID } from '@apify/utilities';+import { betterClearInterval, betterSetInterval } from '@apify/utilities';++import { serviceLocator } from '../service_locator.js';+import type { LoadSignal, LoadSignalStartContext, LoadSnapshot } from './load_signal.js';import { SnapshotStore } from './load_signal.js';const CLIENT_RATE_LIMIT_ERROR_RETRY_COUNT = 2;+/**+ * A snapshot produced by the built-in client (rate-limit) signal.+ * @internal+ */export interface ClientSnapshot extends LoadSnapshot {rateLimitErrorCount: number;}+/**+ * Tuning for the built-in **client** (rate-limit) load signal, as accepted both by {@apilink ClientLoadSignal} and by+ * the {@apilink LoadSignalsOptions.client|`client`} shorthand on {@apilink LoadSignalsOptions}.+ */export interface ClientLoadSignalOptions {- client: StorageBackend;- clientSnapshotIntervalSecs?: number;- maxClientErrors?: number;+ /**+ * Defines the interval of checking the current state of the remote API client, in seconds.+ * @default 1+ */+ snapshotIntervalSecs?: number;++ /**+ * Defines the maximum number of new rate limit errors within the given interval.+ * @default 3+ */+ maxErrors?: number;++ /**+ * Maximum ratio of overloaded snapshots in a sample before the client counts as overloaded.+ * @default 0.3+ */overloadedRatio?: number;- snapshotHistoryMillis?: number;}/**- * Periodically checks the storage client for rate-limit errors (HTTP 429)- * and reports overload when the error delta exceeds a threshold.+ * Periodically checks the storage backend for rate-limit errors (HTTP 429) and reports overload when the error delta+ * exceeds a threshold.+ *+ * Built by default; construct one yourself only to wrap or adapt it — see {@apilink LoadSignal}.+ *+ * Switch it off entirely ({@apilink LoadSignalsOptions.client|`client: false`}) if the storage backend reports no+ * rate-limit statistics, since it otherwise polls it every second to no purpose.+ *+ * @category Scaling*/-export function createClientLoadSignal(options: ClientLoadSignalOptions) {- const maxClientErrors = options.maxClientErrors ?? 3;-- const signal = SnapshotStore.fromInterval<ClientSnapshot>({- name: 'clientInfo',- overloadedRatio: options.overloadedRatio ?? 0.3,- intervalMillis: (options.clientSnapshotIntervalSecs ?? 1) * 1000,- snapshotHistoryMillis: options.snapshotHistoryMillis,- handler(store, intervalCallback) {- const now = new Date();-- const allErrorCounts = options.client.stats?.rateLimitErrors ?? [];- const currentErrCount = allErrorCounts[CLIENT_RATE_LIMIT_ERROR_RETRY_COUNT] || 0;-- const snapshot: ClientSnapshot = {- createdAt: now,- isOverloaded: false,- rateLimitErrorCount: currentErrCount,- };- const all = store.getAll();- const previousSnapshot = all[all.length - 1];- if (previousSnapshot) {- const { rateLimitErrorCount } = previousSnapshot;- const delta = currentErrCount - rateLimitErrorCount;- if (delta > maxClientErrors) snapshot.isOverloaded = true;- }-- store.push(snapshot, now);- intervalCallback();- },- });-- return signal;-}+export class ClientLoadSignal implements LoadSignal {+ readonly name = 'clientInfo';+ readonly overloadedRatio: number;++ private readonly store = new SnapshotStore<ClientSnapshot>();+ private readonly intervalMillis: number;+ private readonly maxErrors: number;+ private interval?: BetterIntervalID;+ private client?: StorageBackend;++ constructor(options: ClientLoadSignalOptions = {}) {+ this.overloadedRatio = options.overloadedRatio ?? 0.3;+ this.intervalMillis = (options.snapshotIntervalSecs ?? 1) * 1000;+ this.maxErrors = options.maxErrors ?? 3;+ this.handle = this.handle.bind(this);+ }-/** @internal Return type for backward compat in Snapshotter facade */-export type ClientLoadSignal = ReturnType<typeof createClientLoadSignal>;+ async start(context: LoadSignalStartContext): Promise<void> {+ this.store.useSampleWindow(context.maxSampleWindowMillis);+ // A new session starts from a clean slate, or its first measurement diffs the error count against the previous+ // session's — possibly against a different backend, since the client is resolved afresh just below.+ this.store.clear();++ // Resolved here rather than in the constructor, where asking for the backend would instantiate a default one+ // as a side effect - long before the crawler that owns the run has had a chance to register its own.+ this.client = serviceLocator.getStorageBackend();+ this.interval = betterSetInterval(this.handle, this.intervalMillis);+ }++ async stop(): Promise<void> {+ if (this.interval) betterClearInterval(this.interval);+ this.interval = undefined;+ this.client = undefined;+ }++ getSample(sampleDurationMillis?: number): LoadSnapshot[] {+ return this.store.getSample(sampleDurationMillis);+ }++ /**+ * Records one snapshot, overloaded when rate-limit errors grew by more than the configured limit since the+ * previous one.+ * @internal Also lets tests drive the measurement without waiting on a timer.+ */+ handle(intervalCallback: () => unknown): void {+ const now = new Date();++ const allErrorCounts = this.client?.stats?.rateLimitErrors ?? [];+ const currentErrCount = allErrorCounts[CLIENT_RATE_LIMIT_ERROR_RETRY_COUNT] || 0;++ const snapshot: ClientSnapshot = {+ createdAt: now,+ isOverloaded: false,+ rateLimitErrorCount: currentErrCount,+ };++ const all = this.store.getAll();+ const previousSnapshot = all[all.length - 1];++ if (previousSnapshot) {+ const delta = currentErrCount - previousSnapshot.rateLimitErrorCount;+ if (delta > this.maxErrors) snapshot.isOverloaded = true;+ }++ this.store.push(snapshot, now);+ intervalCallback();+ }+}diff --git a/packages/core/src/autoscaling/concurrency_system.ts b/packages/core/src/autoscaling/concurrency_system.tsnew file mode 100644index 000000000..0dd676a5c--- /dev/null+++ b/packages/core/src/autoscaling/concurrency_system.ts@@ -0,0 +1,590 @@+import ow from 'ow';++import type { BetterIntervalID } from '@apify/utilities';+import { betterClearInterval, betterSetInterval } from '@apify/utilities';++import type { CrawleeLogger } from '../log.js';+import { serviceLocator } from '../service_locator.js';+import type { LoadSignal } from './load_signal.js';+import { Snapshotter } from './snapshotter.js';+import type { LoadSignalsOptions } from './snapshotter.js';+import type { SystemInfo } from './system_status.js';+import { SystemStatus } from './system_status.js';++export interface ConcurrencySystemOptions {+ /**+ * The minimum number of tasks running in parallel.+ *+ * *WARNING:* If you set this value too high with respect to the available system memory and CPU, your code might run extremely slow or crash.+ * If you're not sure, just keep the default value and the concurrency will scale up automatically.+ * @default 1+ */+ minConcurrency?: number;++ /**+ * The maximum number of tasks running in parallel.+ * @default 200+ */+ maxConcurrency?: number;++ /**+ * The desired number of tasks that should be running parallel on the start of the pool,+ * if there is a large enough supply of them.+ * By default, it is `minConcurrency`.+ */+ desiredConcurrency?: number;++ /**+ * Minimum level of desired concurrency to reach before more scaling up is allowed.+ * @default 0.90+ */+ desiredConcurrencyRatio?: number;++ /**+ * Defines the fractional amount of desired concurrency to be added with each scaling up.+ * The minimum scaling step is one.+ * @default 0.05+ */+ scaleUpStepRatio?: number;++ /**+ * Defines the amount of desired concurrency to be subtracted with each scaling down.+ * The minimum scaling step is one.+ * @default 0.05+ */+ scaleDownStepRatio?: number;++ /**+ * Specifies a period in which the instance logs its state, in seconds.+ * Set to `null` to disable periodic logging.+ * @default 60+ */+ loggingIntervalSecs?: number | null;++ /**+ * Defines in seconds how often the system should attempt to adjust the desired concurrency+ * based on the latest system status. Setting it lower than 1 might have a severe impact on performance.+ * We suggest using a value from 5 to 20.+ * @default 10+ */+ autoscaleIntervalSecs?: number;++ /**+ * The signals that tell the system whether the machine is overloaded: per-resource tuning for the built-in four+ * (memory, event loop, CPU, client) plus any {@apilink LoadSignalsOptions.custom|`custom`} implementations of+ * your own. See {@apilink LoadSignalsOptions}.+ */+ loadSignals?: LoadSignalsOptions;++ /**+ * How far back the **autoscaling** decisions look, in seconds — the window the historical system status is+ * evaluated over, and therefore how much history the signals retain (the memory cost of raising it).+ * @default 30+ */+ snapshotHistorySecs?: number;++ /**+ * How far back the **task-gating** decision looks, in seconds — the window used to judge whether the system is+ * overloaded *right now*, before dispatching one more task. Deliberately shorter than+ * {@apilink ConcurrencySystemOptions.snapshotHistorySecs|`snapshotHistorySecs`}, so that dispatch reacts to+ * spikes quickly while scaling stays stable.+ * @default 5+ */+ currentHistorySecs?: number;++ /**+ * The maximum number of tasks per minute the system can run.+ * By default, this is set to `Infinity`, but you can pass any positive, non-zero integer.+ */+ maxTasksPerMinute?: number;++ log?: CrawleeLogger;+}++/**+ * Identifies *who* is asking a governor for capacity: one {@apilink AutoscaledPool}, or the crawler driving it. The+ * same object is passed on every call a pool makes, so per-consumer state can be keyed off it or off its `id`.+ * @category Scaling+ */+export interface ConcurrencyConsumer {+ /** Process-unique and human-readable — a crawler's is its {@apilink BasicCrawlerOptions.id|`id`} option. */+ readonly id: string;+}++/**+ * The contract between an {@apilink AutoscaledPool} and its concurrency "governor" — the object that answers *is+ * there free compute for one more task?* and tracks the budget that tasks are booked against.+ * {@apilink ConcurrencySystem} is the canonical implementation; the interface lets alternate governors be substituted+ * without depending on its internals.+ *+ * Every allocation method is told which {@apilink ConcurrencyConsumer|consumer} is asking, so an implementation can+ * allocate per consumer. {@apilink ConcurrencySystem} does not: it serves whoever asks first, which can starve a pool+ * that joins a saturated system late.+ * @category Scaling+ */+export interface IConcurrencySystem {+ /**+ * The number of tasks that should currently be running in parallel, assuming a sufficient supply of them. How it+ * is derived is up to the implementation, hence read-only here — but it must always be at least `1`, or a pool+ * could never start the first task.+ */+ readonly desiredConcurrency: number;++ /** The number of parallel tasks currently booked against this governor, regardless of which pool booked them. */+ readonly currentConcurrency: number;++ /**+ * Whether the governor is ready to be booked against. {@apilink AutoscaledPool.run|`pool.run()`} refuses to run+ * when this is `false`. An implementation with no startup lifecycle simply reports `true`.+ */+ readonly isRunning: boolean;++ /**+ * May **one more** task start right now, on behalf of `consumer`? A cheap pre-check the pool consults before+ * querying task readiness.+ *+ * Must **not** enforce rate limits that only make sense for ready tasks (e.g. a per-minute task cap): the pool+ * calls this before knowing whether any task is ready, so refusing here would stall an already-empty queue.+ *+ * Must also return `true` whenever `consumer` has nothing in flight of its own. A `false` sends that pool straight+ * to its finished-check **without** consulting `isTaskReadyFunction`, so a governor that starves an idle pool can+ * make its `run()` resolve while work is still pending. Tracking bookings per consumer answers that directly;+ * {@apilink ConcurrencySystem}, which does not, instead never refuses while+ * {@apilink IConcurrencySystem.currentConcurrency|`currentConcurrency`} is `0`.+ */+ hasCapacityForTask(consumer: ConcurrencyConsumer): boolean;++ /**+ * Books a task against the budget for `consumer`, returning `false` (without booking) when there is no room — the+ * budget is spent, the consumer is over its share, or an implementation-specific rate limit was reached.+ *+ * Must be an *atomic* (synchronous) check-and-book: several pools may share one governor, and a check separated+ * from the booking by an `await` lets two of them claim the last free slot at once.+ */+ tryRegisterTaskStart(consumer: ConcurrencyConsumer): boolean;++ /** Returns a task's slot to `consumer`'s budget. Called once the task settles (resolve or reject). */+ registerTaskEnd(consumer: ConcurrencyConsumer): void;+}++/**+ * The shareable "governor" behind an {@apilink AutoscaledPool}: it decides whether there is free compute for one more+ * task by combining live system load (via an internal {@apilink Snapshotter}) with a concurrency budget it autoscales+ * over time.+ *+ * Sharing one instance between several pools (and therefore several crawlers) caps their *combined* compute, instead+ * of letting each scale independently and oversubscribe the machine.+ *+ * Whoever builds the instance owns its lifecycle: call {@apilink ConcurrencySystem.start|`start()`} before any+ * borrowing pool runs and {@apilink ConcurrencySystem.stop|`stop()`} once they are all done (crawlers do this for the+ * default system they build, never for an injected one). Both calls are idempotent, and the first `stop()` tears the+ * system down for every borrower.+ * @category Scaling+ */+export class ConcurrencySystem implements IConcurrencySystem {+ private readonly log: CrawleeLogger;++ private readonly desiredConcurrencyRatio: number;+ private readonly scaleUpStepRatio: number;+ private readonly scaleDownStepRatio: number;+ private readonly loggingIntervalMillis: number;+ private readonly autoscaleIntervalMillis: number;+ private readonly maxTasksPerMinute: number;++ private _minConcurrency: number;+ private _maxConcurrency: number;+ private _desiredConcurrency: number;+ private _currentConcurrency = 0;+ private lastLoggingTime?: number;+ private _tasksPerMinute: number[] = Array.from({ length: 60 }, () => 0);++ private readonly snapshotter: Snapshotter;+ private readonly loadSignals: LoadSignal[];+ private readonly systemStatus: SystemStatus;++ private autoscaleInterval?: BetterIntervalID;+ private tasksDonePerSecondInterval?: BetterIntervalID;++ /** Whether the snapshotter and autoscaling intervals are currently running. */+ private running = false;++ /** The in-flight (or completed) startup, memoized so concurrent `start()` calls await one boot. */+ private startPromise?: Promise<void>;++ /** Set once per session, so a pool outliving `stop()` is reported once rather than every half second. */+ private warnedAboutQueryWhileStopped = false;++ constructor(options: ConcurrencySystemOptions = {}) {+ ow(+ options,+ ow.object.exactShape({+ maxConcurrency: ow.optional.number.integer.greaterThanOrEqual(1),+ minConcurrency: ow.optional.number.integer.greaterThanOrEqual(1),+ desiredConcurrency: ow.optional.number.integer.greaterThanOrEqual(1),+ desiredConcurrencyRatio: ow.optional.number.greaterThan(0).lessThan(1),+ scaleUpStepRatio: ow.optional.number.greaterThan(0).lessThan(1),+ scaleDownStepRatio: ow.optional.number.greaterThan(0).lessThan(1),+ loggingIntervalSecs: ow.any(ow.number.greaterThan(0), ow.nullOrUndefined),+ autoscaleIntervalSecs: ow.optional.number.greaterThan(0),+ loadSignals: ow.optional.object,+ snapshotHistorySecs: ow.optional.number.greaterThan(0),+ currentHistorySecs: ow.optional.number.greaterThan(0),+ log: ow.optional.object,+ maxTasksPerMinute: ow.optional.number.integerOrInfinite.greaterThanOrEqual(1),+ }),+ );++ const {+ maxConcurrency = 200,+ minConcurrency = 1,+ desiredConcurrency,+ desiredConcurrencyRatio = 0.9,+ scaleUpStepRatio = 0.05,+ scaleDownStepRatio = 0.05,+ loggingIntervalSecs = 60,+ autoscaleIntervalSecs = 10,+ loadSignals = {},+ snapshotHistorySecs,+ currentHistorySecs,+ log = serviceLocator.getLogger(),+ maxTasksPerMinute = Infinity,+ } = options;++ this.log = log.child({ prefix: 'ConcurrencySystem' });++ this.desiredConcurrencyRatio = desiredConcurrencyRatio;+ this.scaleUpStepRatio = scaleUpStepRatio;+ this.scaleDownStepRatio = scaleDownStepRatio;+ this.loggingIntervalMillis = (loggingIntervalSecs ?? 0) * 1000;+ this.autoscaleIntervalMillis = autoscaleIntervalSecs * 1000;+ this.maxTasksPerMinute = maxTasksPerMinute;++ this._minConcurrency = minConcurrency;+ this._maxConcurrency = maxConcurrency;+ this._desiredConcurrency = desiredConcurrency ?? minConcurrency;+ this.clampDesiredConcurrency();++ this._autoscale = this._autoscale.bind(this);+ this._incrementTasksDonePerSecond = this._incrementTasksDonePerSecond.bind(this);++ // The built-in signals are collected by the snapshotter; custom ones are simply evaluated alongside them.+ const { custom: customLoadSignals = [], ...builtinSignalOptions } = loadSignals;++ this.snapshotter = new Snapshotter(builtinSignalOptions);+ this.loadSignals = customLoadSignals;+ this.systemStatus = new SystemStatus({+ snapshotter: this.snapshotter,+ loadSignals: customLoadSignals,+ currentHistorySecs,+ // Both windows are requested from the signals explicitly, so a signal's own retention can neither widen+ // nor (given the start context below) narrow what it contributes.+ historySecs: snapshotHistorySecs,+ });+ }++ /**+ * Gets the minimum number of tasks running in parallel.+ */+ get minConcurrency(): number {+ return this._minConcurrency;+ }++ /**+ * Sets the minimum number of tasks running in parallel.+ *+ * *WARNING:* If you set this value too high with respect to the available system memory and CPU, your code might run extremely slow or crash.+ * If you're not sure, just keep the default value and the concurrency will scale up automatically.+ */+ set minConcurrency(value: number) {+ ow(value, ow.optional.number.integer.greaterThanOrEqual(1));+ this._minConcurrency = value;+ this.clampDesiredConcurrency();+ }++ /**+ * Gets the maximum number of tasks running in parallel.+ */+ get maxConcurrency(): number {+ return this._maxConcurrency;+ }++ /**+ * Sets the maximum number of tasks running in parallel. Lowering it below the current+ * {@apilink ConcurrencySystem.desiredConcurrency|`desiredConcurrency`} pulls that down to the new ceiling too, so+ * the change takes effect immediately (in-flight tasks are never cancelled — the budget simply drains to the new+ * limit as they settle).+ */+ set maxConcurrency(value: number) {+ ow(value, ow.optional.number.integer.greaterThanOrEqual(1));+ this._maxConcurrency = value;+ this.clampDesiredConcurrency();+ }++ /**+ * Gets the desired concurrency for the system,+ * which is an estimated number of parallel tasks that the system can currently support.+ */+ get desiredConcurrency(): number {+ return this._desiredConcurrency;+ }++ /**+ * Sets the desired concurrency for the system, i.e. the number of tasks that should be running+ * in parallel if there's large enough supply of tasks.+ */+ set desiredConcurrency(value: number) {+ ow(value, ow.optional.number.integer.greaterThanOrEqual(1));+ this._desiredConcurrency = value;+ this.clampDesiredConcurrency();+ }++ /**+ * Re-establishes `minConcurrency <= desiredConcurrency <= maxConcurrency` after any of the three is retuned.+ * Dispatch gates on the desired value alone, so one stranded above `maxConcurrency` would make the ceiling+ * meaningless. A contradictory pair (`minConcurrency > maxConcurrency`) resolves in favour of the maximum, since+ * that is the limit callers set in order to protect something.+ */+ private clampDesiredConcurrency(): void {+ const atLeastMin = Math.max(this._desiredConcurrency, this._minConcurrency);+ this._desiredConcurrency = Math.min(atLeastMin, this._maxConcurrency);+ }++ get currentConcurrency(): number {+ return this._currentConcurrency;+ }++ /** Whether the system is currently monitoring load and autoscaling the budget. */+ get isRunning(): boolean {+ return this.running;+ }++ /**+ * Boots the underlying snapshotter and the autoscaling interval. Idempotent, so a shared system isn't restarted+ * when handed to another consumer; concurrent callers await one startup. Rejects, leaving nothing running, if a+ * signal fails to start.+ */+ async start(): Promise<void> {+ // Unwound and dropped again on failure, so a later `start()` retries instead of resolving instantly against+ // a system that is down.+ this.startPromise ??= this.boot().catch(async (error) => {+ this.startPromise = undefined;+ await this.shutDown();+ throw error;+ });++ await this.startPromise;+ }++ private async boot(): Promise<void> {+ // Per-session measurement state, reset so a restarted system isn't judged on the previous session. The+ // per-minute window matters most: its ageing interval is cleared while we are down, so starts from before an+ // arbitrarily long stop would otherwise still count against "this minute" and trip the cap immediately.+ this._tasksPerMinute = Array.from({ length: 60 }, () => 0);+ this.lastLoggingTime = undefined;+ this.warnedAboutQueryWhileStopped = false;++ // Signals are told how much history to keep when they start: exactly the longest window they will be sampled+ // over, so nobody has to guess a retention value that matches this system's configuration.+ const startContext = { maxSampleWindowMillis: this.systemStatus.maxSampleWindowMillis };+ await this.snapshotter.start(startContext);+ await Promise.all(this.loadSignals.map(async (s) => s.start(startContext)));++ this.autoscaleInterval = betterSetInterval(this._autoscale, this.autoscaleIntervalMillis);++ if (this.maxTasksPerMinute !== Infinity) {+ this.tasksDonePerSecondInterval = betterSetInterval(this._incrementTasksDonePerSecond, 1000);+ }++ // Last, so `isRunning` never claims a system whose signals aren't collecting yet.+ this.running = true;+ }++ /**+ * Stops the snapshotter and intervals. Idempotent and safe to call even if the system was never started.+ */+ async stop(): Promise<void> {+ if (this.startPromise === undefined) {+ return;+ }++ // Waited out rather than interrupted, or the intervals a starting signal is about to register outlive us.+ await this.startPromise.catch(() => {});+ this.startPromise = undefined;+ this.running = false;++ await this.shutDown();+ }++ private async shutDown(): Promise<void> {+ if (this.autoscaleInterval) betterClearInterval(this.autoscaleInterval);+ if (this.tasksDonePerSecondInterval) betterClearInterval(this.tasksDonePerSecondInterval);+ await this.snapshotter.stop();+ await Promise.all(this.loadSignals.map(async (s) => s.stop()));+ }++ /**+ * Reports, once per session, that capacity is being queried on a system that isn't running — a mistake nothing+ * else catches, since {@apilink AutoscaledPool.run|`pool.run()`} only checks+ * {@apilink ConcurrencySystem.isRunning|`isRunning`} on the way in. Both the overload verdict and+ * `desiredConcurrency` are frozen at that point, so the borrowing pool would otherwise just quietly mis-scale.+ */+ private warnIfNotRunning(): void {+ if (this.running || this.warnedAboutQueryWhileStopped) {+ return;+ }++ this.warnedAboutQueryWhileStopped = true;+ this.log.warning(+ 'Capacity is being queried on a ConcurrencySystem that is not running, so system load is no longer being ' ++ 'monitored and the concurrency will no longer be adjusted. Whoever creates a ConcurrencySystem owns ' ++ 'its lifecycle: call `await concurrencySystem.stop()` only once every pool and crawler borrowing it ' ++ 'has finished.',+ );+ }++ /**+ * May **one more** task start right now? Returns `false` when the shared budget is spent (desired concurrency+ * reached) or when the machine is overloaded past `minConcurrency`.+ *+ * One budget for the whole machine, so the asking consumer is ignored — and therefore optional here, unlike in the+ * interface, letting the answer be queried directly.+ */+ hasCapacityForTask(_consumer?: ConcurrencyConsumer): boolean {+ this.warnIfNotRunning();++ if (this._currentConcurrency >= this._desiredConcurrency) {+ this.log.perf('Task will not run. Desired concurrency achieved.');+ return false;+ }++ const currentStatus = this.systemStatus.getCurrentStatus();+ const { isSystemIdle } = currentStatus;+ if (!isSystemIdle && this._currentConcurrency >= this._minConcurrency) {+ this.log.perf(+ 'Task will not be run. System is overloaded.',+ currentStatus as unknown as Record<string, unknown>,+ );+ return false;+ }++ return true;+ }++ /** Whether the per-minute task cap has been reached. */+ private get isOverMaxRequestLimit(): boolean {+ if (this.maxTasksPerMinute === Infinity) {+ return false;+ }++ return this._tasksPerMinute.reduce((acc, curr) => acc + curr, 0) >= this.maxTasksPerMinute;+ }++ /**+ * Atomically books a task against the shared budget: re-checks+ * {@apilink ConcurrencySystem.hasCapacityForTask|`hasCapacityForTask()`} plus the per-minute task cap and+ * increments the current concurrency in one synchronous step, returning `false` (without booking) when there is no+ * room. Call right before the task actually runs.+ *+ * The cap is enforced here rather than in the pre-check so that an empty queue never blocks the pool for a whole+ * extra minute.+ */+ tryRegisterTaskStart(consumer?: ConcurrencyConsumer): boolean {+ if (!this.hasCapacityForTask(consumer)) {+ return false;+ }++ if (this.isOverMaxRequestLimit) {+ this.log.perf('Task will not run. Maximum tasks per minute reached.');+ return false;+ }++ this._currentConcurrency++;+ this._tasksPerMinute[0]++;+ return true;+ }++ /** Returns a slot to the shared budget, whoever booked it. */+ registerTaskEnd(_consumer?: ConcurrencyConsumer): void {+ this._currentConcurrency--;+ }++ /**+ * What the system currently makes of the machine: the per-signal overload verdicts, evaluated over the+ * task-gating window, exactly as {@apilink ConcurrencySystem.hasCapacityForTask|`hasCapacityForTask()`} sees them.+ * The one public window into load monitoring — useful for answering *why* a crawl is not scaling up.+ */+ getCurrentStatus(): SystemInfo {+ return this.systemStatus.getCurrentStatus();+ }++ /**+ * Evaluates the historical system status and scales the shared desired concurrency up or down accordingly. Driven+ * by the autoscaling interval started in {@apilink ConcurrencySystem.start|`start()`}.+ */+ private _autoscale(intervalCallback: () => void): void {+ if (this.isOverMaxRequestLimit) return intervalCallback();++ const systemStatus = this.systemStatus.getHistoricalStatus();+ const { isSystemIdle } = systemStatus;+ const weAreNotAtMax = this._desiredConcurrency < this._maxConcurrency;+ const minCurrentConcurrency = Math.floor(this._desiredConcurrency * this.desiredConcurrencyRatio);+ const weAreReachingDesiredConcurrency = this._currentConcurrency >= minCurrentConcurrency;++ if (isSystemIdle && weAreNotAtMax && weAreReachingDesiredConcurrency) this._scaleUp(systemStatus);++ const isSystemOverloaded = !isSystemIdle;+ const weAreNotAtMin = this._desiredConcurrency > this._minConcurrency;++ if (isSystemOverloaded && weAreNotAtMin) this._scaleDown(systemStatus);++ if (this.loggingIntervalMillis > 0) {+ const now = Date.now();++ if (this.lastLoggingTime == null) {+ this.lastLoggingTime = now;+ } else if (now > this.lastLoggingTime + this.loggingIntervalMillis) {+ this.lastLoggingTime = now;+ this.log.info('state', {+ currentConcurrency: this._currentConcurrency,+ desiredConcurrency: this._desiredConcurrency,+ systemStatus,+ });+ }+ }++ return intervalCallback();+ }++ /**+ * Scales the system up by increasing the desired concurrency by the scaleUpStepRatio.+ */+ private _scaleUp(systemStatus: SystemInfo): void {+ const step = Math.ceil(this._desiredConcurrency * this.scaleUpStepRatio);+ this._desiredConcurrency = Math.min(this._maxConcurrency, this._desiredConcurrency + step);+ this.log.debug('scaling up', {+ oldConcurrency: this._desiredConcurrency - step,+ newConcurrency: this._desiredConcurrency,+ systemStatus,+ });+ }++ /**+ * Scales the system down by decreasing the desired concurrency by the scaleDownStepRatio.+ */+ private _scaleDown(systemStatus: SystemInfo): void {+ const step = Math.ceil(this._desiredConcurrency * this.scaleDownStepRatio);+ this._desiredConcurrency = Math.max(this._minConcurrency, this._desiredConcurrency - step);+ this.log.debug('scaling down', {+ oldConcurrency: this._desiredConcurrency + step,+ newConcurrency: this._desiredConcurrency,+ systemStatus,+ });+ }++ private _incrementTasksDonePerSecond(intervalCallback: () => void): void {+ this._tasksPerMinute.unshift(0);+ this._tasksPerMinute.pop();++ return intervalCallback();+ }+}diff --git a/packages/core/src/autoscaling/cpu_load_signal.ts b/packages/core/src/autoscaling/cpu_load_signal.tsindex 77cd91953..123a0e1c7 100644--- a/packages/core/src/autoscaling/cpu_load_signal.ts+++ b/packages/core/src/autoscaling/cpu_load_signal.ts@@ -1,46 +1,83 @@-import type { Configuration } from '../configuration.js';+import type { EventManager } from '../events/event_manager.js';import { EventType } from '../events/event_manager.js';import { serviceLocator } from '../service_locator.js';-import type { LoadSnapshot } from './load_signal.js';+import type { LoadSignal, LoadSignalStartContext, LoadSnapshot } from './load_signal.js';import { SnapshotStore } from './load_signal.js';import type { SystemInfo } from './system_status.js';+/**+ * A snapshot produced by the built-in CPU signal.+ * @internal+ */export interface CpuSnapshot extends LoadSnapshot {usedRatio: number;ticks?: { idle: number; total: number };}+/**+ * Tuning for the built-in **CPU** load signal, as accepted both by {@apilink CpuLoadSignal} and by the+ * {@apilink LoadSignalsOptions.cpu|`cpu`} shorthand on {@apilink LoadSignalsOptions}.+ */export interface CpuLoadSignalOptions {+ /**+ * Maximum ratio of overloaded snapshots in a sample before the CPU counts as overloaded.+ * @default 0.4+ */overloadedRatio?: number;- snapshotHistoryMillis?: number;- configuration: Configuration;}/**- * Tracks CPU usage via `SYSTEM_INFO` events and reports overload when- * the platform or local OS metrics indicate the CPU is overloaded.+ * Tracks CPU usage via `SYSTEM_INFO` events and reports overload when the platform or local OS metrics indicate the+ * CPU is overloaded.+ *+ * Built by default; construct one yourself only to wrap or adapt it — see {@apilink LoadSignal}.+ *+ * @category Scaling*/-export function createCpuLoadSignal(options: CpuLoadSignalOptions) {- return SnapshotStore.fromEvent<CpuSnapshot, SystemInfo>({- name: 'cpuInfo',- overloadedRatio: options.overloadedRatio ?? 0.4,- events: serviceLocator.getEventManager(),- event: EventType.SYSTEM_INFO,- snapshotHistoryMillis: options.snapshotHistoryMillis,- handler(store, systemInfo) {- const { cpuCurrentUsage, isCpuOverloaded } = systemInfo;- const createdAt = systemInfo.createdAt ? new Date(systemInfo.createdAt) : new Date();- store.push(- {- createdAt,- isOverloaded: isCpuOverloaded!,- usedRatio: Math.ceil(cpuCurrentUsage! / 100),- },+export class CpuLoadSignal implements LoadSignal {+ readonly name = 'cpuInfo';+ readonly overloadedRatio: number;++ private readonly store = new SnapshotStore<CpuSnapshot>();+ private events?: EventManager;++ constructor(options: CpuLoadSignalOptions = {}) {+ this.overloadedRatio = options.overloadedRatio ?? 0.4;+ this.handle = this.handle.bind(this);+ }++ async start(context: LoadSignalStartContext): Promise<void> {+ this.store.useSampleWindow(context.maxSampleWindowMillis);+ // A new session starts from a clean slate, so it is not judged on measurements from before the downtime.+ this.store.clear();++ // Resolved here rather than in the constructor, so an instance built ahead of time (to be wrapped, or shared+ // between systems) cannot capture whichever event manager happened to be registered at that moment.+ this.events = serviceLocator.getEventManager();+ this.events.on(EventType.SYSTEM_INFO, this.handle);+ }++ async stop(): Promise<void> {+ this.events?.off(EventType.SYSTEM_INFO, this.handle);+ this.events = undefined;+ }++ getSample(sampleDurationMillis?: number): LoadSnapshot[] {+ return this.store.getSample(sampleDurationMillis);+ }++ /** @internal Records a snapshot from a `SYSTEM_INFO` payload. Exposed for tests. */+ handle(systemInfo: SystemInfo): void {+ const { cpuCurrentUsage, isCpuOverloaded } = systemInfo;+ const createdAt = systemInfo.createdAt ? new Date(systemInfo.createdAt) : new Date();++ this.store.push(+ {createdAt,- );- },- });+ isOverloaded: isCpuOverloaded!,+ usedRatio: Math.ceil(cpuCurrentUsage! / 100),+ },+ createdAt,+ );+ }}--/** @internal Return type for backward compat in Snapshotter facade */-export type CpuLoadSignal = ReturnType<typeof createCpuLoadSignal>;diff --git a/packages/core/src/autoscaling/event_loop_load_signal.ts b/packages/core/src/autoscaling/event_loop_load_signal.tsindex d580d6c8b..37f71f4cb 100644--- a/packages/core/src/autoscaling/event_loop_load_signal.ts+++ b/packages/core/src/autoscaling/event_loop_load_signal.ts@@ -1,56 +1,106 @@-import type { LoadSnapshot } from './load_signal.js';+import type { BetterIntervalID } from '@apify/utilities';+import { betterClearInterval, betterSetInterval } from '@apify/utilities';++import type { LoadSignal, LoadSignalStartContext, LoadSnapshot } from './load_signal.js';import { SnapshotStore } from './load_signal.js';+/**+ * A snapshot produced by the built-in event loop signal.+ * @internal+ */export interface EventLoopSnapshot extends LoadSnapshot {exceededMillis: number;}+/**+ * Tuning for the built-in **event loop** load signal, as accepted both by {@apilink EventLoopLoadSignal} and by the+ * {@apilink LoadSignalsOptions.eventLoop|`eventLoop`} shorthand on {@apilink LoadSignalsOptions}.+ */export interface EventLoopLoadSignalOptions {- eventLoopSnapshotIntervalSecs?: number;+ /**+ * Defines the interval of measuring the event loop response time, in seconds.+ * @default 0.5+ */+ snapshotIntervalSecs?: number;++ /**+ * Maximum allowed delay of the event loop in milliseconds.+ * Exceeding this limit overloads the event loop.+ * @default 50+ */maxBlockedMillis?: number;++ /**+ * Maximum ratio of overloaded snapshots in a sample before the event loop counts as overloaded.+ * @default 0.6+ */overloadedRatio?: number;- snapshotHistoryMillis?: number;}/**- * Periodically measures event loop delay and reports overload when the- * delay exceeds a configured threshold.+ * Periodically measures event loop delay and reports overload when the delay exceeds a configured threshold.+ *+ * Built by default; construct one yourself only to wrap or adapt it — see {@apilink LoadSignal}.+ *+ * @category Scaling*/-export function createEventLoopLoadSignal(options: EventLoopLoadSignalOptions = {}) {- const intervalMillis = (options.eventLoopSnapshotIntervalSecs ?? 0.5) * 1000;- const maxBlockedMillis = options.maxBlockedMillis ?? 50;-- const signal = SnapshotStore.fromInterval<EventLoopSnapshot>({- name: 'eventLoopInfo',- overloadedRatio: options.overloadedRatio ?? 0.6,- intervalMillis,- snapshotHistoryMillis: options.snapshotHistoryMillis,- handler(store, intervalCallback) {- const now = new Date();-- const snapshot: EventLoopSnapshot = {- createdAt: now,- isOverloaded: false,- exceededMillis: 0,- };-- const all = store.getAll();- const previousSnapshot = all[all.length - 1];- if (previousSnapshot) {- const { createdAt } = previousSnapshot;- const delta = now.getTime() - +createdAt - intervalMillis;-- if (delta > maxBlockedMillis) snapshot.isOverloaded = true;- snapshot.exceededMillis = Math.max(delta - maxBlockedMillis, 0);- }-- store.push(snapshot, now);- intervalCallback();- },- });-- return signal;-}+export class EventLoopLoadSignal implements LoadSignal {+ readonly name = 'eventLoopInfo';+ readonly overloadedRatio: number;++ private readonly store = new SnapshotStore<EventLoopSnapshot>();+ private readonly intervalMillis: number;+ private readonly maxBlockedMillis: number;+ private interval?: BetterIntervalID;++ constructor(options: EventLoopLoadSignalOptions = {}) {+ this.overloadedRatio = options.overloadedRatio ?? 0.6;+ this.intervalMillis = (options.snapshotIntervalSecs ?? 0.5) * 1000;+ this.maxBlockedMillis = options.maxBlockedMillis ?? 50;+ this.handle = this.handle.bind(this);+ }-/** @internal Return type for backward compat in Snapshotter facade */-export type EventLoopLoadSignal = ReturnType<typeof createEventLoopLoadSignal>;+ async start(context: LoadSignalStartContext): Promise<void> {+ this.store.useSampleWindow(context.maxSampleWindowMillis);+ // A new session starts from a clean slate, or the downtime gets charged to the event loop: `handle()` measures+ // the gap since the previous snapshot, which across a restart is however long the system was stopped.+ this.store.clear();+ this.interval = betterSetInterval(this.handle, this.intervalMillis);+ }++ async stop(): Promise<void> {+ if (this.interval) betterClearInterval(this.interval);+ this.interval = undefined;+ }++ getSample(sampleDurationMillis?: number): LoadSnapshot[] {+ return this.store.getSample(sampleDurationMillis);+ }++ /**+ * Records one snapshot: how much later than scheduled this tick ran is how long the loop was blocked.+ * @internal Also lets tests drive the measurement without waiting on a timer.+ */+ handle(intervalCallback: () => unknown): void {+ const now = new Date();++ const snapshot: EventLoopSnapshot = {+ createdAt: now,+ isOverloaded: false,+ exceededMillis: 0,+ };++ const all = this.store.getAll();+ const previousSnapshot = all[all.length - 1];++ if (previousSnapshot) {+ const delta = now.getTime() - +previousSnapshot.createdAt - this.intervalMillis;++ if (delta > this.maxBlockedMillis) snapshot.isOverloaded = true;+ snapshot.exceededMillis = Math.max(delta - this.maxBlockedMillis, 0);+ }++ this.store.push(snapshot, now);+ intervalCallback();+ }+}diff --git a/packages/core/src/autoscaling/index.ts b/packages/core/src/autoscaling/index.tsindex 0e3829a86..356788ffa 100644--- a/packages/core/src/autoscaling/index.ts+++ b/packages/core/src/autoscaling/index.ts@@ -1,4 +1,5 @@export * from './autoscaled_pool.js';+export * from './concurrency_system.js';export * from './client_load_signal.js';export * from './cpu_load_signal.js';export * from './event_loop_load_signal.js';diff --git a/packages/core/src/autoscaling/load_signal.ts b/packages/core/src/autoscaling/load_signal.tsindex 95231bd46..cfea06546 100644--- a/packages/core/src/autoscaling/load_signal.ts+++ b/packages/core/src/autoscaling/load_signal.ts@@ -1,9 +1,5 @@import { weightedAvg } from '@crawlee/utils';-import type { BetterIntervalID } from '@apify/utilities';-import { betterClearInterval, betterSetInterval } from '@apify/utilities';--import type { EventManager, EventTypeName } from '../events/event_manager.js';import type { ClientInfo } from './system_status.js';/**@@ -15,15 +11,35 @@ export interface LoadSnapshot {}/**- * A signal that reports whether a particular resource is overloaded.+ * Handed to a {@apilink LoadSignal} when it starts, so it can size its snapshot retention to what it will actually+ * be asked for — without having to know how the {@apilink ConcurrencySystem} that drives it is configured.+ */+export interface LoadSignalStartContext {+ /**+ * The longest sample window the signal will be queried with (the wider of the task-gating and autoscaling+ * windows). Keeping less history than this contributes a narrower view of the resource than the other signals;+ * keeping more is wasted memory, as the extra snapshots are never sampled.+ */+ maxSampleWindowMillis: number;+}++/**+ * A signal that reports whether a particular resource is overloaded. The {@apilink ConcurrencySystem} aggregates+ * several of them — if any one reports overload, the system is overloaded.*- * `SystemStatus` aggregates multiple `LoadSignal` instances to determine- * overall system health. The built-in signals cover memory, CPU, event loop,- * and API client rate limits. You can implement this interface to add- * custom overload signals (e.g. navigation timeouts, proxy health).+ * The built-in signals cover memory, CPU, event loop and storage-client rate limits. Implement this interface to add+ * your own (navigation timeouts, proxy health, …) and pass them via+ * {@apilink LoadSignalsOptions.custom|`loadSignals.custom`}; {@apilink SnapshotStore} does the time-windowed+ * bookkeeping if you want it. Each built-in is also a public class, so one can be *wrapped* rather than reimplemented+ * — construct it yourself and switch the default off with {@apilink LoadSignalsOptions.cpu|`cpu: false`} or friends.*/export interface LoadSignal {- /** Human-readable name used in logging and `SystemInfo` keys. */+ /**+ * This signal's key in the reported {@apilink SystemInfo}, also used in logging — so it must be unique among the+ * signals of one {@apilink ConcurrencySystem}, which throws on a duplicate. The four built-in names (`memInfo`,+ * `eventLoopInfo`, `cpuInfo`, `clientInfo`) land in the correspondingly named `SystemInfo` fields rather than the+ * `loadSignalInfo` bag; taking one over means switching that built-in off.+ */readonly name: string;/**@@ -33,10 +49,13 @@ export interface LoadSignal {*/readonly overloadedRatio: number;- /** Start collecting snapshots. Called when the pool starts. */- start(): Promise<void>;+ /**+ * Start collecting snapshots, retaining at least the sample window named in the `context`. Called when the+ * {@apilink ConcurrencySystem} starts — which may be a *restart*, so drop anything measured before it.+ */+ start(context: LoadSignalStartContext): Promise<void>;- /** Stop collecting snapshots. Called when the pool shuts down. */+ /** Stop collecting snapshots. Called when the {@apilink ConcurrencySystem} shuts down. */stop(): Promise<void>;/**@@ -47,15 +66,22 @@ export interface LoadSignal {}/**- * A time-pruning, time-windowed store for `LoadSnapshot` values.- * Signals compose with this instead of inheriting from a base class.+ * A time-pruning, time-windowed store for `LoadSnapshot` values. All four built-in signals compose with one of these,+ * and so can yours — it is the only part of their machinery worth reusing.*/export class SnapshotStore<T extends LoadSnapshot = LoadSnapshot> {private snapshots: T[] = [];- private readonly historyMillis: number;- constructor(historyMillis = 30_000) {- this.historyMillis = historyMillis;+ /** Retention window in milliseconds. Unbounded until {@apilink SnapshotStore.useSampleWindow|`useSampleWindow()`}. */+ private historyMillis = Infinity;++ /**+ * Sizes retention to the window the signal will be sampled over, as handed to it in+ * {@apilink LoadSignal.start|`start()`}. Until this is called nothing is pruned at all, so a signal that ignores+ * its start context grows unboundedly.+ */+ useSampleWindow(maxSampleWindowMillis: number): void {+ this.historyMillis = maxSampleWindowMillis;}/**@@ -98,85 +124,21 @@ export class SnapshotStore<T extends LoadSnapshot = LoadSnapshot> {}/**- * Direct access to the underlying array (for backward-compat getters).+ * Direct, unwindowed access to the underlying array — used by signals whose handler needs the previous snapshot+ * to compute a delta (e.g. the event loop and client signals read the last entry to measure change since it).*/getAll(): T[] {return this.snapshots;}/**- * Create a `LoadSignal` that snapshots on a `betterSetInterval` tick.- *- * The `handler` receives the store (to read previous snapshots) and the- * interval callback (which it **must** call when done). It should call- * `store.push()` to record a snapshot.- */- static fromInterval<T extends LoadSnapshot>(options: {- name: string;- overloadedRatio: number;- intervalMillis: number;- snapshotHistoryMillis?: number;- handler: (store: SnapshotStore<T>, intervalCallback: () => unknown) => void;- }): Omit<LoadSignal, 'getSample'> & {- store: SnapshotStore<T>;- handle: (cb: () => unknown) => void;- getSample(sampleDurationMillis?: number): T[];- } {- const store = new SnapshotStore<T>(options.snapshotHistoryMillis);- let interval: BetterIntervalID = null!;-- const handle = (cb: () => unknown) => options.handler(store, cb);-- return {- name: options.name,- overloadedRatio: options.overloadedRatio,- store,- handle,- getSample: (ms) => store.getSample(ms),- async start() {- interval = betterSetInterval(handle, options.intervalMillis);- },- async stop() {- betterClearInterval(interval);- },- };- }-- /**- * Create a `LoadSignal` that snapshots in response to an `EventManager` event.- *- * The `handler` receives the event payload and the store. It should call- * `store.push()` to record a snapshot.+ * Discards every retained snapshot. The built-in signals do this when they *start*, so that a session neither+ * samples nor diffs against measurements from before the preceding downtime — pruning is relative to the newest+ * snapshot rather than the wall clock, so stale entries would otherwise survive indefinitely. Clearing on start+ * rather than on stop leaves a finished session readable.*/- static fromEvent<T extends LoadSnapshot, E>(options: {- name: string;- overloadedRatio: number;- events: EventManager;- event: EventTypeName;- snapshotHistoryMillis?: number;- handler: (store: SnapshotStore<T>, payload: E) => void;- }): Omit<LoadSignal, 'getSample'> & {- store: SnapshotStore<T>;- handle: (payload: E) => void;- getSample(sampleDurationMillis?: number): T[];- } {- const store = new SnapshotStore<T>(options.snapshotHistoryMillis);-- const handle = (payload: E) => options.handler(store, payload);-- return {- name: options.name,- overloadedRatio: options.overloadedRatio,- store,- handle,- getSample: (ms) => store.getSample(ms),- async start() {- options.events.on(options.event, handle);- },- async stop() {- options.events.off(options.event, handle);- },- };+ clear(): void {+ this.snapshots = [];}}@@ -184,6 +146,7 @@ export class SnapshotStore<T extends LoadSnapshot = LoadSnapshot> {* Evaluate whether a sample of `LoadSnapshot` values exceeds the given* overloaded ratio, using a time-weighted average. This is the shared* evaluation logic used by `SystemStatus` for all signal types.+ * @internal*/export function evaluateLoadSignalSample(sample: LoadSnapshot[], overloadedRatio: number): ClientInfo {if (sample.length === 0) {diff --git a/packages/core/src/autoscaling/memory_load_signal.ts b/packages/core/src/autoscaling/memory_load_signal.tsindex 59881c4a2..893283c9a 100644--- a/packages/core/src/autoscaling/memory_load_signal.ts+++ b/packages/core/src/autoscaling/memory_load_signal.ts@@ -5,59 +5,85 @@ import type { CrawleeLogger } from '../log.js';import { serviceLocator } from '../service_locator.js';import { getMemoryInfo } from '../system-info/memory-info.js';import { isContainerized } from '../system-info/runtime.js';-import type { LoadSignal, LoadSnapshot } from './load_signal.js';+import type { LoadSignal, LoadSignalStartContext, LoadSnapshot } from './load_signal.js';import { SnapshotStore } from './load_signal.js';import type { SystemInfo } from './system_status.js';const RESERVE_MEMORY_RATIO = 0.5;const CRITICAL_OVERLOAD_RATE_LIMIT_MILLIS = 10_000;+/**+ * A snapshot produced by the built-in memory signal.+ * @internal+ */export interface MemorySnapshot extends LoadSnapshot {usedBytes?: number;}+/**+ * Tuning for the built-in **memory** load signal, as accepted both by {@apilink MemoryLoadSignal} and by the+ * {@apilink LoadSignalsOptions.memory|`memory`} shorthand on {@apilink LoadSignalsOptions}.+ */export interface MemoryLoadSignalOptions {- maxUsedMemoryRatio?: number;+ /**+ * Defines the maximum ratio of total memory that can be used.+ * Exceeding this limit overloads the memory.+ * @default 0.9+ */+ maxUsedRatio?: number;++ /**+ * Maximum ratio of overloaded snapshots in a sample before memory counts as overloaded.+ * @default 0.2+ */overloadedRatio?: number;- snapshotHistoryMillis?: number;- configuration: Configuration;- log?: CrawleeLogger;}/**- * Tracks memory usage via `SYSTEM_INFO` events and reports overload when- * the used-to-available memory ratio exceeds a threshold.+ * Tracks memory usage via `SYSTEM_INFO` events and reports overload when the used-to-available memory ratio exceeds a+ * threshold. Also warns when memory use becomes critical.+ *+ * Built by default; construct one yourself only to wrap or adapt it — see {@apilink LoadSignal}.+ *+ * @category Scaling*/export class MemoryLoadSignal implements LoadSignal {readonly name = 'memInfo';readonly overloadedRatio: number;- private readonly store: SnapshotStore<MemorySnapshot>;- private readonly configuration: Configuration;- private readonly events: EventManager;- private readonly log: CrawleeLogger;- private readonly maxUsedMemoryRatio: number;- private maxMemoryRatio: number | undefined;+ private readonly store = new SnapshotStore<MemorySnapshot>();+ private readonly maxUsedRatio: number;+ /** All resolved in `start()`, before anything that reads them can fire. */+ private config!: Configuration;+ private log!: CrawleeLogger;private maxMemoryBytes!: number;+ private events?: EventManager;+ private maxMemoryRatio: number | undefined;private lastLoggedCriticalMemoryOverloadAt: Date | null = null;- constructor(options: MemoryLoadSignalOptions) {- this.store = new SnapshotStore(options.snapshotHistoryMillis);- this.configuration = options.configuration;- this.events = serviceLocator.getEventManager();- this.log = options.log ?? serviceLocator.getLogger().child({ prefix: 'MemoryLoadSignal' });- this.maxUsedMemoryRatio = options.maxUsedMemoryRatio ?? 0.9;+ constructor(options: MemoryLoadSignalOptions = {}) {+ this.maxUsedRatio = options.maxUsedRatio ?? 0.9;this.overloadedRatio = options.overloadedRatio ?? 0.2;- this._onSystemInfo = this._onSystemInfo.bind(this);+ this.handle = this.handle.bind(this);}- async start(): Promise<void> {- const memoryMbytes = this.configuration.memoryMbytes ?? 0;+ async start(context: LoadSignalStartContext): Promise<void> {+ this.store.useSampleWindow(context.maxSampleWindowMillis);+ // A new session starts from a clean slate, so it is not judged on measurements from before the downtime.+ this.store.clear();++ // Resolved here rather than in the constructor: an instance built ahead of time (to be wrapped, or shared+ // between systems) must not capture whichever services happened to be registered at that moment.+ this.config = serviceLocator.getConfiguration();+ this.events = serviceLocator.getEventManager();+ this.log = serviceLocator.getLogger().child({ prefix: 'MemoryLoadSignal' });++ const memoryMbytes = this.config.memoryMbytes ?? 0;if (memoryMbytes > 0) {this.maxMemoryBytes = memoryMbytes * 1024 * 1024;} else {- this.maxMemoryRatio = this.configuration.availableMemoryRatio;+ this.maxMemoryRatio = this.config.availableMemoryRatio;if (!this.maxMemoryRatio) {throw new Error('availableMemoryRatio is not set in configuration.');} else {@@ -70,37 +96,31 @@ export class MemoryLoadSignal implements LoadSignal {this.maxMemoryBytes = await this._getTotalMemoryBytes();}- this.events.on(EventType.SYSTEM_INFO, this._onSystemInfo);+ this.events.on(EventType.SYSTEM_INFO, this.handle);}async stop(): Promise<void> {- this.events.off(EventType.SYSTEM_INFO, this._onSystemInfo);+ this.events?.off(EventType.SYSTEM_INFO, this.handle);+ this.events = undefined;}- getSample(sampleDurationMillis?: number): MemorySnapshot[] {+ getSample(sampleDurationMillis?: number): LoadSnapshot[] {return this.store.getSample(sampleDurationMillis);}- /**- * Returns typed memory snapshots for backward compatibility with `Snapshotter`.- */- getMemorySnapshots(): MemorySnapshot[] {- return this.store.getAll();- }-- /** @internal */- _onSystemInfo(systemInfo: SystemInfo): void {+ /** @internal Records a snapshot from a `SYSTEM_INFO` payload. Exposed for tests. */+ handle(systemInfo: SystemInfo): void {const createdAt = systemInfo.createdAt ? new Date(systemInfo.createdAt) : new Date();const { memCurrentBytes, memTotalBytes } = systemInfo;- let maxMemoryBytes = this.maxMemoryBytes!;+ let maxMemoryBytes = this.maxMemoryBytes;if (this.maxMemoryRatio !== undefined && this.maxMemoryRatio > 0) {maxMemoryBytes = this.maxMemoryRatio * (memTotalBytes ?? this.maxMemoryBytes);}const snapshot: MemorySnapshot = {createdAt,- isOverloaded: memCurrentBytes! / maxMemoryBytes > this.maxUsedMemoryRatio,+ isOverloaded: memCurrentBytes! / maxMemoryBytes > this.maxUsedRatio,usedBytes: memCurrentBytes,};@@ -110,7 +130,7 @@ export class MemoryLoadSignal implements LoadSignal {/** @internal */_memoryOverloadWarning(systemInfo: SystemInfo, maxMemoryBytes?: number): void {- const effectiveMax = maxMemoryBytes ?? this.maxMemoryBytes!;+ const effectiveMax = maxMemoryBytes ?? this.maxMemoryBytes;const { memCurrentBytes } = systemInfo;const createdAt = systemInfo.createdAt ? new Date(systemInfo.createdAt) : new Date();if (@@ -119,8 +139,8 @@ export class MemoryLoadSignal implements LoadSignal {)return;- const maxDesiredMemoryBytes = this.maxUsedMemoryRatio * effectiveMax;- const reserveMemory = effectiveMax * (1 - this.maxUsedMemoryRatio) * RESERVE_MEMORY_RATIO;+ const maxDesiredMemoryBytes = this.maxUsedRatio * effectiveMax;+ const reserveMemory = effectiveMax * (1 - this.maxUsedRatio) * RESERVE_MEMORY_RATIO;const criticalOverloadBytes = maxDesiredMemoryBytes + reserveMemory;const isCriticalOverload = memCurrentBytes! > criticalOverloadBytes;@@ -138,7 +158,7 @@ export class MemoryLoadSignal implements LoadSignal {}private async _getTotalMemoryBytes(): Promise<number> {- const containerized = this.configuration.containerized ?? (await isContainerized());+ const containerized = this.config.containerized ?? (await isContainerized());return (await getMemoryInfo({ containerized, logger: serviceLocator.getLogger() })).totalBytes;}}diff --git a/packages/core/src/autoscaling/snapshotter.ts b/packages/core/src/autoscaling/snapshotter.tsindex d460160f9..cf18f7d12 100644--- a/packages/core/src/autoscaling/snapshotter.ts+++ b/packages/core/src/autoscaling/snapshotter.ts@@ -1,248 +1,129 @@-import type { StorageBackend } from '@crawlee/types';-import ow from 'ow';--import type { Configuration } from '../configuration.js';-import type { CrawleeLogger } from '../log.js';-import { serviceLocator } from '../service_locator.js';-import type { ClientLoadSignal, ClientSnapshot } from './client_load_signal.js';-import { createClientLoadSignal } from './client_load_signal.js';-import type { CpuLoadSignal, CpuSnapshot } from './cpu_load_signal.js';-import { createCpuLoadSignal } from './cpu_load_signal.js';-import type { EventLoopLoadSignal, EventLoopSnapshot } from './event_loop_load_signal.js';-import { createEventLoopLoadSignal } from './event_loop_load_signal.js';-import type { LoadSignal } from './load_signal.js';-import type { MemorySnapshot } from './memory_load_signal.js';+import type { ClientLoadSignalOptions } from './client_load_signal.js';+import { ClientLoadSignal } from './client_load_signal.js';+import type { CpuLoadSignalOptions } from './cpu_load_signal.js';+import { CpuLoadSignal } from './cpu_load_signal.js';+import type { EventLoopLoadSignalOptions } from './event_loop_load_signal.js';+import { EventLoopLoadSignal } from './event_loop_load_signal.js';+import type { LoadSignal, LoadSignalStartContext } from './load_signal.js';+import type { MemoryLoadSignalOptions } from './memory_load_signal.js';import { MemoryLoadSignal } from './memory_load_signal.js';-export interface SnapshotterOptions {- /**- * Defines the interval of measuring the event loop response time.- * @default 0.5- */- eventLoopSnapshotIntervalSecs?: number;-+/**+ * The load signals a {@apilink ConcurrencySystem} watches to decide whether the machine is overloaded.+ *+ * Each of the four built-in signals is configured by passing its options bag — shorthand for constructing the+ * corresponding {@apilink LoadSignal} class yourself, so `{ cpu: { overloadedRatio: 0.5 } }` is exactly+ * `{ cpu: false, custom: [new CpuLoadSignal({ overloadedRatio: 0.5 })] }`. Pass `false` to leave a resource+ * unwatched, and put anything else you want taken into account in {@apilink LoadSignalsOptions.custom|`custom`}.+ *+ * How far back the signals are evaluated is *not* set here, but by+ * {@apilink ConcurrencySystemOptions.snapshotHistorySecs|`snapshotHistorySecs`} and+ * {@apilink ConcurrencySystemOptions.currentHistorySecs|`currentHistorySecs`}.+ */+export interface LoadSignalsOptions {/**- * Defines the interval of checking the current state- * of the remote API client.- * @default 1+ * Tuning for the built-in {@apilink MemoryLoadSignal} (used-memory limit + overload ratio), or `false` to switch+ * it off.*/- clientSnapshotIntervalSecs?: number;+ memory?: MemoryLoadSignalOptions | false;/**- * Maximum allowed delay of the event loop in milliseconds.- * Exceeding this limit overloads the event loop.- * @default 50+ * Tuning for the built-in {@apilink EventLoopLoadSignal} (snapshot interval + blocked-millis limit + overload+ * ratio), or `false` to switch it off — which also stops its measuring interval.*/- maxBlockedMillis?: number;+ eventLoop?: EventLoopLoadSignalOptions | false;/**- * Defines the maximum ratio of total memory that can be used.- * Exceeding this limit overloads the memory.- * @default 0.9+ * Tuning for the built-in {@apilink CpuLoadSignal} (overload ratio), or `false` to switch it off.*/- maxUsedMemoryRatio?: number;+ cpu?: CpuLoadSignalOptions | false;/**- * Defines the maximum number of new rate limit errors within- * the given interval.- * @default 3+ * Tuning for the built-in {@apilink ClientLoadSignal} (snapshot interval + error limit + overload ratio), or+ * `false` to switch it off — worth doing when the storage backend reports no rate-limit statistics, since the+ * signal otherwise polls it every second to no purpose.*/- maxClientErrors?: number;+ client?: ClientLoadSignalOptions | false;/**- * Sets the interval in seconds for which a history of resource snapshots- * will be kept. Increasing this to very high numbers will affect performance.- * @default 30+ * Additional {@apilink LoadSignal} implementations — e.g. navigation timeouts or proxy health — evaluated+ * alongside the built-in four. If any signal reports overload, the system counts as overloaded. Their lifecycle+ * is driven by the {@apilink ConcurrencySystem} they are given to, and their {@apilink LoadSignal.name|names} must+ * not collide with an enabled built-in's.*/- snapshotHistorySecs?: number;-- /** @internal */- log?: CrawleeLogger;-- /** @internal */- client?: StorageBackend;-- /** @internal */- configuration?: Configuration;+ custom?: LoadSignal[];}/**- * Creates snapshots of system resources at given intervals and marks the resource- * as either overloaded or not during the last interval. Keeps a history of the snapshots.- * It tracks the following resources: Memory, EventLoop, API and CPU.- * The class is used by the {@apilink AutoscaledPool} class.- *- * When running on the Apify platform, the CPU and memory statistics are provided by the platform,- * as collected from the running Docker container. When running locally, `Snapshotter`- * makes its own statistics by querying the OS.- *- * CPU becomes overloaded locally when its current use exceeds the `maxUsedCpuRatio` option or- * when Apify platform marks it as overloaded.- *- * Memory becomes overloaded if its current use exceeds the `maxUsedMemoryRatio` option.- * It's computed using the total memory available to the container when running on- * the Apify platform and a quarter of total system memory when running locally.- * Max total memory when running locally may be overridden by using the `CRAWLEE_MEMORY_MBYTES`- * environment variable.- *- * Event loop becomes overloaded if it slows down by more than the `maxBlockedMillis` option.- *- * Client becomes overloaded when rate limit errors (429 - Too Many Requests),- * typically received from the request queue, exceed the set limit within the set interval.+ * An implementation detail of the {@apilink ConcurrencySystem}: the built-in signal tuning from+ * {@apilink LoadSignalsOptions}, minus the custom signals, which the system evaluates itself rather than collecting+ * them here.+ * @internal+ */+export type SnapshotterOptions = Omit<LoadSignalsOptions, 'custom'>;++/**+ * Owns the four built-in {@apilink LoadSignal} instances — {@apilink MemoryLoadSignal},+ * {@apilink EventLoopLoadSignal}, {@apilink CpuLoadSignal} and {@apilink ClientLoadSignal} — constructing the ones+ * that were not switched off and driving their shared lifecycle.*- * @category Scaling+ * Configured indirectly through {@apilink ConcurrencySystemOptions.loadSignals|`loadSignals`}, whose per-signal bags+ * are simply forwarded to the corresponding constructor.+ * @internal*/export class Snapshotter {- readonly log: CrawleeLogger;- readonly client: StorageBackend;- readonly configuration: Configuration;-- private readonly memorySignal: MemoryLoadSignal;- private readonly eventLoopSignal: EventLoopLoadSignal;- private readonly cpuSignal: CpuLoadSignal;- private readonly clientSignal: ClientLoadSignal;+ // Absent when switched off through the corresponding option (e.g. `client: false`).+ private readonly memorySignal?: MemoryLoadSignal;+ private readonly eventLoopSignal?: EventLoopLoadSignal;+ private readonly cpuSignal?: CpuLoadSignal;+ private readonly clientSignal?: ClientLoadSignal;/**- * Returns the four built-in signals as an array, so `SystemStatus` can- * iterate them alongside any custom `LoadSignal` instances.+ * Returns the enabled built-in signals, so `SystemStatus` can iterate them alongside any custom `LoadSignal`+ * instances. Signals switched off through the options are simply absent — the system status reports them as+ * not overloaded.*/getLoadSignals(): LoadSignal[] {- return [this.memorySignal, this.eventLoopSignal, this.cpuSignal, this.clientSignal];- }-- // Legacy public properties kept for backward compat (tests read these directly)- get cpuSnapshots(): CpuSnapshot[] {- return this.cpuSignal.store.getAll();- }-- get eventLoopSnapshots(): EventLoopSnapshot[] {- return this.eventLoopSignal.store.getAll();- }-- get memorySnapshots(): MemorySnapshot[] {- return this.memorySignal.getMemorySnapshots();- }-- get clientSnapshots(): ClientSnapshot[] {- return this.clientSignal.store.getAll();+ const builtin: (LoadSignal | undefined)[] = [+ this.memorySignal,+ this.eventLoopSignal,+ this.cpuSignal,+ this.clientSignal,+ ];++ return builtin.filter((signal): signal is LoadSignal => signal !== undefined);}/*** @param [options] All `Snapshotter` configuration options.*/constructor(options: SnapshotterOptions = {}) {- ow(- options,- ow.object.exactShape({- eventLoopSnapshotIntervalSecs: ow.optional.number,- clientSnapshotIntervalSecs: ow.optional.number,- snapshotHistorySecs: ow.optional.number,- maxBlockedMillis: ow.optional.number,- maxUsedMemoryRatio: ow.optional.number,- maxClientErrors: ow.optional.number,- log: ow.optional.object,- client: ow.optional.object,- configuration: ow.optional.object,- }),- );-- const {- eventLoopSnapshotIntervalSecs = 0.5,- clientSnapshotIntervalSecs = 1,- snapshotHistorySecs = 30,- maxBlockedMillis = 50,- maxUsedMemoryRatio = 0.9,- maxClientErrors = 3,- log = serviceLocator.getLogger(),- configuration = serviceLocator.getConfiguration(),- client = serviceLocator.getStorageBackend(),- } = options;-- this.log = log.child({ prefix: 'Snapshotter' });- this.client = client;- this.configuration = configuration;-- const snapshotHistoryMillis = snapshotHistorySecs * 1000;-- this.memorySignal = new MemoryLoadSignal({- maxUsedMemoryRatio,- snapshotHistoryMillis,- configuration: this.configuration,- log: this.log,- });-- this.eventLoopSignal = createEventLoopLoadSignal({- eventLoopSnapshotIntervalSecs,- maxBlockedMillis,- snapshotHistoryMillis,- });-- this.cpuSignal = createCpuLoadSignal({- snapshotHistoryMillis,- configuration: this.configuration,- });-- this.clientSignal = createClientLoadSignal({- client: this.client,- clientSnapshotIntervalSecs,- maxClientErrors,- snapshotHistoryMillis,- });+ const { memory = {}, eventLoop = {}, cpu = {}, client = {} } = options;++ // Each signal resolves its own ambient dependencies when started, and is told the window it will be sampled+ // over then too - so there is nothing to thread in here beyond the caller's tuning.+ if (memory !== false) this.memorySignal = new MemoryLoadSignal(memory);+ if (eventLoop !== false) this.eventLoopSignal = new EventLoopLoadSignal(eventLoop);+ if (cpu !== false) this.cpuSignal = new CpuLoadSignal(cpu);+ if (client !== false) this.clientSignal = new ClientLoadSignal(client);}/**- * Starts capturing snapshots at configured intervals.+ * Starts capturing snapshots at configured intervals. The `context` carries the sample window the signals will+ * be queried with, which is also how much history they retain.*/- async start(): Promise<void> {- await this.memorySignal.start();- await this.eventLoopSignal.start();- await this.cpuSignal.start();- await this.clientSignal.start();+ async start(context: LoadSignalStartContext): Promise<void> {+ await Promise.all(this.getLoadSignals().map(async (signal) => signal.start(context)));}/*** Stops all resource capturing.*/async stop(): Promise<void> {- await this.memorySignal.stop();- await this.eventLoopSignal.stop();- await this.cpuSignal.stop();- await this.clientSignal.stop();+ await Promise.all(this.getLoadSignals().map(async (signal) => signal.stop()));// Allow microtask queue to unwind before stop returns.await new Promise((resolve) => {setImmediate(resolve);});}-- /**- * Returns a sample of latest memory snapshots, with the size of the sample defined- * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.- */- getMemorySample(sampleDurationMillis?: number): MemorySnapshot[] {- return this.memorySignal.getSample(sampleDurationMillis);- }-- /**- * Returns a sample of latest event loop snapshots, with the size of the sample defined- * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.- */- getEventLoopSample(sampleDurationMillis?: number): EventLoopSnapshot[] {- return this.eventLoopSignal.getSample(sampleDurationMillis);- }-- /**- * Returns a sample of latest CPU snapshots, with the size of the sample defined- * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.- */- getCpuSample(sampleDurationMillis?: number): CpuSnapshot[] {- return this.cpuSignal.getSample(sampleDurationMillis);- }-- /**- * Returns a sample of latest Client snapshots, with the size of the sample defined- * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.- */- getClientSample(sampleDurationMillis?: number): ClientSnapshot[] {- return this.clientSignal.getSample(sampleDurationMillis);- }}diff --git a/packages/core/src/autoscaling/system_status.ts b/packages/core/src/autoscaling/system_status.tsindex 310663619..e5f1f3ede 100644--- a/packages/core/src/autoscaling/system_status.ts+++ b/packages/core/src/autoscaling/system_status.ts@@ -1,8 +1,6 @@-import ow from 'ow';-import type { LoadSignal } from './load_signal.js';import { evaluateLoadSignalSample } from './load_signal.js';-import { Snapshotter } from './snapshotter.js';+import type { LoadSignalsOptions, Snapshotter } from './snapshotter.js';/*** Represents the current status of the system.@@ -39,6 +37,24 @@ export interface SystemInfo {loadSignalInfo?: Record<string, ClientInfo>;}+/**+ * How far back the *current* system status looks by default — the window that gates task dispatch.+ * @internal+ */+export const DEFAULT_CURRENT_HISTORY_SECS = 5;++/**+ * How far back the *historical* system status looks by default — the window autoscaling decisions are based on, and+ * therefore how much history the signals are asked to retain.+ * @internal+ */+export const DEFAULT_SNAPSHOT_HISTORY_SECS = 30;++/**+ * An implementation detail of the {@apilink ConcurrencySystem} — configure it through+ * {@apilink ConcurrencySystemOptions} (`loadSignals`, `currentHistorySecs` and `snapshotHistorySecs`).+ * @internal+ */export interface SystemStatusOptions {/*** Defines max age of snapshots used in the {@apilink SystemStatus.getCurrentStatus} measurement.@@ -47,43 +63,23 @@ export interface SystemStatusOptions {currentHistorySecs?: number;/**- * Sets the maximum ratio of overloaded snapshots in a memory sample.- * If the sample exceeds this ratio, the system will be overloaded.- * @default 0.2+ * Defines max age of snapshots used in the {@apilink SystemStatus.getHistoricalStatus} measurement — the window+ * autoscaling decisions are based on. Applied uniformly to every signal, built-in or custom, so that a signal's+ * private retention cannot silently widen the window.+ * @default 30*/- maxMemoryOverloadedRatio?: number;+ historySecs?: number;/**- * Sets the maximum ratio of overloaded snapshots in an event loop sample.- * If the sample exceeds this ratio, the system will be overloaded.- * @default 0.6+ * The `Snapshotter` whose built-in signals are evaluated.*/- maxEventLoopOverloadedRatio?: number;-- /**- * Sets the maximum ratio of overloaded snapshots in a CPU sample.- * If the sample exceeds this ratio, the system will be overloaded.- * @default 0.4- */- maxCpuOverloadedRatio?: number;-- /**- * Sets the maximum ratio of overloaded snapshots in a Client sample.- * If the sample exceeds this ratio, the system will be overloaded.- * @default 0.3- */- maxClientOverloadedRatio?: number;-- /**- * The `Snapshotter` instance to be queried for `SystemStatus`.- */- snapshotter?: Snapshotter;+ snapshotter: Snapshotter;/*** Additional load signals to include in the system status evaluation.* These are evaluated alongside the built-in memory, CPU, event loop,* and client signals. If any signal reports overload, the system is- * considered overloaded.+ * considered overloaded. Each signal carries its own overload ratio.*/loadSignals?: LoadSignal[];}@@ -107,80 +103,78 @@ export interface FinalStatistics {crawlerRuntimeMillis: number;}-/** The four built-in signal names that map to typed `SystemInfo` fields. */-const BUILTIN_SIGNAL_NAMES = new Set(['memInfo', 'eventLoopInfo', 'cpuInfo', 'clientInfo']);+/** The four built-in signal names that map to typed `SystemInfo` fields, and the option that switches each off. */+const BUILTIN_SIGNAL_OPTION_KEYS: Record<string, keyof LoadSignalsOptions> = {+ memInfo: 'memory',+ eventLoopInfo: 'eventLoop',+ cpuInfo: 'cpu',+ clientInfo: 'client',+};++const BUILTIN_SIGNAL_NAMES = new Set(Object.keys(BUILTIN_SIGNAL_OPTION_KEYS));/**- * Provides a simple interface to reading system status from a {@apilink Snapshotter} instance.- * It only exposes two functions {@apilink SystemStatus.getCurrentStatus}- * and {@apilink SystemStatus.getHistoricalStatus}.- * The system status is calculated using a weighted average of overloaded- * messages in the snapshots, with the weights being the time intervals- * between the snapshots. Each resource is calculated separately- * and the system is overloaded whenever at least one resource is overloaded.- * The class is used by the {@apilink AutoscaledPool} class.+ * Reads the overload verdict of every signal — the {@apilink Snapshotter}'s built-in four plus any custom ones — and+ * combines them into a {@apilink SystemInfo}: each signal is a time-weighted average of its snapshots, and the system+ * is overloaded whenever at least one of them is.*- * {@apilink SystemStatus.getCurrentStatus}- * returns a boolean that represents the current status of the system.- * The length of the current timeframe in seconds is configurable- * by the `currentHistorySecs` option and represents the max age- * of snapshots to be considered for the calculation.+ * Evaluated over two windows, both requested explicitly from every signal so that a signal's private retention cannot+ * widen what it contributes: a short `currentHistorySecs` one ({@apilink SystemStatus.getCurrentStatus}, gating task+ * dispatch) and a longer `historySecs` one ({@apilink SystemStatus.getHistoricalStatus}, driving autoscaling).*- * {@apilink SystemStatus.getHistoricalStatus}- * returns a boolean that represents the long-term status- * of the system. It considers the full snapshot history available- * in the {@apilink Snapshotter} instance.- * @category Scaling+ * An implementation detail of the {@apilink ConcurrencySystem}, configured through+ * {@apilink ConcurrencySystemOptions}.+ * @internal*/export class SystemStatus {private readonly currentHistoryMillis: number;- private readonly snapshotter: Snapshotter;+ private readonly historyMillis: number;private readonly signals: LoadSignal[];- /**- * Per-signal ratio overrides. The built-in four get their overrides from- * the legacy `max*OverloadedRatio` options; custom signals use their own- * `overloadedRatio`.- */- private ratioOverrides: Record<string, number>;-- constructor(options: SystemStatusOptions = {}) {- ow(- options,- ow.object.exactShape({- currentHistorySecs: ow.optional.number,- maxMemoryOverloadedRatio: ow.optional.number,- maxEventLoopOverloadedRatio: ow.optional.number,- maxCpuOverloadedRatio: ow.optional.number,- maxClientOverloadedRatio: ow.optional.number,- snapshotter: ow.optional.object,- loadSignals: ow.optional.array,- }),- );-+ constructor(options: SystemStatusOptions) {const {- currentHistorySecs = 5,- maxMemoryOverloadedRatio = 0.2,- maxEventLoopOverloadedRatio = 0.6,- maxCpuOverloadedRatio = 0.4,- maxClientOverloadedRatio = 0.3,+ currentHistorySecs = DEFAULT_CURRENT_HISTORY_SECS,+ historySecs = DEFAULT_SNAPSHOT_HISTORY_SECS,snapshotter,loadSignals = [],} = options;this.currentHistoryMillis = currentHistorySecs * 1000;- this.snapshotter = snapshotter || new Snapshotter();+ this.historyMillis = historySecs * 1000;- // Built-in signals from the snapshotter + any custom signals- this.signals = [...this.snapshotter.getLoadSignals(), ...loadSignals];+ this.signals = [...snapshotter.getLoadSignals(), ...loadSignals];+ this.assertUniqueSignalNames();+ }- // Allow legacy options to override the built-in signal ratios- this.ratioOverrides = {- memInfo: maxMemoryOverloadedRatio,- eventLoopInfo: maxEventLoopOverloadedRatio,- cpuInfo: maxCpuOverloadedRatio,- clientInfo: maxClientOverloadedRatio,- };+ /**+ * The widest window any signal will be queried with, and therefore exactly how much history the signals are asked+ * to retain when they start. Derived here, where the windows are resolved, so nothing has to reapply their+ * defaults.+ */+ get maxSampleWindowMillis(): number {+ return Math.max(this.currentHistoryMillis, this.historyMillis);+ }++ /**+ * Signal names are the keys of the reported {@apilink SystemInfo}, so a duplicate would leave a status object that+ * contradicts actual behavior: both signals are still evaluated (any overloaded one holds concurrency down), but+ * only the last is reported.+ */+ private assertUniqueSignalNames(): void {+ const seen = new Set<string>();++ for (const { name } of this.signals) {+ if (!seen.has(name)) {+ seen.add(name);+ continue;+ }++ const hint = BUILTIN_SIGNAL_NAMES.has(name)+ ? `it is the name of a built-in signal. To replace that signal, switch it off with \`loadSignals: { ${BUILTIN_SIGNAL_OPTION_KEYS[name]}: false }\` and keep your implementation in \`loadSignals.custom\`; to run yours alongside it, give it a different name.`+ : 'two custom signals cannot share a name - rename one of them.';++ throw new Error(`Duplicate load signal name ${JSON.stringify(name)}: ${hint}`);+ }}/**@@ -215,12 +209,11 @@ export class SystemStatus {* }* ```*- * Where the `isSystemIdle` property is set to `false` if the system- * has been overloaded in the full history of the {@apilink Snapshotter}- * (which is configurable in the {@apilink Snapshotter}) and `true` otherwise.+ * Where the `isSystemIdle` property is set to `false` if the system has been overloaded within the last+ * `historySecs` seconds and `true` otherwise.*/getHistoricalStatus(): SystemInfo {- return this.isSystemIdle();+ return this.isSystemIdle(this.historyMillis);}/**@@ -238,9 +231,8 @@ export class SystemStatus {let loadSignalInfo: Record<string, ClientInfo> | undefined;for (const signal of this.signals) {- const ratio = this.ratioOverrides[signal.name] ?? signal.overloadedRatio;const sample = signal.getSample(sampleDurationMillis);- const info = evaluateLoadSignalSample(sample, ratio);+ const info = evaluateLoadSignalSample(sample, signal.overloadedRatio);if (info.isOverloaded) {result.isSystemIdle = false;diff --git a/packages/http-crawler/README.md b/packages/http-crawler/README.mdindex 05dd473c9..89b15b86f 100644--- a/packages/http-crawler/README.md+++ b/packages/http-crawler/README.md@@ -22,7 +22,7 @@ preNavigationHooks: [By default, `HttpCrawler` only processes web pages with the `text/html` and `application/xhtml+xml` MIME content types (as reported by the `Content-Type` HTTP header), and skips pages with other content types. If you want the crawler to process other content types, use the [HttpCrawlerOptions.additionalMimeTypes](https://crawlee.dev/js/api/http-crawler/interface/HttpCrawlerOptions#additionalMimeTypes) constructor option. Beware that the parsing behavior differs for HTML, XML, JSON and other types of content. For more details, see [HttpCrawlerOptions.requestHandler](https://crawlee.dev/js/api/http-crawler/interface/HttpCrawlerOptions#requestHandler).-New requests are only dispatched when there is enough free CPU and memory available, using the functionality provided by the [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) class. All [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) configuration options can be passed to the `autoscaledPoolOptions` parameter of the `HttpCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency` [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) options are available directly in the `HttpCrawler` constructor.+New requests are only dispatched when there is enough free CPU and memory available, using the functionality provided by the [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) class. Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the `HttpCrawler` constructor, or, for finer control, by injecting a pre-configured `concurrencySystem` — see `ConcurrencySystem`.## Example usagediff --git a/packages/http-crawler/src/internals/file-download.ts b/packages/http-crawler/src/internals/file-download.tsindex 0faf96a71..d047212c9 100644--- a/packages/http-crawler/src/internals/file-download.ts+++ b/packages/http-crawler/src/internals/file-download.ts@@ -140,7 +140,7 @@ export function ByteCounterStream({* ]* ```*- * New requests are only dispatched when there is enough free CPU and memory available, using the functionality provided by the {@apilink AutoscaledPool} class. All {@apilink AutoscaledPool} configuration options can be passed to the `autoscaledPoolOptions` parameter of the `FileCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency` {@apilink AutoscaledPool} options are available directly in the `FileCrawler` constructor.+ * New requests are only dispatched when there is enough free CPU and memory available, using the functionality provided by the {@apilink AutoscaledPool} class. Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the `FileCrawler` constructor, or, for finer control, by injecting a pre-configured {@apilink ConcurrencySystem|`concurrencySystem`}.** ## Example usage*diff --git a/packages/http-crawler/src/internals/http-crawler.ts b/packages/http-crawler/src/internals/http-crawler.tsindex e1047427f..987648874 100644--- a/packages/http-crawler/src/internals/http-crawler.ts+++ b/packages/http-crawler/src/internals/http-crawler.ts@@ -2,8 +2,9 @@ import { Readable } from 'node:stream';import util from 'node:util';import type {- AutoscaledPoolOptions,BasicCrawlerOptions,+ ConcurrencySystem,+ ConcurrencySystemOptions,ContextMiddleware,CrawlingContext,ErrorHandler,@@ -43,14 +44,25 @@ import { extractCharsetFromHtmlBytes, parseContentTypeFromResponse, processHttpR*/const HTML_AND_XML_MIME_TYPES = ['text/html', 'text/xml', 'application/xhtml+xml', 'application/xml'];const APPLICATION_JSON_MIME_TYPE = 'application/json';-const HTTP_OPTIMIZED_AUTOSCALED_POOL_OPTIONS: AutoscaledPoolOptions = {+/**+ * A higher starting concurrency and a relaxed event loop signal, since HTTP-only crawling barely touches the event+ * loop. {@apilink HttpCrawler} folds these into the {@apilink ConcurrencySystem} it builds by default.+ *+ * A {@apilink BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} you supply yourself replaces that default+ * wholesale, tuning included, so spread these options in if you want to keep it:+ *+ * ```typescript+ * new ConcurrencySystem({ ...HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS, maxConcurrency: 50 });+ * ```+ */+export const HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS: ConcurrencySystemOptions = {desiredConcurrency: 10,- snapshotterOptions: {- eventLoopSnapshotIntervalSecs: 2,- maxBlockedMillis: 100,- },- systemStatusOptions: {- maxEventLoopOverloadedRatio: 0.7,+ loadSignals: {+ eventLoop: {+ snapshotIntervalSecs: 2,+ maxBlockedMillis: 100,+ overloadedRatio: 0.7,+ },},};@@ -292,9 +304,9 @@ export type HttpRequestHandler<** New requests are only dispatched when there is enough free CPU and memory available,* using the functionality provided by the {@apilink AutoscaledPool} class.- * All {@apilink AutoscaledPool} configuration options can be passed to the `autoscaledPoolOptions`- * parameter of the constructor. For user convenience, the `minConcurrency` and `maxConcurrency`- * {@apilink AutoscaledPool} options are available directly in the constructor.+ * Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the+ * constructor, or, for finer control, by injecting a pre-configured+ * {@apilink ConcurrencySystem|`concurrencySystem`}.** **Example usage:***@@ -374,14 +386,12 @@ export class HttpCrawler<postNavigationHooks = [],// BasicCrawler- autoscaledPoolOptions = HTTP_OPTIMIZED_AUTOSCALED_POOL_OPTIONS,contextPipelineBuilder,...basicCrawlerOptions} = options;super({...basicCrawlerOptions,- autoscaledPoolOptions,contextPipelineBuilder:contextPipelineBuilder ??(() => this.buildContextPipeline() as ContextPipeline<CrawlingContext, Context>),@@ -412,6 +422,19 @@ export class HttpCrawler<this.saveResponseCookies = saveResponseCookies;}+ /**+ * Folds {@apilink HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS} into the default system, keeping the user's+ * concurrency shortcuts on top. Not called for a supplied+ * {@apilink BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} — spread the constant into it yourself to+ * keep the tuning.+ */+ protected override createDefaultConcurrencySystem(options: ConcurrencySystemOptions): ConcurrencySystem {+ return super.createDefaultConcurrencySystem({+ ...HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS,+ ...options,+ });+ }+protected override buildContextPipeline(): ContextPipeline<CrawlingContext, InternalHttpCrawlingContext> {// When navigation is skipped, `prepareHttpRequest` has already installed throwing getters for// the response-derived members, so the guarded action is bypassed and the context left untouched.diff --git a/packages/jsdom-crawler/README.md b/packages/jsdom-crawler/README.mdindex afde8250d..c2cd250a1 100644--- a/packages/jsdom-crawler/README.md+++ b/packages/jsdom-crawler/README.md@@ -24,7 +24,7 @@ preNavigationHooks: [By default, `JSDOMCrawler` only processes web pages with the `text/html` and `application/xhtml+xml` MIME content types (as reported by the `Content-Type` HTTP header), and skips pages with other content types. If you want the crawler to process other content types, use the [JSDOMCrawlerOptions.additionalMimeTypes](https://crawlee.dev/js/api/jsdom-crawler/interface/JSDOMCrawlerOptions#additionalMimeTypes) constructor option. Beware that the parsing behavior differs for HTML, XML, JSON and other types of content. For more details, see [JSDOMCrawlerOptions.requestHandler](https://crawlee.dev/js/api/jsdom-crawler/interface/JSDOMCrawlerOptions#requestHandler).-New requests are only dispatched when there is enough free CPU and memory available, using the functionality provided by the [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) class. All [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) configuration options can be passed to the `autoscaledPoolOptions` parameter of the `JSDOMCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency` [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) options are available directly in the `JSDOMCrawler` constructor.+New requests are only dispatched when there is enough free CPU and memory available, using the functionality provided by the [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) class. Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the `JSDOMCrawler` constructor, or, for finer control, by injecting a pre-configured `concurrencySystem` — see `ConcurrencySystem`.## Example usagediff --git a/packages/jsdom-crawler/src/internals/jsdom-crawler.ts b/packages/jsdom-crawler/src/internals/jsdom-crawler.tsindex 3e6a43aa4..16d5e3c36 100644--- a/packages/jsdom-crawler/src/internals/jsdom-crawler.ts+++ b/packages/jsdom-crawler/src/internals/jsdom-crawler.ts@@ -156,9 +156,9 @@ export type JSDOMRequestHandler<** New requests are only dispatched when there is enough free CPU and memory available,* using the functionality provided by the {@apilink AutoscaledPool} class.- * All {@apilink AutoscaledPool} configuration options can be passed to the `autoscaledPoolOptions`- * parameter of the `CheerioCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency`- * {@apilink AutoscaledPool} options are available directly in the `CheerioCrawler` constructor.+ * Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the+ * `JSDOMCrawler` constructor, or, for finer control, by injecting a pre-configured+ * {@apilink ConcurrencySystem|`concurrencySystem`}.** **Example usage:***diff --git a/packages/linkedom-crawler/README.md b/packages/linkedom-crawler/README.mdindex 014749c81..47e4d8c26 100644--- a/packages/linkedom-crawler/README.md+++ b/packages/linkedom-crawler/README.md@@ -26,7 +26,7 @@ preNavigationHooks: [By default, `LinkeDOMCrawler` only processes web pages with the `text/html` and `application/xhtml+xml` MIME content types (as reported by the `Content-Type` HTTP header), and skips pages with other content types. If you want the crawler to process other content types, use the [LinkeDOMCrawlerOptions.additionalMimeTypes](https://crawlee.dev/js/api/linkedom-crawler/interface/LinkeDOMCrawlerOptions#additionalMimeTypes) constructor option. Beware that the parsing behavior differs for HTML, XML, JSON and other types of content. For more details, see [LinkeDOMCrawlerOptions.requestHandler](https://crawlee.dev/js/api/linkedom-crawler/interface/LinkeDOMCrawlerOptions#requestHandler).-New requests are only dispatched when there is enough free CPU and memory available, using the functionality provided by the [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) class. All [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) configuration options can be passed to the `autoscaledPoolOptions` parameter of the `LinkeDOMCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency` [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) options are available directly in the `LinkeDOMCrawler` constructor.+New requests are only dispatched when there is enough free CPU and memory available, using the functionality provided by the [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) class. Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the `LinkeDOMCrawler` constructor, or, for finer control, by injecting a pre-configured `concurrencySystem` — see `ConcurrencySystem`.## Example usagediff --git a/packages/linkedom-crawler/src/internals/linkedom-crawler.ts b/packages/linkedom-crawler/src/internals/linkedom-crawler.tsindex cf5f2dec3..12e531eb8 100644--- a/packages/linkedom-crawler/src/internals/linkedom-crawler.ts+++ b/packages/linkedom-crawler/src/internals/linkedom-crawler.ts@@ -146,9 +146,9 @@ export type LinkeDOMRequestHandler<** New requests are only dispatched when there is enough free CPU and memory available,* using the functionality provided by the {@apilink AutoscaledPool} class.- * All {@apilink AutoscaledPool} configuration options can be passed to the `autoscaledPoolOptions`- * parameter of the `CheerioCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency`- * {@apilink AutoscaledPool} options are available directly in the `CheerioCrawler` constructor.+ * Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the+ * `LinkeDOMCrawler` constructor, or, for finer control, by injecting a pre-configured+ * {@apilink ConcurrencySystem|`concurrencySystem`}.** **Example usage:***diff --git a/packages/playwright-crawler/README.md b/packages/playwright-crawler/README.mdindex 85728e399..adae570b6 100644--- a/packages/playwright-crawler/README.md+++ b/packages/playwright-crawler/README.md@@ -12,7 +12,7 @@ The crawler finishes when there are no more [Request](https://crawlee.dev/js/api`PlaywrightCrawler` opens a new Chrome page (i.e. tab) for each [Request](https://crawlee.dev/js/api/core/class/Request) object to crawl and then calls the function provided by user as the [PlaywrightCrawlerOptions.requestHandler](https://crawlee.dev/js/api/playwright-crawler/interface/PlaywrightCrawlerOptions#requestHandler) option.-New pages are only opened when there is enough free CPU and memory available, using the functionality provided by the [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) class. All [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) configuration options can be passed to the [PlaywrightCrawlerOptions.autoscaledPoolOptions](https://crawlee.dev/js/api/playwright-crawler/interface/PlaywrightCrawlerOptions#autoscaledPoolOptions) parameter of the `PlaywrightCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency` [AutoscaledPoolOptions](https://crawlee.dev/js/api/core/interface/AutoscaledPoolOptions) are available directly in the `PlaywrightCrawler` constructor.+New pages are only opened when there is enough free CPU and memory available, using the functionality provided by the [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) class. Concurrency is tuned via the [`minConcurrency`](https://crawlee.dev/js/api/playwright-crawler/interface/PlaywrightCrawlerOptions#minConcurrency), [`maxConcurrency`](https://crawlee.dev/js/api/playwright-crawler/interface/PlaywrightCrawlerOptions#maxConcurrency) and [`maxRequestsPerMinute`](https://crawlee.dev/js/api/playwright-crawler/interface/PlaywrightCrawlerOptions#maxRequestsPerMinute) options of the `PlaywrightCrawler` constructor, or, for finer control, by injecting a pre-configured [`concurrencySystem`](https://crawlee.dev/js/api/playwright-crawler/interface/PlaywrightCrawlerOptions#concurrencySystem) — see `ConcurrencySystem`.Note that the pool of Playwright instances is internally managed by the [BrowserPool](https://github.com/apify/browser-pool) class.diff --git a/packages/playwright-crawler/src/internals/playwright-crawler.ts b/packages/playwright-crawler/src/internals/playwright-crawler.tsindex c4df502e2..90b8f297f 100644--- a/packages/playwright-crawler/src/internals/playwright-crawler.ts+++ b/packages/playwright-crawler/src/internals/playwright-crawler.ts@@ -145,9 +145,9 @@ export interface PlaywrightCrawlerOptions<** New pages are only opened when there is enough free CPU and memory available,* using the functionality provided by the {@apilink AutoscaledPool} class.- * All {@apilink AutoscaledPool} configuration options can be passed to the {@apilink PlaywrightCrawlerOptions.autoscaledPoolOptions}- * parameter of the `PlaywrightCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency`- * {@apilink AutoscaledPoolOptions} are available directly in the `PlaywrightCrawler` constructor.+ * Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the+ * `PlaywrightCrawler` constructor, or, for finer control, by injecting a pre-configured+ * {@apilink ConcurrencySystem|`concurrencySystem`}.** Note that the pool of Playwright instances is internally managed by the [BrowserPool](https://github.com/apify/browser-pool) class.*diff --git a/packages/puppeteer-crawler/README.md b/packages/puppeteer-crawler/README.mdindex 27b6b3e06..c52535543 100644--- a/packages/puppeteer-crawler/README.md+++ b/packages/puppeteer-crawler/README.md@@ -17,9 +17,7 @@ and then calls the function provided by user as the [PuppeteerCrawlerOptions.reqNew pages are only opened when there is enough free CPU and memory available,using the functionality provided by the [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) class.-All [AutoscaledPool](https://crawlee.dev/js/api/core/class/AutoscaledPool) configuration options can be passed to the [PuppeteerCrawlerOptions.autoscaledPoolOptions](https://crawlee.dev/js/api/puppeteer-crawler/interface/PuppeteerCrawlerOptions#autoscaledPoolOptions)-parameter of the `PuppeteerCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency`-[AutoscaledPoolOptions](https://crawlee.dev/js/api/core/interface/AutoscaledPoolOptions) are available directly in the `PuppeteerCrawler` constructor.+Concurrency is tuned via the [`minConcurrency`](https://crawlee.dev/js/api/puppeteer-crawler/interface/PuppeteerCrawlerOptions#minConcurrency), [`maxConcurrency`](https://crawlee.dev/js/api/puppeteer-crawler/interface/PuppeteerCrawlerOptions#maxConcurrency) and [`maxRequestsPerMinute`](https://crawlee.dev/js/api/puppeteer-crawler/interface/PuppeteerCrawlerOptions#maxRequestsPerMinute) options of the `PuppeteerCrawler` constructor, or, for finer control, by injecting a pre-configured [`concurrencySystem`](https://crawlee.dev/js/api/puppeteer-crawler/interface/PuppeteerCrawlerOptions#concurrencySystem) — see `ConcurrencySystem`.Note that the pool of Puppeteer instances is internally managed by the [BrowserPool](https://github.com/apify/browser-pool) class.diff --git a/packages/puppeteer-crawler/src/internals/puppeteer-crawler.ts b/packages/puppeteer-crawler/src/internals/puppeteer-crawler.tsindex 4f5773352..cbbdb1f1c 100644--- a/packages/puppeteer-crawler/src/internals/puppeteer-crawler.ts+++ b/packages/puppeteer-crawler/src/internals/puppeteer-crawler.ts@@ -122,9 +122,9 @@ export interface PuppeteerCrawlerOptions<** New pages are only opened when there is enough free CPU and memory available,* using the functionality provided by the {@apilink AutoscaledPool} class.- * All {@apilink AutoscaledPool} configuration options can be passed to the {@apilink PuppeteerCrawlerOptions.autoscaledPoolOptions}- * parameter of the `PuppeteerCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency`- * {@apilink AutoscaledPoolOptions} are available directly in the `PuppeteerCrawler` constructor.+ * Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the+ * `PuppeteerCrawler` constructor, or, for finer control, by injecting a pre-configured+ * {@apilink ConcurrencySystem|`concurrencySystem`}.** Note that the pool of Puppeteer instances is internally managed by the [BrowserPool](https://github.com/apify/browser-pool) class.*diff --git a/test/core/autoscaling/autoscaled_pool.test.ts b/test/core/autoscaling/autoscaled_pool.test.tsindex 8e8e63b11..ab7812403 100644--- a/test/core/autoscaling/autoscaled_pool.test.ts+++ b/test/core/autoscaling/autoscaled_pool.test.ts@@ -1,9 +1,45 @@-import type { LoadSignal, LoadSnapshot } from '@crawlee/core';-import { AutoscaledPool } from '@crawlee/core';+import type {+ AutoscaledPoolOptions,+ ConcurrencyConsumer,+ ConcurrencySystemOptions,+ LoadSignal,+ LoadSnapshot,+} from '@crawlee/core';+import { AutoscaledPool, ConcurrencySystem, CriticalError } from '@crawlee/core';import { sleep } from '@crawlee/utils';import log from '@apify/log';+/**+ * Test helper mirroring how {@apilink BasicCrawler} drives a pool: `concurrencyOptions` build a {@apilink+ * ConcurrencySystem}, `poolOptions` configure the pool itself. Kept as two separate bags routed to their own+ * constructors. Tests that need the system directly can read `pool.system`.+ *+ * The pool no longer owns the system's lifecycle, so the helper awaits `start()` on the freshly-built system (the+ * pool assumes it's already running) and registers an `onTestFinished` hook to `stop()` it, so snapshotter intervals+ * don't leak between tests. Must be called from within a test (or a `beforeEach`).+ */+async function makePool(+ poolOptions: Omit<AutoscaledPoolOptions, 'concurrencySystem' | 'consumer'> & { consumer?: ConcurrencyConsumer },+ concurrencyOptions: ConcurrencySystemOptions = {},+): Promise<AutoscaledPool> {+ const concurrencySystem = new ConcurrencySystem(concurrencyOptions);+ await concurrencySystem.start();+ onTestFinished(async () => concurrencySystem.stop());++ // The identity only matters to a governor that allocates per consumer, which `ConcurrencySystem` does not - so+ // tests get a stock one unless they say otherwise.+ return new AutoscaledPool({ consumer: { id: 'test-pool' }, ...poolOptions, concurrencySystem });+}++/**+ * The concrete governor behind a pool. The pool exposes only the read-only {@apilink IConcurrencySystem} telemetry —+ * tests that tune or inspect scaling policy (min/max concurrency, ratios) reach for the canonical implementation.+ */+function systemOf(pool: AutoscaledPool): ConcurrencySystem {+ return pool.system as ConcurrencySystem;+}+describe('AutoscaledPool', () => {let logLevel: number;beforeAll(() => {@@ -33,13 +69,14 @@ describe('AutoscaledPool', () => {});};- const pool = new AutoscaledPool({- minConcurrency: 1,- maxConcurrency: 1,- runTaskFunction,- isFinishedFunction: async () => Promise.resolve(isFinished),- isTaskReadyFunction: async () => Promise.resolve(!isFinished),- });+ const pool = await makePool(+ {+ runTaskFunction,+ isFinishedFunction: async () => Promise.resolve(isFinished),+ isTaskReadyFunction: async () => Promise.resolve(!isFinished),+ },+ { minConcurrency: 1, maxConcurrency: 1 },+ );await pool.run();expect(result).toEqual([...Array(10).keys()]);@@ -63,13 +100,14 @@ describe('AutoscaledPool', () => {});};- const pool = new AutoscaledPool({- minConcurrency: 10,- maxConcurrency: 10,- runTaskFunction,- isFinishedFunction: async () => Promise.resolve(isFinished),- isTaskReadyFunction: async () => Promise.resolve(!isFinished),- });+ const pool = await makePool(+ {+ runTaskFunction,+ isFinishedFunction: async () => Promise.resolve(isFinished),+ isTaskReadyFunction: async () => Promise.resolve(!isFinished),+ },+ { minConcurrency: 10, maxConcurrency: 10 },+ );await pool.run();@@ -94,29 +132,30 @@ describe('AutoscaledPool', () => {});};- const pool = new AutoscaledPool({+ const pool = await makePool(+ {+ runTaskFunction,+ isFinishedFunction: async () => isFinished,+ isTaskReadyFunction: async () => !isFinished,+ },// Test initial concurrency setting- minConcurrency: 3,- maxConcurrency: 13,- desiredConcurrency: 9,- runTaskFunction,- isFinishedFunction: async () => isFinished,- isTaskReadyFunction: async () => !isFinished,- });+ { minConcurrency: 3, maxConcurrency: 13, desiredConcurrency: 9 },+ );- expect(pool.minConcurrency).toBe(3);- expect(pool.maxConcurrency).toBe(13);+ const system = systemOf(pool);+ expect(system.minConcurrency).toBe(3);+ expect(system.maxConcurrency).toBe(13);expect(pool.desiredConcurrency).toBe(9);const promise = pool.run();- // Test setting concurrency- pool.minConcurrency = 4;- pool.maxConcurrency = 14;- pool.desiredConcurrency = 7;+ // Concurrency is tuned on the governor; the pool only reflects it as read-only telemetry.+ system.minConcurrency = 4;+ system.maxConcurrency = 14;+ system.desiredConcurrency = 7;- expect(pool.minConcurrency).toBe(4);- expect(pool.maxConcurrency).toBe(14);+ expect(system.minConcurrency).toBe(4);+ expect(system.maxConcurrency).toBe(14);expect(pool.desiredConcurrency).toBe(7);await promise;@@ -142,72 +181,80 @@ describe('AutoscaledPool', () => {let pool: AutoscaledPool;let systemStatus: MockSystemStatus;const cb = () => {};- beforeEach(() => {+ beforeEach(async () => {systemStatus = new MockSystemStatus(true, true);- pool = new AutoscaledPool({- minConcurrency: 1,- maxConcurrency: 100,- runTaskFunction: async () => {},- isFinishedFunction: async () => false,- isTaskReadyFunction: async () => true,- });+ pool = await makePool(+ {+ runTaskFunction: async () => {},+ isFinishedFunction: async () => false,+ isTaskReadyFunction: async () => true,+ },+ { minConcurrency: 1, maxConcurrency: 100 },+ );+ // Autoscaling now lives on the shared governor; mock its system status.// @ts-expect-error Mock- pool.systemStatus = systemStatus;+ pool.system.systemStatus = systemStatus;});test('works with low values', () => {- // @ts-expect-error Calling private method- pool.autoscale(cb);+ // @ts-expect-error Calling private method on the governor+ pool.system._autoscale(cb);expect(pool.desiredConcurrency).toBe(2);- // @ts-expect-error Calling private method- pool.autoscale(cb);+ // @ts-expect-error Calling private method on the governor+ pool.system._autoscale(cb);expect(pool.desiredConcurrency).toBe(2); // because currentConcurrency is not high enough;// @ts-expect-error Overwriting readonly private prop- pool._currentConcurrency = 2;- // @ts-expect-error Calling private method- pool.autoscale(cb);+ pool.system._currentConcurrency = 2;+ // @ts-expect-error Calling private method on the governor+ pool.system._autoscale(cb);expect(pool.desiredConcurrency).toBe(3);systemStatus.okNow = false; // this should have no effect// @ts-expect-error Overwriting readonly private prop- pool._currentConcurrency = 3;- // @ts-expect-error Calling private method- pool.autoscale(cb);+ pool.system._currentConcurrency = 3;+ // @ts-expect-error Calling private method on the governor+ pool.system._autoscale(cb);expect(pool.desiredConcurrency).toBe(4);systemStatus.okLately = false;- // @ts-expect-error Calling private method- pool.autoscale(cb);+ // @ts-expect-error Calling private method on the governor+ pool.system._autoscale(cb);expect(pool.desiredConcurrency).toBe(3);});test('works with high values', () => {// Should not scale because current concurrency is too low.- pool.desiredConcurrency = 50;+ systemOf(pool).desiredConcurrency = 50;// @ts-expect-error Overwriting readonly private prop- pool._currentConcurrency = Math.floor(pool.desiredConcurrency * pool.desiredConcurrencyRatio) - 1;+ pool.system._currentConcurrency =+ // @ts-expect-error Accessing private prop on the governor+ Math.floor(pool.desiredConcurrency * pool.system.desiredConcurrencyRatio) - 1;systemStatus.okLately = true;- // @ts-expect-error Calling private method- pool.autoscale(cb);+ // @ts-expect-error Calling private method on the governor+ pool.system._autoscale(cb);expect(pool.desiredConcurrency).toBe(50);// Should scale because we bumped up current concurrency.// @ts-expect-error Overwriting readonly private prop- pool._currentConcurrency = Math.floor(pool.desiredConcurrency * pool.desiredConcurrencyRatio);- // @ts-expect-error Accessing private prop- let newConcurrency = pool.desiredConcurrency + Math.ceil(pool.desiredConcurrency * pool.scaleUpStepRatio);- // @ts-expect-error Calling private method- pool.autoscale(cb);+ pool.system._currentConcurrency =+ // @ts-expect-error Accessing private prop on the governor+ Math.floor(pool.desiredConcurrency * pool.system.desiredConcurrencyRatio);+ let newConcurrency =+ // @ts-expect-error Accessing private prop on the governor+ pool.desiredConcurrency + Math.ceil(pool.desiredConcurrency * pool.system.scaleUpStepRatio);+ // @ts-expect-error Calling private method on the governor+ pool.system._autoscale(cb);expect(pool.desiredConcurrency).toEqual(newConcurrency);// Should scale down.systemStatus.okLately = false;- // @ts-expect-error Accessing private prop- newConcurrency = pool.desiredConcurrency - Math.ceil(pool.desiredConcurrency * pool.scaleDownStepRatio);- // @ts-expect-error Calling private method- pool.autoscale(cb);+ newConcurrency =+ // @ts-expect-error Accessing private prop on the governor+ pool.desiredConcurrency - Math.ceil(pool.desiredConcurrency * pool.system.scaleDownStepRatio);+ // @ts-expect-error Calling private method on the governor+ pool.system._autoscale(cb);expect(pool.desiredConcurrency).toEqual(newConcurrency);});@@ -215,8 +262,8 @@ describe('AutoscaledPool', () => {let limit = 5;let concurrencyLog: number[] = [];let count = 0;- // @ts-expect-error Overwriting readonly private prop- pool.systemStatus.okNow = false;+ // @ts-expect-error Overwriting readonly private prop on the governor+ pool.system.systemStatus.okNow = false;// @ts-expect-error Overwriting readonly private proppool.runTaskFunction = async () => {await sleep(10);@@ -226,11 +273,12 @@ describe('AutoscaledPool', () => {pool.isFinishedFunction = async () => count >= limit;// @ts-expect-error Overwriting readonly private proppool.isTaskReadyFunction = async () => count < limit;- pool.desiredConcurrency = 10;- // @ts-expect-error Overwriting readonly private prop- pool._currentConcurrency = pool.currentConcurrency;+ systemOf(pool).desiredConcurrency = 10;- Object.defineProperty(pool, 'currentConcurrency', {+ // Spy on the governor's concurrency accounting - that is where per-task current concurrency now lives.+ // @ts-expect-error Overwriting readonly private prop on the governor+ pool.system._currentConcurrency = pool.currentConcurrency;+ Object.defineProperty(pool.system, 'currentConcurrency', {get() {return this._currentConcurrency;},@@ -248,7 +296,7 @@ describe('AutoscaledPool', () => {limit = 50;concurrencyLog = [];count = 0;- pool.minConcurrency = 5;+ systemOf(pool).minConcurrency = 5;await pool.run();expect(concurrencyLog.some((n) => n > 5)).toBe(false);@@ -275,13 +323,14 @@ describe('AutoscaledPool', () => {if (counter > 20) throw new Error('some-promise-error');};- const pool = new AutoscaledPool({- maxConcurrency: 5,- minConcurrency: 5,- runTaskFunction,- isFinishedFunction: async () => counter > 200,- isTaskReadyFunction: async () => true,- });+ const pool = await makePool(+ {+ runTaskFunction,+ isFinishedFunction: async () => counter > 200,+ isTaskReadyFunction: async () => true,+ },+ { maxConcurrency: 5, minConcurrency: 5 },+ );await expect(pool.run()).rejects.toThrow('some-promise-error');});@@ -292,47 +341,152 @@ describe('AutoscaledPool', () => {throw new Error('some-runtask-error');};- const pool = new AutoscaledPool({- maxConcurrency: 1,- runTaskFunction,+ const pool = await makePool(+ {+ runTaskFunction,+ isFinishedFunction: async () => false,+ isTaskReadyFunction: async () => true,+ },+ { maxConcurrency: 1 },+ );++ await expect(pool.run()).rejects.toThrow('some-runtask-error');+ });++ test('and still returns the failed task’s slot to the governor', async () => {+ const pool = await makePool(+ {+ runTaskFunction: async () => {+ await sleep(1);+ throw new Error('some-runtask-error');+ },+ isFinishedFunction: async () => false,+ isTaskReadyFunction: async () => true,+ },+ { minConcurrency: 1, maxConcurrency: 1, desiredConcurrency: 1 },+ );++ await expect(pool.run()).rejects.toThrow('some-runtask-error');++ // A slot leaked on the error path is never recovered - with a shared ConcurrencySystem it permanently+ // shrinks the budget of every other pool borrowing it.+ expect(systemOf(pool).currentConcurrency).toBe(0);+ expect(systemOf(pool).hasCapacityForTask()).toBe(true);+ });++ test('and still returns the slot when the task throws a CriticalError', async () => {+ // CriticalError takes a different branch out of the task loop (it is deliberately not logged), which is+ // exactly where the slot used to leak.+ const pool = await makePool(+ {+ runTaskFunction: async () => {+ await sleep(1);+ throw new CriticalError('some-critical-error');+ },+ isFinishedFunction: async () => false,+ isTaskReadyFunction: async () => true,+ },+ { minConcurrency: 1, maxConcurrency: 1, desiredConcurrency: 1 },+ );++ await expect(pool.run()).rejects.toThrow('some-critical-error');++ expect(pool.currentConcurrency).toBe(0);+ expect(systemOf(pool).currentConcurrency).toBe(0);+ });++ test('and still returns the slot when the task times out', async () => {+ const pool = await makePool(+ {+ runTaskFunction: async () => sleep(1e3),+ taskTimeoutSecs: 0.05,+ isFinishedFunction: async () => false,+ isTaskReadyFunction: async () => true,+ },+ { minConcurrency: 1, maxConcurrency: 1, desiredConcurrency: 1 },+ );++ await expect(pool.run()).rejects.toThrow('runTaskFunction timed out');++ // The abandoned task is left to its own devices, but its slot is not.+ expect(systemOf(pool).currentConcurrency).toBe(0);+ });++ test('and a failing pool does not shrink a shared budget', async () => {+ const system = new ConcurrencySystem({ minConcurrency: 2, maxConcurrency: 2, desiredConcurrency: 2 });+ await system.start();+ onTestFinished(async () => system.stop());++ const failing = new AutoscaledPool({+ concurrencySystem: system,+ consumer: { id: 'failing' },+ runTaskFunction: async () => {+ await sleep(1);+ throw new Error('some-runtask-error');+ },isFinishedFunction: async () => false,isTaskReadyFunction: async () => true,});- await expect(pool.run()).rejects.toThrow('some-runtask-error');+ await expect(failing.run()).rejects.toThrow('some-runtask-error');++ // The survivor must still be able to reach the full shared concurrency of 2.+ let done = 0;+ let peak = 0;+ let current = 0;+ const survivor = new AutoscaledPool({+ concurrencySystem: system,+ consumer: { id: 'survivor' },+ runTaskFunction: async () => {+ current++;+ peak = Math.max(peak, current);+ await sleep(5);+ done++;+ current--;+ },+ isFinishedFunction: async () => done >= 10,+ isTaskReadyFunction: async () => done < 10,+ });++ await survivor.run();+ expect(peak).toBe(2);});test('when isFinishedFunction throws', async () => {let count = 0;- const pool = new AutoscaledPool({- maxConcurrency: 1,- runTaskFunction: async () => {- count++;+ const pool = await makePool(+ {+ runTaskFunction: async () => {+ count++;+ },+ isFinishedFunction: async () => {+ throw new Error('some-finished-error');+ },+ isTaskReadyFunction: async () => {+ return count < 1;+ },},- isFinishedFunction: async () => {- throw new Error('some-finished-error');- },- isTaskReadyFunction: async () => {- return count < 1;- },- });+ { maxConcurrency: 1 },+ );await expect(pool.run()).rejects.toThrow('some-finished-error');});test('when isTaskReadyFunction throws', async () => {let count = 0;- const pool = new AutoscaledPool({- maxConcurrency: 1,- runTaskFunction: async () => {- count++;- },- isFinishedFunction: async () => false,- isTaskReadyFunction: async () => {- if (count > 1) throw new Error('some-ready-error');- else return true;+ const pool = await makePool(+ {+ runTaskFunction: async () => {+ count++;+ },+ isFinishedFunction: async () => false,+ isTaskReadyFunction: async () => {+ if (count > 1) throw new Error('some-ready-error');+ else return true;+ },},- });+ { maxConcurrency: 1 },+ );await expect(pool.run()).rejects.toThrow('some-ready-error');});@@ -343,15 +497,17 @@ describe('AutoscaledPool', () => {let count = 0;// Run the pool and close it after 3s.- const pool = new AutoscaledPool({- minConcurrency: 3,- runTaskFunction: async () =>- sleep(1).then(() => {- count++;- }),- isFinishedFunction: isFinished,- isTaskReadyFunction: async () => !(await isFinished()),- });+ const pool = await makePool(+ {+ runTaskFunction: async () =>+ sleep(1).then(() => {+ count++;+ }),+ isFinishedFunction: isFinished,+ isTaskReadyFunction: async () => !(await isFinished()),+ },+ { minConcurrency: 3 },+ );// @ts-expect-error Overwriting readonly private proppool.maybeRunIntervalMillis = 5;@@ -369,26 +525,28 @@ describe('AutoscaledPool', () => {let isTaskReady = true;let counter = 0;- const pool = new AutoscaledPool({- maxConcurrency: 1,- runTaskFunction: async () => {- await sleep(1);- if (counter === 10) {- isTaskReady = false;- setTimeout(() => {- isTaskReady = true;- }, 10);- }- if (counter === 19) {- isTaskReady = false;- isFinished = true;- }- counter++;- finished.push(Date.now());+ const pool = await makePool(+ {+ runTaskFunction: async () => {+ await sleep(1);+ if (counter === 10) {+ isTaskReady = false;+ setTimeout(() => {+ isTaskReady = true;+ }, 10);+ }+ if (counter === 19) {+ isTaskReady = false;+ isFinished = true;+ }+ counter++;+ finished.push(Date.now());+ },+ isFinishedFunction: async () => isFinished,+ isTaskReadyFunction: async () => !isFinished && isTaskReady,},- isFinishedFunction: async () => isFinished,- isTaskReadyFunction: async () => !isFinished && isTaskReady,- });+ { maxConcurrency: 1 },+ );// @ts-expect-error Overwriting readonly private proppool.maybeRunIntervalMillis = 1;await pool.run();@@ -399,23 +557,23 @@ describe('AutoscaledPool', () => {});test('should work with loggingIntervalSecs = null', async () => {- const pool = new AutoscaledPool({- minConcurrency: 1,- maxConcurrency: 100,- runTaskFunction: async () => Promise.resolve(),- isFinishedFunction: async () => Promise.resolve(false),- isTaskReadyFunction: async () => Promise.resolve(true),- loggingIntervalSecs: null,- });- // @ts-expect-error Calling private method- pool.autoscale(() => {});+ const pool = await makePool(+ {+ runTaskFunction: async () => Promise.resolve(),+ isFinishedFunction: async () => Promise.resolve(false),+ isTaskReadyFunction: async () => Promise.resolve(true),+ },+ { minConcurrency: 1, maxConcurrency: 100, loggingIntervalSecs: null },+ );+ // @ts-expect-error Calling private method on the governor+ pool.system._autoscale(() => {});expect(pool.desiredConcurrency).toBe(2);});test('should abort', async () => {let finished = false;let aborted = false;- const pool = new AutoscaledPool({+ const pool = await makePool({runTaskFunction: async () => {if (!aborted) {await pool.abort();@@ -436,7 +594,7 @@ describe('AutoscaledPool', () => {let started = false;let completed = false;- const pool = new AutoscaledPool({+ const pool = await makePool({runTaskFunction: async () => {started = true;await sleep(100);@@ -465,18 +623,20 @@ describe('AutoscaledPool', () => {pauseResolve = res;});- const pool = new AutoscaledPool({- maybeRunIntervalSecs: 0.01,- minConcurrency: 10,- runTaskFunction: async () => {- results.push(count++);- if (count === 20) {- void pool.pause().then(pauseResolve);- }+ const pool = await makePool(+ {+ maybeRunIntervalSecs: 0.01,+ runTaskFunction: async () => {+ results.push(count++);+ if (count === 20) {+ void pool.pause().then(pauseResolve);+ }+ },+ isFinishedFunction: async () => !(count < 50),+ isTaskReadyFunction: async () => count < 50,},- isFinishedFunction: async () => !(count < 50),- isTaskReadyFunction: async () => count < 50,- });+ { minConcurrency: 10 },+ );let finished = false;const runPromise = pool.run();@@ -503,14 +663,15 @@ describe('AutoscaledPool', () => {return 1;};- const pool = new AutoscaledPool({- minConcurrency: 1,- maxConcurrency: 1,- runTaskFunction,- taskTimeoutSecs: 0.1,- isFinishedFunction: async () => false,- isTaskReadyFunction: async () => true,- });+ const pool = await makePool(+ {+ runTaskFunction,+ taskTimeoutSecs: 0.1,+ isFinishedFunction: async () => false,+ isTaskReadyFunction: async () => true,+ },+ { minConcurrency: 1, maxConcurrency: 1 },+ );const now = Date.now();await expect(pool.run()).rejects.toThrow('runTaskFunction timed out after 0.1 seconds.');@@ -525,14 +686,15 @@ describe('AutoscaledPool', () => {finished = true;return 1;};- const pool = new AutoscaledPool({- minConcurrency: 1,- maxConcurrency: 1,- runTaskFunction,- taskTimeoutSecs: 0,- isFinishedFunction: async () => finished,- isTaskReadyFunction: async () => !finished,- });+ const pool = await makePool(+ {+ runTaskFunction,+ taskTimeoutSecs: 0,+ isFinishedFunction: async () => finished,+ isTaskReadyFunction: async () => !finished,+ },+ { minConcurrency: 1, maxConcurrency: 1 },+ );const now = Date.now();await expect(pool.run()).resolves.toBeUndefined();@@ -548,13 +710,14 @@ describe('AutoscaledPool', () => {return 1;};- const pool = new AutoscaledPool({- minConcurrency: 1,- maxConcurrency: 1,- runTaskFunction,- isFinishedFunction: async () => finished,- isTaskReadyFunction: async () => !finished,- });+ const pool = await makePool(+ {+ runTaskFunction,+ isFinishedFunction: async () => finished,+ isTaskReadyFunction: async () => !finished,+ },+ { minConcurrency: 1, maxConcurrency: 1 },+ );const now = Date.now();await expect(pool.run()).resolves.toBeUndefined();@@ -587,17 +750,17 @@ describe('AutoscaledPool', () => {const signal = createFakeLoadSignal('proxyHealth', { isOverloaded: true });let count = 0;- const pool = new AutoscaledPool({- minConcurrency: 1,- maxConcurrency: 10,- runTaskFunction: async () => {- count++;- await sleep(10);+ const pool = await makePool(+ {+ runTaskFunction: async () => {+ count++;+ await sleep(10);+ },+ isFinishedFunction: async () => count >= 50,+ isTaskReadyFunction: async () => count < 50,},- isFinishedFunction: async () => count >= 50,- isTaskReadyFunction: async () => count < 50,- systemStatusOptions: { loadSignals: [signal] },- });+ { minConcurrency: 1, maxConcurrency: 10, loadSignals: { custom: [signal] } },+ );await pool.run();@@ -608,20 +771,20 @@ describe('AutoscaledPool', () => {const signal = createFakeLoadSignal('navTimeout', { overloadedRatio: 0.2, isOverloaded: true });let count = 0;- const pool = new AutoscaledPool({- minConcurrency: 1,- maxConcurrency: 10,- runTaskFunction: async () => {- count++;- await sleep(10);+ const pool = await makePool(+ {+ runTaskFunction: async () => {+ count++;+ await sleep(10);+ },+ isFinishedFunction: async () => count >= 10,+ isTaskReadyFunction: async () => count < 10,},- isFinishedFunction: async () => count >= 10,- isTaskReadyFunction: async () => count < 10,- systemStatusOptions: { loadSignals: [signal] },- });+ { minConcurrency: 1, maxConcurrency: 10, loadSignals: { custom: [signal] } },+ );- // @ts-expect-error Accessing private prop- const status = pool.systemStatus.getCurrentStatus();+ // `getCurrentStatus()` is telemetry on the concrete governor, not part of the pool-facing interface.+ const status = (pool.system as ConcurrencySystem).getCurrentStatus();expect(status.loadSignalInfo?.navTimeout?.isOverloaded).toBe(true);await pool.run();diff --git a/test/core/autoscaling/concurrency_system.test.ts b/test/core/autoscaling/concurrency_system.test.tsnew file mode 100644index 000000000..313f0af92--- /dev/null+++ b/test/core/autoscaling/concurrency_system.test.ts@@ -0,0 +1,708 @@+import type { ConcurrencyConsumer, IConcurrencySystem, LoadSignal, LoadSignalStartContext } from '@crawlee/core';+import { AutoscaledPool, ConcurrencySystem, EventLoopLoadSignal, SnapshotStore } from '@crawlee/core';+import { sleep } from '@crawlee/utils';++import log from '@apify/log';++describe('ConcurrencySystem', () => {+ let logLevel: number;+ beforeAll(() => {+ logLevel = log.getLevel();+ log.setLevel(log.LEVELS.ERROR);+ });++ afterAll(() => {+ log.setLevel(logLevel);+ });++ describe('budget accounting', () => {+ test('hasCapacityForTask() gates on desired concurrency', () => {+ const system = new ConcurrencySystem({ minConcurrency: 1, maxConcurrency: 10, desiredConcurrency: 2 });++ expect(system.hasCapacityForTask()).toBe(true);+ expect(system.tryRegisterTaskStart()).toBe(true);+ expect(system.currentConcurrency).toBe(1);+ expect(system.hasCapacityForTask()).toBe(true);+ expect(system.tryRegisterTaskStart()).toBe(true);+ expect(system.currentConcurrency).toBe(2);+ // Desired concurrency reached - no more room.+ expect(system.hasCapacityForTask()).toBe(false);++ system.registerTaskEnd();+ expect(system.currentConcurrency).toBe(1);+ expect(system.hasCapacityForTask()).toBe(true);+ });++ test('tryRegisterTaskStart() refuses to book past the budget', () => {+ const system = new ConcurrencySystem({ minConcurrency: 1, maxConcurrency: 10, desiredConcurrency: 1 });++ expect(system.tryRegisterTaskStart()).toBe(true);+ // The budget is spent - a booking attempt (e.g. by a second pool sharing the system) must fail+ // atomically instead of overshooting the shared cap.+ expect(system.tryRegisterTaskStart()).toBe(false);+ expect(system.currentConcurrency).toBe(1);++ system.registerTaskEnd();+ expect(system.tryRegisterTaskStart()).toBe(true);+ expect(system.currentConcurrency).toBe(1);+ });++ test('tryRegisterTaskStart() enforces maxTasksPerMinute', () => {+ const system = new ConcurrencySystem({ minConcurrency: 5, maxTasksPerMinute: 2 });++ expect(system.tryRegisterTaskStart()).toBe(true);+ expect(system.tryRegisterTaskStart()).toBe(true);+ // Two starts within the current minute reach the cap - further bookings are refused even though there+ // is concurrency budget to spare, and ending a task changes nothing (the cap counts starts, not slots).+ expect(system.tryRegisterTaskStart()).toBe(false);+ system.registerTaskEnd();+ expect(system.tryRegisterTaskStart()).toBe(false);+ expect(system.currentConcurrency).toBe(1);+ });++ test('maxTasksPerMinute === Infinity never limits', () => {+ const system = new ConcurrencySystem({+ minConcurrency: 1000,+ maxConcurrency: 1000,+ maxTasksPerMinute: Infinity,+ });+ for (let i = 0; i < 1000; i++) expect(system.tryRegisterTaskStart()).toBe(true);+ });+ });++ describe('runtime tuning', () => {+ test('lowering maxConcurrency takes effect immediately', () => {+ const system = new ConcurrencySystem({ minConcurrency: 1, maxConcurrency: 100, desiredConcurrency: 50 });++ // Dispatch gates on `desiredConcurrency`, so a ceiling that left it stranded at 50 would be no ceiling at+ // all - and nothing would ever bring it down, since scaling up is blocked at the ceiling and scaling down+ // needs a load signal to report overload.+ system.maxConcurrency = 10;++ expect(system.maxConcurrency).toBe(10);+ expect(system.desiredConcurrency).toBe(10);++ for (let i = 0; i < 10; i++) expect(system.tryRegisterTaskStart()).toBe(true);+ expect(system.tryRegisterTaskStart()).toBe(false);+ });++ test('raising minConcurrency takes effect immediately', () => {+ const system = new ConcurrencySystem({ minConcurrency: 1, maxConcurrency: 100, desiredConcurrency: 5 });++ system.minConcurrency = 20;++ expect(system.desiredConcurrency).toBe(20);+ });++ test('desiredConcurrency is held within the current bounds', () => {+ const system = new ConcurrencySystem({ minConcurrency: 5, maxConcurrency: 50 });++ system.desiredConcurrency = 500;+ expect(system.desiredConcurrency).toBe(50);++ system.desiredConcurrency = 1;+ expect(system.desiredConcurrency).toBe(5);+ });++ test('the maximum wins a contradictory pair of bounds', () => {+ const system = new ConcurrencySystem({ minConcurrency: 10, maxConcurrency: 100, desiredConcurrency: 50 });++ // `maxConcurrency` is the limit callers set to protect something, so it outranks a now-unreachable minimum.+ system.maxConcurrency = 4;++ expect(system.desiredConcurrency).toBe(4);+ });++ test('the constructor honours both bounds', () => {+ // A ceiling below the requested starting point wins...+ expect(new ConcurrencySystem({ maxConcurrency: 3, desiredConcurrency: 10 }).desiredConcurrency).toBe(3);+ // ...and so does a floor above it, rather than starting below the minimum the caller asked for.+ expect(new ConcurrencySystem({ minConcurrency: 10, desiredConcurrency: 3 }).desiredConcurrency).toBe(10);+ });+ });++ describe('load signals', () => {+ test('signals are told the widest window they will be sampled over', async () => {+ const contexts: LoadSignalStartContext[] = [];+ const signal: LoadSignal = {+ name: 'proxyHealth',+ overloadedRatio: 0.3,+ async start(context) {+ contexts.push(context);+ },+ async stop() {},+ getSample: () => [],+ };++ // The autoscaling window is the wider of the two here.+ const system = new ConcurrencySystem({+ loadSignals: { custom: [signal] },+ currentHistorySecs: 5,+ snapshotHistorySecs: 45,+ });+ await system.start();+ await system.stop();++ expect(contexts).toEqual([{ maxSampleWindowMillis: 45_000 }]);++ // ...and when the gating window is the wider one, retention has to cover that instead.+ const gatingHeavy = new ConcurrencySystem({+ loadSignals: { custom: [signal] },+ currentHistorySecs: 60,+ snapshotHistorySecs: 30,+ });+ await gatingHeavy.start();+ await gatingHeavy.stop();++ expect(contexts[1]).toEqual({ maxSampleWindowMillis: 60_000 });+ });++ test('a custom signal cannot shadow an enabled built-in, but can replace a disabled one', async () => {+ const now = Date.now();++ // The reported `limitRatio` is the signal's own `overloadedRatio`, so an unmistakable value identifies+ // which signal ended up owning the `memInfo` field.+ const memorySignal = (): LoadSignal => ({+ name: 'memInfo',+ overloadedRatio: 0.99,+ async start() {},+ async stop() {},+ getSample: () => [+ { createdAt: new Date(now - 1_000), isOverloaded: true },+ { createdAt: new Date(now), isOverloaded: true },+ ],+ });++ expect(() => new ConcurrencySystem({ loadSignals: { custom: [memorySignal()] } })).toThrow(+ 'Duplicate load signal name "memInfo"',+ );++ const system = new ConcurrencySystem({+ loadSignals: { memory: false, custom: [memorySignal()] },+ });++ const status = system.getCurrentStatus();++ // The replacement owns the vacated field and gates the system, rather than being reported separately.+ expect(status.memInfo).toEqual({ isOverloaded: true, limitRatio: 0.99, actualRatio: 1 });+ expect(status.loadSignalInfo).toBeUndefined();+ expect(status.isSystemIdle).toBe(false);++ // The other three built-ins are untouched — each still reports under its own default ratio.+ expect(status.eventLoopInfo.limitRatio).toBe(0.6);+ expect(status.cpuInfo.limitRatio).toBe(0.4);+ expect(status.clientInfo.limitRatio).toBe(0.3);+ });++ test('built-in signals can be switched off with `false`', async () => {+ const system = new ConcurrencySystem({+ loadSignals: { client: false, eventLoop: false },+ });++ await system.start();+ try {+ // A disabled signal cannot report overload, so the status shows it as idle rather than omitting it.+ const status = system.getCurrentStatus();+ expect(status.clientInfo).toEqual({ isOverloaded: false, limitRatio: 0, actualRatio: 0 });+ expect(status.eventLoopInfo).toEqual({ isOverloaded: false, limitRatio: 0, actualRatio: 0 });+ expect(status.isSystemIdle).toBe(true);++ // The two that stayed on are distinguishable from the placeholders above: `limitRatio` is the+ // reporting signal's own `overloadedRatio`, which no disabled signal is around to supply.+ expect(status.memInfo.limitRatio).toBe(0.2);+ expect(status.cpuInfo.limitRatio).toBe(0.4);+ } finally {+ await system.stop();+ }+ });++ test('switching every built-in signal off leaves the system permanently idle', async () => {+ const system = new ConcurrencySystem({+ loadSignals: { memory: false, eventLoop: false, cpu: false, client: false },+ });++ // @ts-expect-error Accessing private prop+ expect(system.snapshotter.getLoadSignals()).toEqual([]);++ await system.start();+ try {+ expect(system.getCurrentStatus().isSystemIdle).toBe(true);+ expect(system.hasCapacityForTask()).toBe(true);+ } finally {+ await system.stop();+ }+ });++ test('a SnapshotStore-based signal sizes its retention from the start context', async () => {+ const store = new SnapshotStore();+ // Before starting, retention is unbounded so nothing is pruned until the store learns its real window.+ // @ts-expect-error Accessing private prop+ expect(store.historyMillis).toBe(Infinity);++ const system = new ConcurrencySystem({+ loadSignals: {+ custom: [+ {+ name: 'custom',+ overloadedRatio: 0.3,+ async start({ maxSampleWindowMillis }) {+ store.useSampleWindow(maxSampleWindowMillis);+ },+ async stop() {},+ getSample: (ms) => store.getSample(ms),+ },+ ],+ },+ snapshotHistorySecs: 90,+ });+ await system.start();+ await system.stop();++ // No out-of-band knowledge needed - the window came from the system that drives the signal.+ // @ts-expect-error Accessing private prop+ expect(store.historyMillis).toBe(90_000);+ });++ test('a restarted built-in signal is not judged on measurements from before the downtime', async () => {+ const signal = new EventLoopLoadSignal();+ await signal.start({ maxSampleWindowMillis: 30_000 });+ signal.handle(() => {});++ const beforeStop = signal.getSample();+ expect(beforeStop.length).toBeGreaterThan(0);+ const lastBeforeStop = +beforeStop[beforeStop.length - 1].createdAt;++ // Stopping leaves the finished session readable - worth having when working out why a crawl never+ // scaled up.+ await signal.stop();+ expect(signal.getSample()).toEqual(beforeStop);++ await sleep(20);+ await signal.start({ maxSampleWindowMillis: 30_000 });+ signal.handle(() => {});++ // Starting, though, wipes the slate, so neither the delta the handler computes nor the sample the system+ // evaluates can span the downtime. Pruning is relative to the newest snapshot rather than the wall clock,+ // so stale entries would otherwise be evaluated forever as if they were current - and here the gap would+ // be billed to the event loop as blocked time, via exactly the stop/start pair the docs recommend for+ // quiescing a system during a long pause.+ expect(signal.getSample().every((snapshot) => +snapshot.createdAt > lastBeforeStop)).toBe(true);+ expect(signal.getSample().some((snapshot) => snapshot.isOverloaded)).toBe(false);++ await signal.stop();+ });+ });++ describe('lifecycle', () => {+ test('start()/stop() are idempotent', async () => {+ const system = new ConcurrencySystem();+ // @ts-expect-error Accessing private prop+ const snapshotter = system.snapshotter;+ const startSpy = vitest.spyOn(snapshotter, 'start');+ const stopSpy = vitest.spyOn(snapshotter, 'stop');++ // A second start() on an already-running system is a no-op...+ await system.start();+ await system.start();+ expect(startSpy).toHaveBeenCalledTimes(1);++ // ...and so is a second stop().+ await system.stop();+ await system.stop();+ expect(stopSpy).toHaveBeenCalledTimes(1);+ });++ test('stop() is a no-op when never started', async () => {+ const system = new ConcurrencySystem();+ // @ts-expect-error Accessing private prop+ const stopSpy = vitest.spyOn(system.snapshotter, 'stop');+ await system.stop();+ expect(stopSpy).not.toHaveBeenCalled();+ });++ test('isRunning reflects the lifecycle', async () => {+ const system = new ConcurrencySystem();+ expect(system.isRunning).toBe(false);++ await system.start();+ expect(system.isRunning).toBe(true);++ await system.stop();+ expect(system.isRunning).toBe(false);+ });++ test('concurrent start() calls await a single startup', async () => {+ let release!: () => void;+ const blocked = new Promise<void>((resolve) => {+ release = resolve;+ });+ let startCount = 0;++ const signal: LoadSignal = {+ name: 'slowSignal',+ overloadedRatio: 0.5,+ async start() {+ startCount++;+ await blocked;+ },+ async stop() {},+ getSample: () => [],+ };++ const system = new ConcurrencySystem({ loadSignals: { custom: [signal] } });++ const first = system.start();+ const second = system.start();++ // A second owner booting the same shared system has to wait the first boot out - returning early here+ // would let it run tasks against signals that are not collecting yet.+ expect(system.isRunning).toBe(false);++ release();+ await Promise.all([first, second]);++ expect(startCount).toBe(1);+ expect(system.isRunning).toBe(true);++ await system.stop();+ });++ test('a failed startup leaves nothing running and can be retried', async () => {+ let attempts = 0;+ const signal: LoadSignal = {+ name: 'flakySignal',+ overloadedRatio: 0.5,+ async start() {+ attempts++;+ if (attempts === 1) throw new Error('signal boot failed');+ },+ async stop() {},+ getSample: () => [],+ };++ const system = new ConcurrencySystem({ loadSignals: { custom: [signal] } });+ // @ts-expect-error Accessing private prop+ const snapshotterStop = vitest.spyOn(system.snapshotter, 'stop');++ await expect(system.start()).rejects.toThrow('signal boot failed');++ // The built-in signals started before the custom one blew up, so the failed attempt has to unwind them+ // instead of leaving their intervals behind - and must not report a system that is up.+ expect(snapshotterStop).toHaveBeenCalledTimes(1);+ expect(system.isRunning).toBe(false);++ // A retry has to actually retry, rather than resolving instantly against the memoized failure.+ await system.start();+ expect(attempts).toBe(2);+ expect(system.isRunning).toBe(true);++ await system.stop();+ });++ test('start() after stop() restarts the system', async () => {+ const system = new ConcurrencySystem();+ // @ts-expect-error Accessing private prop+ const snapshotterStart = vitest.spyOn(system.snapshotter, 'start');++ await system.start();+ await system.stop();+ await system.start();++ expect(snapshotterStart).toHaveBeenCalledTimes(2);+ expect(system.isRunning).toBe(true);++ await system.stop();+ });++ test('a restart does not inherit the previous session\u2019s per-minute task count', async () => {+ const system = new ConcurrencySystem({ minConcurrency: 5, maxTasksPerMinute: 2 });+ await system.start();++ expect(system.tryRegisterTaskStart()).toBe(true);+ expect(system.tryRegisterTaskStart()).toBe(true);+ expect(system.tryRegisterTaskStart()).toBe(false);+ system.registerTaskEnd();+ system.registerTaskEnd();++ await system.stop();+ await system.start();++ // The ageing interval is cleared while the system is down, so the window never advances past the starts+ // booked before the stop. Without a reset those would still count against "this minute" and trip the cap+ // immediately, however long the downtime was.+ expect(system.tryRegisterTaskStart()).toBe(true);++ await system.stop();+ });++ test('capacity queried on a stopped system warns once per session', async () => {+ const system = new ConcurrencySystem();+ // @ts-expect-error Accessing private prop+ const warning = vitest.spyOn(system.log, 'warning');++ await system.start();+ system.hasCapacityForTask();+ // A running system is the normal case and must stay quiet.+ expect(warning).not.toHaveBeenCalled();++ // A pool only checks `isRunning` when `run()` is called, so a system stopped underneath a live pool is+ // otherwise undetectable - the frozen overload verdict just silently pins its concurrency.+ await system.stop();+ system.hasCapacityForTask();+ system.tryRegisterTaskStart();+ expect(warning).toHaveBeenCalledTimes(1);+ expect(warning.mock.calls[0][0]).toMatch(/not running/);++ // Re-armed by the next boot, so a later mistake is reported again.+ await system.start();+ await system.stop();+ system.hasCapacityForTask();+ expect(warning).toHaveBeenCalledTimes(2);+ });++ test('stop() called mid-startup still tears the system down', async () => {+ let release!: () => void;+ const blocked = new Promise<void>((resolve) => {+ release = resolve;+ });+ const signalStop = vitest.fn(async () => {});++ const signal: LoadSignal = {+ name: 'slowSignal',+ overloadedRatio: 0.5,+ async start() {+ await blocked;+ },+ stop: signalStop,+ getSample: () => [],+ };++ const system = new ConcurrencySystem({ loadSignals: { custom: [signal] } });++ const starting = system.start();+ const stopping = system.stop();++ release();+ await Promise.all([starting, stopping]);++ // The teardown waits the boot out instead of racing it, so whatever the signals registered on the way up+ // is stopped rather than orphaned.+ expect(signalStop).toHaveBeenCalled();+ expect(system.isRunning).toBe(false);+ });++ test('a pool refuses to run against a system that was never started', async () => {+ const system = new ConcurrencySystem();+ const runTaskFunction = vitest.fn(async () => {});++ const pool = new AutoscaledPool({+ concurrencySystem: system,+ consumer: { id: 'pool' },+ runTaskFunction,+ isFinishedFunction: async () => false,+ isTaskReadyFunction: async () => true,+ });++ // Forgetting to start an injected system would pin concurrency for the whole run, so fail loudly+ // before any work happens instead of silently misbehaving.+ await expect(pool.run()).rejects.toThrow(/has not been started/);+ expect(runTaskFunction).not.toHaveBeenCalled();+ });++ test('a pool runs happily against a started system', async () => {+ const system = new ConcurrencySystem();+ await system.start();++ let done = 0;+ const pool = new AutoscaledPool({+ concurrencySystem: system,+ consumer: { id: 'pool' },+ runTaskFunction: async () => {+ done++;+ },+ isFinishedFunction: async () => done > 0,+ isTaskReadyFunction: async () => done === 0,+ });++ await expect(pool.run()).resolves.toBeUndefined();+ await system.stop();+ });++ test('a governor with no startup lifecycle is accepted', async () => {+ // An implementation that needs no starting reports `isRunning: true` and is otherwise free of lifecycle.+ let done = 0;+ const pool = new AutoscaledPool({+ concurrencySystem: {+ desiredConcurrency: 1,+ currentConcurrency: 0,+ isRunning: true,+ hasCapacityForTask: () => true,+ tryRegisterTaskStart: () => true,+ registerTaskEnd: () => {},+ },+ consumer: { id: 'pool' },+ runTaskFunction: async () => {+ done++;+ },+ isFinishedFunction: async () => done > 0,+ isTaskReadyFunction: async () => done === 0,+ });++ await expect(pool.run()).resolves.toBeUndefined();+ });+ });++ describe('shared across pools', () => {+ test('a shared system caps the combined concurrency of two pools', async () => {+ // One shared budget of 4; two pools that would each happily run 4 in parallel.+ const system = new ConcurrencySystem({ minConcurrency: 4, maxConcurrency: 4, desiredConcurrency: 4 });++ let combinedCurrent = 0;+ let combinedPeak = 0;++ const makePool = (id: string, taskCount: number) => {+ let done = 0;+ const runTaskFunction = async () => {+ combinedCurrent++;+ combinedPeak = Math.max(combinedPeak, combinedCurrent);+ await sleep(5);+ done++;+ combinedCurrent--;+ };++ return new AutoscaledPool({+ concurrencySystem: system,+ consumer: { id },+ runTaskFunction,+ isFinishedFunction: async () => done >= taskCount,+ isTaskReadyFunction: async () => done < taskCount,+ });+ };++ // The pool no longer owns the system's lifecycle — as the shared owner, the caller starts and stops it.+ await system.start();+ await Promise.all([makePool('first', 30).run(), makePool('second', 30).run()]);+ await system.stop();++ // The two pools together must never exceed the single shared budget.+ expect(combinedPeak).toBeLessThanOrEqual(4);+ });++ test('a pool that ran out of work finishes while another one saturates the shared budget', async () => {+ // A budget of exactly one slot, so the hog below holds all of it for as long as we let it.+ const system = new ConcurrencySystem({ minConcurrency: 1, maxConcurrency: 1, desiredConcurrency: 1 });++ let releaseHog: () => void;+ const hogReleased = new Promise<void>((resolve) => {+ releaseHog = resolve;+ });++ let hogStarted: () => void;+ const hogRunning = new Promise<void>((resolve) => {+ hogStarted = resolve;+ });++ let hogFinished = false;+ const hog = new AutoscaledPool({+ concurrencySystem: system,+ consumer: { id: 'hog' },+ runTaskFunction: async () => {+ hogStarted();+ await hogReleased;+ hogFinished = true;+ },+ isFinishedFunction: async () => hogFinished,+ isTaskReadyFunction: async () => !hogFinished,+ });++ // Nothing to do and finished from the outset - the only thing that could keep this from resolving is the+ // shared budget, which this pool is not waiting on for anything.+ const drained = new AutoscaledPool({+ concurrencySystem: system,+ consumer: { id: 'drained' },+ runTaskFunction: async () => {},+ isFinishedFunction: async () => true,+ isTaskReadyFunction: async () => false,+ });++ await system.start();+ const hogPromise = hog.run();+ await hogRunning;++ // The single slot is now booked by the hog and stays booked. A borrower with no in-flight work of its own+ // has nothing to wait for, so it must still be able to observe that it is finished.+ await expect(drained.run()).resolves.toBeUndefined();++ releaseHog!();+ await hogPromise;+ await system.stop();+ });++ test('every capacity query and booking tells the governor which pool it is for', async () => {+ const calls: { method: string; consumerId: string }[] = [];+ const record = (method: string, consumer: ConcurrencyConsumer) => {+ calls.push({ method, consumerId: consumer.id });+ };++ const governor: IConcurrencySystem = {+ desiredConcurrency: 2,+ currentConcurrency: 0,+ isRunning: true,+ hasCapacityForTask: (consumer) => {+ record('hasCapacityForTask', consumer);+ return true;+ },+ tryRegisterTaskStart: (consumer) => {+ record('tryRegisterTaskStart', consumer);+ return true;+ },+ registerTaskEnd: (consumer) => record('registerTaskEnd', consumer),+ };++ const makePool = (consumer: ConcurrencyConsumer) => {+ let done = 0;+ return new AutoscaledPool({+ concurrencySystem: governor,+ consumer,+ runTaskFunction: async () => {+ done++;+ },+ isFinishedFunction: async () => done > 0,+ isTaskReadyFunction: async () => done === 0,+ });+ };++ await makePool({ id: 'crawler-a' }).run();+ await makePool({ id: 'crawler-b' }).run();++ // The whole point of the identity: a governor can attribute every query and booking to a pool, rather+ // than just counting them.+ for (const id of ['crawler-a', 'crawler-b']) {+ expect(calls).toContainEqual({ method: 'hasCapacityForTask', consumerId: id });+ expect(calls).toContainEqual({ method: 'tryRegisterTaskStart', consumerId: id });+ expect(calls).toContainEqual({ method: 'registerTaskEnd', consumerId: id });+ }+ });++ test('tuning a shared governor is reflected by every borrowing pool', () => {+ const system = new ConcurrencySystem();++ const makeBorrower = (id: string) =>+ new AutoscaledPool({+ concurrencySystem: system,+ consumer: { id },+ runTaskFunction: async () => {},+ isFinishedFunction: async () => true,+ isTaskReadyFunction: async () => false,+ });++ const first = makeBorrower('first');+ const second = makeBorrower('second');++ // Tuning happens on the governor its owner holds; the pools only report it, read-only.+ system.desiredConcurrency = 42;+ expect(first.desiredConcurrency).toBe(42);+ expect(second.desiredConcurrency).toBe(42);+ });+ });+});diff --git a/test/core/autoscaling/snapshotter.test.ts b/test/core/autoscaling/snapshotter.test.tsindex 2bbfd60b9..35d1ac2f7 100644--- a/test/core/autoscaling/snapshotter.test.ts+++ b/test/core/autoscaling/snapshotter.test.ts@@ -1,6 +1,14 @@import os from 'node:os';-import { Configuration, EventType, LocalEventManager, serviceLocator, Snapshotter } from '@crawlee/core';+import {+ ClientLoadSignal,+ Configuration,+ EventType,+ LocalEventManager,+ MemoryLoadSignal,+ serviceLocator,+ Snapshotter,+} from '@crawlee/core';import type { MemoryInfo } from '../../../packages/core/src/system-info/memory-info.js';import * as utils from '../../../packages/core/src/system-info/memory-info.js';import { sleep } from '@crawlee/utils';@@ -10,6 +18,19 @@ import log from '@apify/log';const toBytes = (x: number) => x * 1024 * 1024;const noop = () => {};+/**+ * Signals are told how much history to retain when they start; the ConcurrencySystem derives this from its configured+ * evaluation windows. These tests drive the Snapshotter directly, so they pass the default window explicitly.+ */+const START_CONTEXT = { maxSampleWindowMillis: 30_000 };++/** Reads a signal's sample by name, the same way production (`SystemStatus`) does. */+const sampleOf = (snapshotter: Snapshotter, name: string, sampleDurationMillis?: number): any[] =>+ snapshotter+ .getLoadSignals()+ .find((signal) => signal.name === name)!+ .getSample(sampleDurationMillis);+describe('Snapshotter', () => {let logLevel: number;beforeAll(() => {@@ -32,7 +53,7 @@ describe('Snapshotter', () => {const snapshotter = new Snapshotter();const events = serviceLocator.getEventManager();await events.init();- await snapshotter.start();+ await snapshotter.start(START_CONTEXT);await sleep(625);apifyClient.stats!.rateLimitErrors = [0, 0, 2];@@ -40,10 +61,10 @@ describe('Snapshotter', () => {await snapshotter.stop();await events.close();- const memorySnapshots = snapshotter.getMemorySample();- const eventLoopSnapshots = snapshotter.getEventLoopSample();- const cpuSnapshots = snapshotter.getCpuSample();- const clientSnapshots = snapshotter.getClientSample();+ const memorySnapshots = sampleOf(snapshotter, 'memInfo');+ const eventLoopSnapshots = sampleOf(snapshotter, 'eventLoopInfo');+ const cpuSnapshots = sampleOf(snapshotter, 'cpuInfo');+ const clientSnapshots = sampleOf(snapshotter, 'clientInfo');expect(Array.isArray(cpuSnapshots)).toBe(true);expect(cpuSnapshots.length).toBeGreaterThanOrEqual(1);@@ -82,15 +103,15 @@ describe('Snapshotter', () => {test('should override default timers', async () => {serviceLocator.setConfiguration(new Configuration({ systemInfoIntervalMillis: 0.1 }));- const snapshotter = new Snapshotter({ eventLoopSnapshotIntervalSecs: 0.05 });+ const snapshotter = new Snapshotter({ eventLoop: { snapshotIntervalSecs: 0.05 } });await serviceLocator.getEventManager().init();- await snapshotter.start();+ await snapshotter.start(START_CONTEXT);await sleep(3 * 1e3);await snapshotter.stop();await serviceLocator.getEventManager().close();- const memorySnapshots = snapshotter.getMemorySample();- const eventLoopSnapshots = snapshotter.getEventLoopSample();- const cpuSnapshots = snapshotter.getCpuSample();+ const memorySnapshots = sampleOf(snapshotter, 'memInfo');+ const eventLoopSnapshots = sampleOf(snapshotter, 'eventLoopInfo');+ const cpuSnapshots = sampleOf(snapshotter, 'cpuInfo');expect(cpuSnapshots.length).toBeGreaterThanOrEqual(5);expect(memorySnapshots.length).toBeGreaterThanOrEqual(5);@@ -110,13 +131,13 @@ describe('Snapshotter', () => {};const snapshotter = new Snapshotter();- await snapshotter.start();+ await snapshotter.start(START_CONTEXT);await emitAndWait(10);await emitAndWait(10);await emitAndWait(10);await emitAndWait(0);await snapshotter.stop();- const cpuSnapshots = snapshotter.getCpuSample();+ const cpuSnapshots = sampleOf(snapshotter, 'cpuInfo');expect(cpuSnapshots).toHaveLength(4);cpuSnapshots.forEach((ss, i) => {@@ -150,7 +171,7 @@ describe('Snapshotter', () => {// Establish a baseline before the Snapshotter starts listening for events.await events.emitSystemInfoEvent(noop);cpusMock.mockClear();- await snapshotter.start();+ await snapshotter.start(START_CONTEXT);await events.emitSystemInfoEvent(noop);@@ -167,7 +188,7 @@ describe('Snapshotter', () => {times.other += 4;await events.emitSystemInfoEvent(noop);- const loopSnapshots = snapshotter.getCpuSample();+ const loopSnapshots = sampleOf(snapshotter, 'cpuInfo');expect(loopSnapshots.length).toBe(5);expect(loopSnapshots[0].isOverloaded).toBe(false);@@ -183,9 +204,9 @@ describe('Snapshotter', () => {test('correctly marks eventLoopOverloaded', () => {const clock = vitest.useFakeTimers();try {- const snapshotter = new Snapshotter({ maxBlockedMillis: 5, eventLoopSnapshotIntervalSecs: 0 });+ const snapshotter = new Snapshotter({ eventLoop: { maxBlockedMillis: 5, snapshotIntervalSecs: 0 } });// @ts-expect-error Accessing private property- const eventLoopSignal = snapshotter.eventLoopSignal;+ const eventLoopSignal = snapshotter.eventLoopSignal!;eventLoopSignal.handle(noop);clock.advanceTimersByTime(1);eventLoopSignal.handle(noop);@@ -195,7 +216,7 @@ describe('Snapshotter', () => {eventLoopSignal.handle(noop);clock.advanceTimersByTime(3);eventLoopSignal.handle(noop);- const loopSnapshots = snapshotter.getEventLoopSample();+ const loopSnapshots = sampleOf(snapshotter, 'eventLoopInfo');expect(loopSnapshots.length).toBe(5);expect(loopSnapshots[0].isOverloaded).toBe(false);@@ -216,11 +237,11 @@ describe('Snapshotter', () => {} as MemoryInfo;vitest.spyOn(utils, 'getMemoryInfo').mockResolvedValue(memoryData);serviceLocator.setConfiguration(new Configuration({ availableMemoryRatio: 1 }));- const snapshotter = new Snapshotter({ maxUsedMemoryRatio: 0.5 });+ const snapshotter = new Snapshotter({ memory: { maxUsedRatio: 0.5 } });// do not initialize the event intervals as we will fire them manuallyvitest.spyOn(LocalEventManager.prototype, 'init').mockImplementation(async () => {});const events = serviceLocator.getEventManager() as LocalEventManager;- await snapshotter.start();+ await snapshotter.start(START_CONTEXT);await events.emitSystemInfoEvent(noop);memoryData.mainProcessBytes = toBytes(2000);@@ -231,7 +252,7 @@ describe('Snapshotter', () => {await events.emitSystemInfoEvent(noop);memoryData.childProcessesBytes = toBytes(1999);await events.emitSystemInfoEvent(noop);- const memorySnapshots = snapshotter.getMemorySample();+ const memorySnapshots = sampleOf(snapshotter, 'memInfo');expect(memorySnapshots.length).toBe(5);expect(memorySnapshots[0].isOverloaded).toBe(false);@@ -259,11 +280,17 @@ describe('Snapshotter', () => {// Mock memory info to be able to inject custom memory measurement data.vitest.spyOn(utils, 'getMemoryInfo').mockResolvedValue(memoryData);serviceLocator.setConfiguration(new Configuration({ availableMemoryRatio: 1 }));- const snapshotter = new Snapshotter({ maxUsedMemoryRatio: 0.5 });++ // The signal logs through a child of the registered logger; collapsing `child()` onto its parent lets the+ // spy below observe it.+ const logger = serviceLocator.getLogger();+ vitest.spyOn(logger, 'child').mockReturnValue(logger);+ const warningSpy = vitest.spyOn(logger, 'warning').mockImplementation(() => {});++ const memorySignal = new MemoryLoadSignal({ maxUsedRatio: 0.5 });const eventManager = serviceLocator.getEventManager() as LocalEventManager;- await snapshotter.start();- const warningSpy = vitest.spyOn(snapshotter.log, 'warning').mockImplementation(() => {});+ await memorySignal.start(START_CONTEXT);// First snapshot - below warning usageawait eventManager.emitSystemInfoEvent(noop);@@ -283,19 +310,18 @@ describe('Snapshotter', () => {warningSpy.mockReset();vitest.restoreAllMocks();- await snapshotter.stop();+ await memorySignal.stop();});- test('correctly marks clientOverloaded', () => {+ test('correctly marks clientOverloaded', async () => {// mock client dataconst apifyClient = serviceLocator.getStorageBackend();const oldStats = apifyClient.stats;apifyClient.stats = {} as any;apifyClient.stats!.rateLimitErrors = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];- const snapshotter = new Snapshotter({ maxClientErrors: 1 });- // @ts-expect-error Accessing private property- const clientSignal = snapshotter.clientSignal;+ const clientSignal = new ClientLoadSignal({ maxErrors: 1 });+ await clientSignal.start(START_CONTEXT);clientSignal.handle(noop);apifyClient.stats!.rateLimitErrors = [1, 1, 1, 0, 0, 0, 0, 0, 0, 0];clientSignal.handle(noop);@@ -304,7 +330,9 @@ describe('Snapshotter', () => {apifyClient.stats!.rateLimitErrors = [100, 24, 4, 2, 0, 0, 0, 0, 0, 0];clientSignal.handle(noop);- const clientSnapshots = snapshotter.getClientSample();+ // `start()` takes a baseline snapshot immediately (the measuring interval fires on its first tick), so the+ // four driven below follow it.+ const clientSnapshots = clientSignal.getSample().slice(1);expect(clientSnapshots.length).toBe(4);expect(clientSnapshots[0].isOverloaded).toBe(false);@@ -312,24 +340,25 @@ describe('Snapshotter', () => {expect(clientSnapshots[2].isOverloaded).toBe(false);expect(clientSnapshots[3].isOverloaded).toBe(true);+ await clientSignal.stop();apifyClient.stats = oldStats;});- test('.get[.*]Sample limits amount of samples', async () => {+ test('a signal sample is limited by the requested duration', async () => {const SAMPLE_SIZE_MILLIS = 120;serviceLocator.setConfiguration(new Configuration({ systemInfoIntervalMillis: 10 }));const snapshotter = new Snapshotter({- eventLoopSnapshotIntervalSecs: 0.01,+ eventLoop: { snapshotIntervalSecs: 0.01 },});- await snapshotter.start();+ await snapshotter.start(START_CONTEXT);await serviceLocator.getEventManager().init();await sleep(1.5e3);await snapshotter.stop();await serviceLocator.getEventManager().close();- const memorySnapshots = snapshotter.getMemorySample();- const eventLoopSnapshots = snapshotter.getEventLoopSample();- const memorySample = snapshotter.getMemorySample(SAMPLE_SIZE_MILLIS);- const eventLoopSample = snapshotter.getEventLoopSample(SAMPLE_SIZE_MILLIS);+ const memorySnapshots = sampleOf(snapshotter, 'memInfo');+ const eventLoopSnapshots = sampleOf(snapshotter, 'eventLoopInfo');+ const memorySample = sampleOf(snapshotter, 'memInfo', SAMPLE_SIZE_MILLIS);+ const eventLoopSample = sampleOf(snapshotter, 'eventLoopInfo', SAMPLE_SIZE_MILLIS);expect(memorySnapshots.length).toBeGreaterThan(memorySample.length);expect(eventLoopSnapshots.length).toBeGreaterThan(eventLoopSample.length);@@ -384,10 +413,13 @@ describe('Snapshotter', () => {});}- const snapshotter = new Snapshotter({ configuration });+ // The signal reads its configuration when it starts, from wherever the services are registered.+ serviceLocator.setConfiguration(configuration);++ const memorySignal = new MemoryLoadSignal();vitest.spyOn(LocalEventManager.prototype, 'init').mockImplementation(async () => {});const eventManager = serviceLocator.getEventManager() as LocalEventManager;- await snapshotter.start();+ await memorySignal.start(START_CONTEXT);// First snapshot - full usage of the memory, should be overloaded in both modesawait eventManager.emitSystemInfoEvent(noop);@@ -397,12 +429,12 @@ describe('Snapshotter', () => {memoryData.freeBytes = memoryData.totalBytes - actualMemoryUsage;await eventManager.emitSystemInfoEvent(noop);- const memorySnapshots = snapshotter.getMemorySample();+ const memorySnapshots = memorySignal.getSample();expect(memorySnapshots).toHaveLength(2);expect(memorySnapshots[0].isOverloaded).toBe(true);expect(memorySnapshots[1].isOverloaded).toBe(!dynamic);- await snapshotter.stop();+ await memorySignal.stop();},);});diff --git a/test/core/autoscaling/system_status.test.ts b/test/core/autoscaling/system_status.test.tsindex 1cbb2965c..c6e67cecb 100644--- a/test/core/autoscaling/system_status.test.ts+++ b/test/core/autoscaling/system_status.test.ts@@ -1,4 +1,5 @@-import { Snapshotter, SystemStatus } from '@crawlee/core';+import type { LoadSignal, LoadSnapshot } from '@crawlee/core';+import { SystemStatus } from '@crawlee/core';import log from '@apify/log';@@ -13,10 +14,12 @@ describe('SystemStatus', () => {log.setLevel(logLevel);});- function mockSignal(name: string, snapshots: any[]) {+ // The per-signal overloaded ratio now lives on the signal itself (SystemStatus no longer overrides it), so the+ // mock signal carries it directly. Default 0 means "any overloaded snapshot trips it", matching the earlier tests.+ function mockSignal(name: string, snapshots: any[], overloadedRatio = 0) {return {name,- overloadedRatio: 0, // overridden by SystemStatusOptions anyway+ overloadedRatio,getSample(sampleDurationMillis?: number) {return sampleDurationMillis ? snapshots.slice(-sampleDurationMillis) : snapshots;},@@ -31,14 +34,17 @@ describe('SystemStatus', () => {readonly loopSnapshots: any[],readonly cpuSnapshots: any[],readonly clientSnapshots: any[],+ readonly overloadedRatios: Partial<+ Record<'memInfo' | 'eventLoopInfo' | 'cpuInfo' | 'clientInfo', number>+ > = {},) {}getLoadSignals() {return [- mockSignal('memInfo', this.memSnapshots),- mockSignal('eventLoopInfo', this.loopSnapshots),- mockSignal('cpuInfo', this.cpuSnapshots),- mockSignal('clientInfo', this.clientSnapshots),+ mockSignal('memInfo', this.memSnapshots, this.overloadedRatios.memInfo),+ mockSignal('eventLoopInfo', this.loopSnapshots, this.overloadedRatios.eventLoopInfo),+ mockSignal('cpuInfo', this.cpuSnapshots, this.overloadedRatios.cpuInfo),+ mockSignal('clientInfo', this.clientSnapshots, this.overloadedRatios.clientInfo),];}@@ -140,61 +146,47 @@ describe('SystemStatus', () => {test('should overload when threshold is crossed', () => {const snaps = generateSnapsSync(50, true);- const mock = new MockSnapshotter(snaps, snaps, snaps, snaps) as any;+ const ratios = (r: number) => ({ memInfo: r, eventLoopInfo: r, cpuInfo: r, clientInfo: r });// At exactly 0.5, the 50% overloaded sample should NOT trigger (uses >)let systemStatus = new SystemStatus({- snapshotter: mock,- maxMemoryOverloadedRatio: 0.5,- maxEventLoopOverloadedRatio: 0.5,- maxCpuOverloadedRatio: 0.5,- maxClientOverloadedRatio: 0.5,+ snapshotter: new MockSnapshotter(snaps, snaps, snaps, snaps, ratios(0.5)) as any,});expect(systemStatus.getCurrentStatus().isSystemIdle).toBe(true);expect(systemStatus.getHistoricalStatus().isSystemIdle).toBe(true);// Drop all thresholds below 0.5 → all four overloadedsystemStatus = new SystemStatus({- snapshotter: mock,- maxMemoryOverloadedRatio: 0.49,- maxEventLoopOverloadedRatio: 0.49,- maxCpuOverloadedRatio: 0.49,- maxClientOverloadedRatio: 0.49,+ snapshotter: new MockSnapshotter(snaps, snaps, snaps, snaps, ratios(0.49)) as any,});expect(systemStatus.getCurrentStatus().isSystemIdle).toBe(false);expect(systemStatus.getHistoricalStatus().isSystemIdle).toBe(false);// Memory & eventLoop at threshold, CPU & client below → still overloadedsystemStatus = new SystemStatus({- snapshotter: mock,- maxMemoryOverloadedRatio: 0.5,- maxEventLoopOverloadedRatio: 0.5,- maxCpuOverloadedRatio: 0.49,- maxClientOverloadedRatio: 0.49,+ snapshotter: new MockSnapshotter(snaps, snaps, snaps, snaps, {+ memInfo: 0.5,+ eventLoopInfo: 0.5,+ cpuInfo: 0.49,+ clientInfo: 0.49,+ }) as any,});expect(systemStatus.getCurrentStatus().isSystemIdle).toBe(false);expect(systemStatus.getHistoricalStatus().isSystemIdle).toBe(false);// All thresholds well above → idlesystemStatus = new SystemStatus({- snapshotter: mock,- maxMemoryOverloadedRatio: 1,- maxEventLoopOverloadedRatio: 1,- maxCpuOverloadedRatio: 1,- maxClientOverloadedRatio: 1,+ snapshotter: new MockSnapshotter(snaps, snaps, snaps, snaps, ratios(1)) as any,});expect(systemStatus.getCurrentStatus().isSystemIdle).toBe(true);expect(systemStatus.getHistoricalStatus().isSystemIdle).toBe(true);});test('should show different values for now and lately', () => {+ const ratios = { memInfo: 0.5, eventLoopInfo: 0.5, cpuInfo: 0.5, clientInfo: 0.5 };let snaps = generateSnapsSync(95, false);let systemStatus = new SystemStatus({- snapshotter: new MockSnapshotter(snaps, snaps, snaps, snaps) as any,- maxMemoryOverloadedRatio: 0.5,- maxEventLoopOverloadedRatio: 0.5,- maxCpuOverloadedRatio: 0.5,- maxClientOverloadedRatio: 0.5,+ snapshotter: new MockSnapshotter(snaps, snaps, snaps, snaps, ratios) as any,});// @ts-expect-error Overwriting readonly private prop@@ -214,11 +206,7 @@ describe('SystemStatus', () => {snaps = generateSnapsSync(95, true);systemStatus = new SystemStatus({- snapshotter: new MockSnapshotter(snaps, snaps, snaps, snaps) as any,- maxMemoryOverloadedRatio: 0.5,- maxEventLoopOverloadedRatio: 0.5,- maxCpuOverloadedRatio: 0.5,- maxClientOverloadedRatio: 0.5,+ snapshotter: new MockSnapshotter(snaps, snaps, snaps, snaps, ratios) as any,});// @ts-expect-error Overwriting readonly private prop@@ -237,9 +225,87 @@ describe('SystemStatus', () => {expect(systemStatus.getHistoricalStatus().isSystemIdle).toBe(false);});- test('creates a snapshotter when none is passed', () => {- const systemStatus = new SystemStatus();- // @ts-expect-error Accessing private prop- expect(systemStatus.snapshotter).toBeInstanceOf(Snapshotter);+ test('the historical window is requested explicitly, so a long-memory custom signal cannot widen it', () => {+ const now = Date.now();+ // A custom signal that remembers far more than the configured window: overloaded a minute ago, fine since.+ const timestampedSignal: LoadSignal = {+ name: 'proxyHealth',+ overloadedRatio: 0,+ async start() {},+ async stop() {},+ getSample(sampleDurationMillis?: number) {+ // A sustained overload about a minute ago, healthy ever since. (The sample evaluation weights each+ // interval by the flag of the snapshot that ends it, so the overload needs more than one snapshot.)+ const snapshots: LoadSnapshot[] = [+ { createdAt: new Date(now - 60_000), isOverloaded: true },+ { createdAt: new Date(now - 59_000), isOverloaded: true },+ { createdAt: new Date(now - 58_000), isOverloaded: true },+ { createdAt: new Date(now - 1_000), isOverloaded: false },+ ];++ if (!sampleDurationMillis) return snapshots;+ const cutoff = now - sampleDurationMillis;+ return snapshots.filter((snapshot) => +snapshot.createdAt >= cutoff);+ },+ };++ const fine = generateSnapsSync(100, false);+ const systemStatus = new SystemStatus({+ snapshotter: new MockSnapshotter(fine, fine, fine, fine, {}) as any,+ loadSignals: [timestampedSignal],+ historySecs: 30,+ });++ // The minute-old overload falls outside the 30s window, so it must not drag the historical status down.+ expect(systemStatus.getHistoricalStatus().isSystemIdle).toBe(true);++ // Widening the window past the old snapshot brings the overload back into view.+ const widened = new SystemStatus({+ snapshotter: new MockSnapshotter(fine, fine, fine, fine, {}) as any,+ loadSignals: [timestampedSignal],+ historySecs: 120,+ });+ expect(widened.getHistoricalStatus().isSystemIdle).toBe(false);+ });++ describe('duplicate signal names', () => {+ const fine = generateSnapsSync(100, false);+ const snapshotter = () => new MockSnapshotter(fine, fine, fine, fine, {}) as any;++ it('rejects a custom signal that shadows an enabled built-in', () => {+ // Used to silently run alongside the built-in while overwriting its SystemInfo field, so the reported+ // memInfo could claim memory was fine while the built-in held concurrency down.+ expect(+ () => new SystemStatus({ snapshotter: snapshotter(), loadSignals: [mockSignal('memInfo', fine)] }),+ ).toThrow(/Duplicate load signal name "memInfo".*loadSignals: \{ memory: false \}/s);+ });++ it('rejects two custom signals sharing a name', () => {+ expect(+ () =>+ new SystemStatus({+ snapshotter: snapshotter(),+ loadSignals: [mockSignal('proxyHealth', fine), mockSignal('proxyHealth', fine)],+ }),+ ).toThrow(/Duplicate load signal name "proxyHealth".*rename one of them/s);+ });++ it('allows a custom signal to take over the name of a disabled built-in', () => {+ // The supported replacement route: switch the built-in off, keep its SystemInfo field reported by yours.+ const withoutMemory = {+ getLoadSignals: () => snapshotter().getLoadSignals().slice(1),+ } as any;++ const overloaded = generateSnapsSync(100, true);+ const systemStatus = new SystemStatus({+ snapshotter: withoutMemory,+ loadSignals: [mockSignal('memInfo', overloaded)],+ });++ const status = systemStatus.getCurrentStatus();+ expect(status.isSystemIdle).toBe(false);+ expect(status.memInfo.isOverloaded).toBe(true);+ expect(status.loadSignalInfo).toBeUndefined();+ });});});diff --git a/test/core/crawlers/basic_crawler.test.ts b/test/core/crawlers/basic_crawler.test.tsindex fa2359d11..c8da38bdb 100644--- a/test/core/crawlers/basic_crawler.test.ts+++ b/test/core/crawlers/basic_crawler.test.ts@@ -22,7 +22,7 @@ import {serviceLocator,SessionPool,} from '@crawlee/basic';-import { Dataset, MemoryStorageBackend, RequestState, SessionPool, Statistics } from '@crawlee/core';+import { ConcurrencySystem, Dataset, MemoryStorageBackend, RequestState, SessionPool, Statistics } from '@crawlee/core';import type { ISession, ProxyInfo } from '@crawlee/types';import type { Dictionary } from '@crawlee/utils';import { RobotsTxtFile, sleep } from '@crawlee/utils';@@ -167,12 +167,115 @@ describe('BasicCrawler', () => {await basicCrawler.run();- expect(basicCrawler.autoscaledPool!.minConcurrency).toBe(25);+ expect((basicCrawler.autoscaledPool!.system as ConcurrencySystem).minConcurrency).toBe(25);expect(processed).toEqual(sourcesCopy);expect(await requestList.isFinished()).toBe(true);expect(await requestList.isEmpty()).toBe(true);});+ test('folds a supplied concurrencySystem into its pool and never tears the system down', async () => {+ const sources = [...Array(20).keys()].map((index) => ({ url: `https://example.com/${index}` }));+ const requestList = await RequestList.open(null, sources);++ const processed: string[] = [];+ const requestHandler: RequestHandler = async ({ request }) => {+ await sleep(1);+ processed.push(request.url);+ };++ const system = new ConcurrencySystem({ minConcurrency: 7, maxConcurrency: 7 });+ const startSpy = vitest.spyOn(system, 'start');+ const stopSpy = vitest.spyOn(system, 'stop');++ const basicCrawler = new BasicCrawler({+ requestList,+ concurrencySystem: system,+ requestHandler,+ });++ // The caller owns a supplied system's lifecycle.+ await system.start();+ await basicCrawler.run();+ await system.stop();++ // The crawler built its own pool but wired the shared governor into it.+ expect(basicCrawler.autoscaledPool!.system).toBe(system);+ expect((basicCrawler.autoscaledPool!.system as ConcurrencySystem).minConcurrency).toBe(7);+ // Work actually ran (the crawler kept its own task loop).+ expect(processed).toHaveLength(20);+ // The crawler never touched the borrowed system's lifecycle — only our two explicit calls did.+ expect(startSpy).toHaveBeenCalledTimes(1);+ expect(stopSpy).toHaveBeenCalledTimes(1);+ });++ test('identifies itself to its concurrency system by its own id', async () => {+ const system = new ConcurrencySystem({ minConcurrency: 2, maxConcurrency: 2 });+ const bookings = vitest.spyOn(system, 'tryRegisterTaskStart');++ const makeCrawler = async (id: string) => {+ const requestList = await RequestList.open(`identified-${id}`, [{ url: `https://example.com/${id}` }]);+ return new BasicCrawler({ id, requestList, concurrencySystem: system, requestHandler: async () => {} });+ };++ const [a, b] = await Promise.all([makeCrawler('crawler-a'), makeCrawler('crawler-b')]);++ await system.start();+ await Promise.all([a.run(), b.run()]);+ await system.stop();++ // A shared governor is told which crawler each booking is for, under the same id the crawler is known by+ // elsewhere - so an allocating implementation can keep them from starving each other.+ const bookedFor = new Set(bookings.mock.calls.map(([consumer]) => consumer?.id));+ expect(bookedFor).toEqual(new Set(['crawler-a', 'crawler-b']));+ });++ test.each(['minConcurrency', 'maxConcurrency', 'maxRequestsPerMinute'] as const)(+ 'throws when %s is combined with a supplied concurrencySystem',+ (shortcut) => {+ expect(+ () =>+ new BasicCrawler({+ concurrencySystem: new ConcurrencySystem(),+ [shortcut]: 1,+ requestHandler: async () => {},+ }),+ ).toThrow(/cannot be combined with `concurrencySystem`/);+ },+ );++ test('two crawlers sharing a ConcurrencySystem cap their combined concurrency', async () => {+ const system = new ConcurrencySystem({ minConcurrency: 3, maxConcurrency: 3, desiredConcurrency: 3 });++ let combinedCurrent = 0;+ let combinedPeak = 0;++ const makeCrawler = async (offset: number) => {+ const sources = [...Array(30).keys()].map((index) => ({ url: `https://example.com/${offset}-${index}` }));+ const requestList = await RequestList.open(`shared-${offset}`, sources);++ const requestHandler: RequestHandler = async () => {+ combinedCurrent++;+ combinedPeak = Math.max(combinedPeak, combinedCurrent);+ await sleep(3);+ combinedCurrent--;+ };++ return new BasicCrawler({+ requestList,+ concurrencySystem: system,+ requestHandler,+ });+ };++ const [a, b] = await Promise.all([makeCrawler(0), makeCrawler(1)]);+ // The shared system is the caller's to run — the crawlers borrow it and never touch its lifecycle.+ await system.start();+ await Promise.all([a.run(), b.run()]);+ await system.stop();++ expect(combinedPeak).toBeLessThanOrEqual(3);+ });+test('should allow using run method multiple times', async () => {const sources = [...Array(100).keys()].map((index) => `https://example.com/${index}`);const sourcesCopy = JSON.parse(JSON.stringify(sources));@@ -196,6 +299,50 @@ describe('BasicCrawler', () => {expect(processed).toHaveLength(sourcesCopy.length * 3);});+ test('builds a fresh owned ConcurrencySystem for every run', async () => {+ const crawler = new BasicCrawler({+ requestHandler: async () => {},+ });++ await crawler.run(['https://example.com/1']);+ const firstSystem = crawler.autoscaledPool!.system as ConcurrencySystem;+ // Simulate scaling state left behind by the first run.+ firstSystem.desiredConcurrency = 42;++ await crawler.run(['https://example.com/2']);+ const secondSystem = crawler.autoscaledPool!.system;++ // The crawler-owned governor is rebuilt per run, so no previous-run state (resource snapshots,+ // autoscaled desired concurrency, per-minute task counts) can distort the next run's scaling.+ expect(secondSystem).not.toBe(firstSystem);+ // The rebuilt governor starts over from the default desired concurrency (the immediate autoscale tick on+ // start may already have nudged it up a step) instead of inheriting the previous run's value.+ expect(secondSystem.desiredConcurrency).toBeLessThanOrEqual(2);+ });++ test('stops the owned ConcurrencySystem when startup fails after it was started', async () => {+ const crawler = new BasicCrawler({+ requestHandler: async () => {},+ });++ const failure = new Error('Could not open the request queue');+ // `_init()` starts the concurrency system before it resolves the request manager, so this fails after the+ // system's intervals are already ticking.+ const getRequestManager = vitest+ .spyOn(crawler, 'getRequestManager')+ .mockImplementation(async () => Promise.reject(failure));++ // No initial requests — `addRequests()` would resolve the request manager before `_init()` even runs.+ await expect(crawler.run()).rejects.toThrow(failure);++ // The intervals would otherwise keep the event loop alive for the rest of the process's life.+ expect((crawler.autoscaledPool!.system as ConcurrencySystem).isRunning).toBe(false);++ // A failed startup is not a run, so the crawler must not stay wedged as `running`.+ getRequestManager.mockRestore();+ await crawler.run(['https://example.com/2']);+ });+test('should process 4 requests total when calling run() twice with maxRequestsPerCrawl: 2', async () => {const processed: { url: string }[] = [];@@ -426,62 +573,43 @@ describe('BasicCrawler', () => {expect(generatedRequests[1].crawlDepth).toBe(4);});- test('should correctly combine shorthand and full length options', async () => {- const shorthandOptions = {- minConcurrency: 123,- maxConcurrency: 456,- maxRequestsPerMinute: 789,- };-- const autoscaledPoolOptions = {- minConcurrency: 16,- maxConcurrency: 32,- maxTasksPerMinute: 64,- };-- const collectResults = (crawler: BasicCrawler): typeof shorthandOptions | typeof autoscaledPoolOptions => {- return {- minConcurrency: crawler.autoscaledPool!.minConcurrency,- maxConcurrency: crawler.autoscaledPool!.maxConcurrency,- // eslint-disable-next-line dot-notation -- accessing a private member- maxRequestsPerMinute: crawler.autoscaledPool!['maxTasksPerMinute'],- // eslint-disable-next-line dot-notation- maxTasksPerMinute: crawler.autoscaledPool!['maxTasksPerMinute'],- };- };-+ test('concurrency shortcuts configure the default system; an injected system is used as-is', async () => {const requestList = await RequestList.open(null, []);const requestHandler = async () => {};- const results = await Promise.all(- [- new BasicCrawler({- requestList,- requestHandler,- ...shorthandOptions,- }),- new BasicCrawler({- requestList,- requestHandler,- autoscaledPoolOptions,- }),- new BasicCrawler({- requestList,- requestHandler,- ...shorthandOptions,- autoscaledPoolOptions,- }),- ].map(async (c) => {- await c.run();- return collectResults(c);- }),- );+ const collect = (crawler: BasicCrawler) => ({+ minConcurrency: (crawler.autoscaledPool!.system as ConcurrencySystem).minConcurrency,+ maxConcurrency: (crawler.autoscaledPool!.system as ConcurrencySystem).maxConcurrency,+ // eslint-disable-next-line dot-notation -- private member on the governor+ maxTasksPerMinute: (crawler.autoscaledPool!.system as ConcurrencySystem)['maxTasksPerMinute'],+ });- expect(results[0]).toEqual(expect.objectContaining(shorthandOptions));+ // Shortcuts feed the default ConcurrencySystem the crawler builds.+ const shortcuts = new BasicCrawler({+ requestList,+ requestHandler,+ minConcurrency: 123,+ maxConcurrency: 456,+ maxRequestsPerMinute: 789,+ });++ // An injected system carries its own config (the shortcuts are rejected alongside one, see above).+ const injectedSystem = new ConcurrencySystem({ minConcurrency: 16, maxConcurrency: 32, maxTasksPerMinute: 64 });+ const injected = new BasicCrawler({+ requestList,+ requestHandler,+ concurrencySystem: injectedSystem,+ });- expect(results[1]).toEqual(expect.objectContaining(autoscaledPoolOptions));+ // An injected system is ours to run - the crawler refuses to run against one that was never started.+ await injectedSystem.start();+ await Promise.all([shortcuts.run(), injected.run()]);+ await injectedSystem.stop();- expect(results[2]).toEqual(expect.objectContaining(shorthandOptions));+ expect(collect(shortcuts)).toEqual({ minConcurrency: 123, maxConcurrency: 456, maxTasksPerMinute: 789 });+ expect(collect(injected)).toEqual({ minConcurrency: 16, maxConcurrency: 32, maxTasksPerMinute: 64 });+ // The injected system is the very instance the pool uses.+ expect(injected.autoscaledPool!.system).toBe(injectedSystem);});test('auto-saved state object', async () => {@@ -1123,9 +1251,9 @@ describe('BasicCrawler', () => {const basicCrawler = new BasicCrawler({requestQueue,+ minConcurrency: 1,+ maxConcurrency: 1,autoscaledPoolOptions: {- minConcurrency: 1,- maxConcurrency: 1,isFinishedFunction: async () => {isFinishedFunctionCalled = true;return Promise.resolve(isFinished);diff --git a/test/core/crawlers/browser_crawler.test.ts b/test/core/crawlers/browser_crawler.test.tsindex 1bbd4080c..a958600c8 100644--- a/test/core/crawlers/browser_crawler.test.ts+++ b/test/core/crawlers/browser_crawler.test.ts@@ -11,6 +11,7 @@ import {import {bindMethodsToServiceLocator,BLOCKED_STATUS_CODES,+ type ConcurrencySystem,MemoryStorageBackend,serviceLocator,ServiceLocator,@@ -107,7 +108,7 @@ describe('BrowserCrawler', () => {await browserCrawler.run();- expect(browserCrawler.autoscaledPool!.minConcurrency).toBe(1);+ expect((browserCrawler.autoscaledPool!.system as ConcurrencySystem).minConcurrency).toBe(1);expect(processed).toHaveLength(6);expect(failed).toHaveLength(0);diff --git a/test/core/crawlers/cheerio_crawler.test.ts b/test/core/crawlers/cheerio_crawler.test.tsindex 3753c0ae4..56df452b7 100644--- a/test/core/crawlers/cheerio_crawler.test.ts+++ b/test/core/crawlers/cheerio_crawler.test.ts@@ -11,7 +11,13 @@ import {RequestList,Session,} from '@crawlee/cheerio';-import { BaseCrawleeLogger, MemoryStorageBackend, serviceLocator, SessionPool } from '@crawlee/core';+import {+ BaseCrawleeLogger,+ type ConcurrencySystem,+ MemoryStorageBackend,+ serviceLocator,+ SessionPool,+} from '@crawlee/core';import { ImpitHttpClient } from '@crawlee/impit-client';import type { ISession, ProxyInfo } from '@crawlee/types';import type { Dictionary } from '@crawlee/utils';@@ -101,7 +107,7 @@ describe('CheerioCrawler', () => {await cheerioCrawler.run();- expect(cheerioCrawler.autoscaledPool!.minConcurrency).toBe(2);+ expect((cheerioCrawler.autoscaledPool!.system as ConcurrencySystem).minConcurrency).toBe(2);expect(processed).toHaveLength(4);expect(failed).toHaveLength(0);@@ -134,7 +140,7 @@ describe('CheerioCrawler', () => {await cheerioCrawler.run();- expect(cheerioCrawler.autoscaledPool!.minConcurrency).toBe(2);+ expect((cheerioCrawler.autoscaledPool!.system as ConcurrencySystem).minConcurrency).toBe(2);expect(processed).toHaveLength(4);expect(failed).toHaveLength(0);@@ -170,7 +176,7 @@ describe('CheerioCrawler', () => {await cheerioCrawler.run();- expect(cheerioCrawler.autoscaledPool!.minConcurrency).toBe(2);+ expect((cheerioCrawler.autoscaledPool!.system as ConcurrencySystem).minConcurrency).toBe(2);expect(processed).toHaveLength(4);expect(failed).toHaveLength(0);@@ -552,7 +558,7 @@ describe('CheerioCrawler', () => {await cheerioCrawler.run();- expect(cheerioCrawler.autoscaledPool!.minConcurrency).toBe(2);+ expect((cheerioCrawler.autoscaledPool!.system as ConcurrencySystem).minConcurrency).toBe(2);expect(failed).toHaveLength(0);});@@ -573,7 +579,7 @@ describe('CheerioCrawler', () => {await cheerioCrawler.run();- expect(cheerioCrawler.autoscaledPool!.minConcurrency).toBe(2);+ expect((cheerioCrawler.autoscaledPool!.system as ConcurrencySystem).minConcurrency).toBe(2);expect(failed).toHaveLength(4);});diff --git a/test/core/crawlers/http_crawler.test.ts b/test/core/crawlers/http_crawler.test.tsindex fb7f69b83..debb2e124 100644--- a/test/core/crawlers/http_crawler.test.ts+++ b/test/core/crawlers/http_crawler.test.ts@@ -2,8 +2,9 @@ import http from 'node:http';import type { AddressInfo } from 'node:net';import { Readable } from 'node:stream';+import type { ConcurrencySystemOptions } from '@crawlee/core';import { MemoryStorageBackend, serviceLocator } from '@crawlee/core';-import { HttpCrawler, SessionPool } from '@crawlee/http';+import { ConcurrencySystem, HttpCrawler, SessionPool } from '@crawlee/http';import { ResponseWithUrl } from '@crawlee/http-client';import iconv from 'iconv-lite';@@ -125,6 +126,65 @@ test('works', async () => {expect(results[0].includes('Example Domain')).toBeTruthy();});+/**+ * Records the budget of the {@apilink ConcurrencySystem} the crawler builds for itself, *as configured* — i.e. before+ * `start()` arms the autoscaler.+ */+class ObservableHttpCrawler extends HttpCrawler {+ /** The default governor's budget at the moment the crawler built it. */+ asConfigured?: { desiredConcurrency: number; maxConcurrency: number };++ protected override createDefaultConcurrencySystem(options: ConcurrencySystemOptions): ConcurrencySystem {+ const system = super.createDefaultConcurrencySystem(options);++ this.asConfigured = {+ desiredConcurrency: system.desiredConcurrency,+ maxConcurrency: system.maxConcurrency,+ };++ return system;+ }+}++test('builds an HTTP-optimized default ConcurrencySystem and owns its lifecycle', async () => {+ const startSpy = vitest.spyOn(ConcurrencySystem.prototype, 'start');+ const stopSpy = vitest.spyOn(ConcurrencySystem.prototype, 'stop');++ try {+ const crawler = new ObservableHttpCrawler({+ maxRequestRetries: 0,+ requestHandler: () => {},+ });++ await crawler.run([url]);++ // The HTTP-optimized starting concurrency made it into the default system...+ expect(crawler.asConfigured!.desiredConcurrency).toBe(10);+ // ...and the crawler owns the default system, so it drives its lifecycle.+ expect(startSpy).toHaveBeenCalledTimes(1);+ expect(stopSpy).toHaveBeenCalledTimes(1);+ } finally {+ startSpy.mockRestore();+ stopSpy.mockRestore();+ }+});++test('concurrency shortcuts coexist with the HTTP-optimized defaults', async () => {+ const crawler = new ObservableHttpCrawler({+ maxConcurrency: 5,+ maxRequestRetries: 0,+ requestHandler: () => {},+ });++ await crawler.run([url]);++ // The shortcut applies, and the governor really is the one wired into the pool (autoscaling never moves the+ // ceiling, so this one is safe to read after the run)...+ expect((crawler.autoscaledPool!.system as ConcurrencySystem).maxConcurrency).toBe(5);+ // ...without discarding the HTTP-optimized starting concurrency, which the max then caps.+ expect(crawler.asConfigured!.desiredConcurrency).toBe(5);+});+test('parseWithCheerio works', async () => {const results: string[] = [];@@ -367,7 +427,7 @@ test('should ignore http error status codes set by user', async () => {await crawler.run([`${url}/500Error`]);- expect(crawler.autoscaledPool!.minConcurrency).toBe(2);+ expect((crawler.autoscaledPool!.system as ConcurrencySystem).minConcurrency).toBe(2);expect(failed).toHaveLength(0);});@@ -386,7 +446,7 @@ test('should throw an error on http error status codes set by user', async () =>await crawler.run([`${url}/hello.html`]);- expect(crawler.autoscaledPool!.minConcurrency).toBe(2);+ expect((crawler.autoscaledPool!.system as ConcurrencySystem).minConcurrency).toBe(2);expect(failed).toHaveLength(1);});diff --git a/test/core/crawlers/playwright_crawler.test.ts b/test/core/crawlers/playwright_crawler.test.tsindex d6d0eb993..29c83696b 100644--- a/test/core/crawlers/playwright_crawler.test.ts+++ b/test/core/crawlers/playwright_crawler.test.ts@@ -3,7 +3,7 @@ import type { AddressInfo } from 'node:net';import os from 'node:os';import type { PlaywrightCrawlingContext, PlaywrightGotoOptions, Request } from '@crawlee/playwright';-import { MemoryStorageBackend, serviceLocator } from '@crawlee/core';+import { type ConcurrencySystem, MemoryStorageBackend, serviceLocator } from '@crawlee/core';import { createPlaywrightRouter, PlaywrightCrawler, RequestList, RequestValidationError } from '@crawlee/playwright';import type { Cheerio, CheerioAPI, CheerioRoot, Element } from '@crawlee/utils';import express from 'express';@@ -113,7 +113,7 @@ describe('PlaywrightCrawler', () => {await playwrightCrawler.run();- expect(playwrightCrawler.autoscaledPool!.minConcurrency).toBe(1);+ expect((playwrightCrawler.autoscaledPool!.system as ConcurrencySystem).minConcurrency).toBe(1);expect(processed).toHaveLength(6);expect(failed).toHaveLength(0);diff --git a/test/core/crawlers/puppeteer_crawler.test.ts b/test/core/crawlers/puppeteer_crawler.test.tsindex e7d170d18..b0b3fafa7 100644--- a/test/core/crawlers/puppeteer_crawler.test.ts+++ b/test/core/crawlers/puppeteer_crawler.test.ts@@ -24,7 +24,7 @@ import {Session,SessionPool,} from '@crawlee/puppeteer';-import { MemoryStorageBackend, serviceLocator } from '@crawlee/core';+import { type ConcurrencySystem, MemoryStorageBackend, serviceLocator } from '@crawlee/core';import { sleep } from '@crawlee/utils';import type { Server as ProxyChainServer } from 'proxy-chain';import { z } from 'zod';@@ -126,7 +126,7 @@ describe('PuppeteerCrawler', () => {await puppeteerCrawler.run();- expect(puppeteerCrawler.autoscaledPool!.minConcurrency).toBe(1);+ expect((puppeteerCrawler.autoscaledPool!.system as ConcurrencySystem).minConcurrency).toBe(1);expect(processed).toHaveLength(6);expect(failed).toHaveLength(0);diff --git a/test/e2e/autoscaling-max-tasks-per-minute/actor/main.js b/test/e2e/autoscaling-max-tasks-per-minute/actor/main.jsindex 4b9777365..9f25e8edf 100644--- a/test/e2e/autoscaling-max-tasks-per-minute/actor/main.js+++ b/test/e2e/autoscaling-max-tasks-per-minute/actor/main.js@@ -19,7 +19,7 @@ let crawlCalledAt = Date.now();await Actor.main(async () => {const crawler = new BasicCrawler({log: crawlerLogger,- autoscaledPoolOptions: { maxTasksPerMinute: 1 },+ maxRequestsPerMinute: 1,requestHandler({ log }) {log.info(`Crawler requestHandler called after ${Date.now() - crawlCalledAt}ms`);crawlCalledAt = Date.now();diff --git a/test/e2e/cheerio-max-requests/actor/main.js b/test/e2e/cheerio-max-requests/actor/main.jsindex 68c1c1b11..52e1ded56 100644--- a/test/e2e/cheerio-max-requests/actor/main.js+++ b/test/e2e/cheerio-max-requests/actor/main.js@@ -1,5 +1,5 @@import { Actor } from 'apify';-import { CheerioCrawler, Dataset } from '@crawlee/cheerio';+import { CheerioCrawler, ConcurrencySystem, Dataset } from '@crawlee/cheerio';const mainOptions = {exit: Actor.isAtHome(),@@ -10,9 +10,12 @@ const mainOptions = {};await Actor.main(async () => {+ // The caller owns an injected system's lifecycle - start it before the crawler runs and stop it afterwards.+ const concurrencySystem = new ConcurrencySystem({ desiredConcurrency: 2 });+const crawler = new CheerioCrawler({maxRequestsPerCrawl: 10,- autoscaledPoolOptions: { desiredConcurrency: 2 },+ concurrencySystem,async requestHandler({ $, request }) {const {url,@@ -49,5 +52,10 @@ await Actor.main(async () => {},});- await crawler.run([{ url: 'https://crawlee.dev/js/docs/examples', userData: { label: 'START' } }]);+ await concurrencySystem.start();+ try {+ await crawler.run([{ url: 'https://crawlee.dev/js/docs/examples', userData: { label: 'START' } }]);+ } finally {+ await concurrencySystem.stop();+ }}, mainOptions);