@crawlee/core 4.0.0-beta.87 → 4.0.0-beta.89

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,11 @@
1
+ import type { ConcurrencyConsumer, IConcurrencySystem } from './concurrency_system.js';
1
2
  import type { CrawleeLogger } from '../log.js';
2
- import type { SnapshotterOptions } from './snapshotter.js';
3
- import type { SystemStatusOptions } from './system_status.js';
4
- export interface AutoscaledPoolOptions {
5
- /**
6
- * A function that performs an asynchronous resource-intensive task.
7
- * The function must either be labeled `async` or return a promise.
8
- */
9
- runTaskFunction?: () => Promise<unknown>;
3
+ /**
4
+ * The task-readiness predicates a consumer may supply to steer an {@link AutoscaledPool}'s run loop — the parts of
5
+ * the loop a higher-level driver (e.g. a crawler) legitimately overrides, as opposed to the crawler-owned
6
+ * `runTaskFunction`.
7
+ */
8
+ export interface AutoscaledPoolPredicateOptions {
10
9
  /**
11
10
  * A function that indicates whether `runTaskFunction` should be called.
12
11
  * This function is called every time there is free capacity for a new task and it should
@@ -22,104 +21,55 @@ export interface AutoscaledPoolOptions {
22
21
  * To abort a run, use the {@link AutoscaledPool.abort} method.
23
22
  */
24
23
  isFinishedFunction?: () => Promise<boolean>;
24
+ }
25
+ export interface AutoscaledPoolOptions extends AutoscaledPoolPredicateOptions {
25
26
  /**
26
- * The minimum number of tasks running in parallel.
27
+ * The governor that decides whether there is free compute for one more task. Typically a
28
+ * {@link ConcurrencySystem}, but any {@link IConcurrencySystem} works. Share a single instance across
29
+ * multiple pools (and therefore multiple crawlers) to cap their *combined* concurrency against one budget.
27
30
  *
28
- * *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.
29
- * If you're not sure, just keep the default value and the concurrency will scale up automatically.
30
- * @default 1
31
- */
32
- minConcurrency?: number;
33
- /**
34
- * The maximum number of tasks running in parallel.
35
- * @default 200
31
+ * All concurrency/scaling/snapshotter configuration lives on the governor the pool only owns the task loop and
32
+ * its cadence.
36
33
  */
37
- maxConcurrency?: number;
34
+ concurrencySystem: IConcurrencySystem;
38
35
  /**
39
- * The desired number of tasks that should be running parallel on the start of the pool,
40
- * if there is a large enough supply of them.
41
- * By default, it is `minConcurrency`.
36
+ * Who this pool is, presented to the governor on every capacity query and booking so that a shared one can tell
37
+ * several pools apart. Worth naming meaningfully — a governor that allocates per consumer reports this `id`.
42
38
  */
43
- desiredConcurrency?: number;
39
+ consumer: ConcurrencyConsumer;
44
40
  /**
45
- * Minimum level of desired concurrency to reach before more scaling up is allowed.
46
- * @default 0.90
47
- */
48
- desiredConcurrencyRatio?: number;
49
- /**
50
- * Defines the fractional amount of desired concurrency to be added with each scaling up.
51
- * The minimum scaling step is one.
52
- * @default 0.05
53
- */
54
- scaleUpStepRatio?: number;
55
- /**
56
- * Defines the amount of desired concurrency to be subtracted with each scaling down.
57
- * The minimum scaling step is one.
58
- * @default 0.05
41
+ * A function that performs an asynchronous resource-intensive task.
42
+ * The function must either be labeled `async` or return a promise.
59
43
  */
60
- scaleDownStepRatio?: number;
44
+ runTaskFunction?: () => Promise<unknown>;
61
45
  /**
62
46
  * Indicates how often the pool should call the `runTaskFunction()` to start a new task, in seconds.
63
47
  * This has no effect on starting new tasks immediately after a task completes.
64
48
  * @default 0.5
65
49
  */
66
50
  maybeRunIntervalSecs?: number;
67
- /**
68
- * Specifies a period in which the instance logs its state, in seconds.
69
- * Set to `null` to disable periodic logging.
70
- * @default 60
71
- */
72
- loggingIntervalSecs?: number | null;
73
- /**
74
- * Defines in seconds how often the pool should attempt to adjust the desired concurrency
75
- * based on the latest system status. Setting it lower than 1 might have a severe impact on performance.
76
- * We suggest using a value from 5 to 20.
77
- * @default 10
78
- */
79
- autoscaleIntervalSecs?: number;
80
51
  /**
81
52
  * Timeout in which the `runTaskFunction` needs to finish, given in seconds.
82
53
  * @default 0
83
54
  */
84
55
  taskTimeoutSecs?: number;
85
- /**
86
- * Options to be passed down to the {@link Snapshotter} constructor. This is useful for fine-tuning
87
- * the snapshot intervals and history.
88
- */
89
- snapshotterOptions?: SnapshotterOptions;
90
- /**
91
- * Options to be passed down to the {@link SystemStatus} constructor. This is useful for fine-tuning
92
- * the system status reports. If a custom snapshotter is set in the options, it will be used
93
- * by the pool.
94
- */
95
- systemStatusOptions?: SystemStatusOptions;
96
- /**
97
- * The maximum number of tasks per minute the pool can run.
98
- * By default, this is set to `Infinity`, but you can pass any positive, non-zero integer.
99
- */
100
- maxTasksPerMinute?: number;
101
56
  log?: CrawleeLogger;
102
57
  }
103
58
  /**
104
59
  * Manages a pool of asynchronous resource-intensive tasks that are executed in parallel.
105
- * The pool only starts new tasks if there is enough free CPU and memory available
106
- * and the Javascript event loop is not blocked.
107
- *
108
- * The information about the CPU and memory usage is obtained by the {@link Snapshotter} class,
109
- * which makes regular snapshots of system resources that may be either local
110
- * or from the Apify cloud infrastructure in case the process is running on the Apify platform.
111
- * Meaningful data gathered from these snapshots is provided to `AutoscaledPool` by the {@link SystemStatus} class.
60
+ * The pool only starts new tasks while its {@link IConcurrencySystem|concurrency system} reports free capacity
61
+ * that governor is what monitors CPU, memory and event loop load and autoscales the concurrency budget.
112
62
  *
113
63
  * Before running the pool, you need to implement the following three functions:
114
- * {@link AutoscaledPoolOptions.runTaskFunction},
115
- * {@link AutoscaledPoolOptions.isTaskReadyFunction} and
116
- * {@link AutoscaledPoolOptions.isFinishedFunction}.
64
+ * {@link AutoscaledPoolOptions.runTaskFunction|`runTaskFunction`},
65
+ * {@link AutoscaledPoolPredicateOptions.isTaskReadyFunction|`isTaskReadyFunction`} and
66
+ * {@link AutoscaledPoolPredicateOptions.isFinishedFunction|`isFinishedFunction`}.
117
67
  *
118
68
  * The auto-scaled pool is started by calling the {@link AutoscaledPool.run} function.
119
- * The pool periodically queries the {@link AutoscaledPoolOptions.isTaskReadyFunction} function
120
- * for more tasks, managing optimal concurrency, until the function resolves to `false`. The pool then queries
121
- * the {@link AutoscaledPoolOptions.isFinishedFunction}. If it resolves to `true`, the run finishes after all running tasks complete.
122
- * If it resolves to `false`, it assumes there will be more tasks available later and keeps periodically querying for tasks.
69
+ * The pool periodically queries `isTaskReadyFunction` for more tasks, managing optimal concurrency, until the function
70
+ * resolves to `false`. The pool then queries `isFinishedFunction`. If it resolves to `true`, the run finishes after all
71
+ * running tasks complete. If it resolves to `false`, it assumes there will be more tasks available later and keeps
72
+ * periodically querying for tasks.
123
73
  * If any of the tasks throws then the {@link AutoscaledPool.run} function rejects the promise with an error.
124
74
  *
125
75
  * The pool evaluates whether it should start a new task every time one of the tasks finishes
@@ -128,8 +78,12 @@ export interface AutoscaledPoolOptions {
128
78
  * **Example usage:**
129
79
  *
130
80
  * ```javascript
81
+ * const concurrencySystem = new ConcurrencySystem({ maxConcurrency: 50 });
82
+ * await concurrencySystem.start();
83
+ *
131
84
  * const pool = new AutoscaledPool({
132
- * maxConcurrency: 50,
85
+ * concurrencySystem,
86
+ * consumer: { id: 'my-pool' },
133
87
  * runTaskFunction: async () => {
134
88
  * // Run some resource-intensive asynchronous operation here.
135
89
  * },
@@ -144,78 +98,56 @@ export interface AutoscaledPoolOptions {
144
98
  * }
145
99
  * });
146
100
  *
147
- * await pool.run();
101
+ * try {
102
+ * await pool.run();
103
+ * } finally {
104
+ * await concurrencySystem.stop();
105
+ * }
148
106
  * ```
149
107
  * @category Scaling
150
108
  */
151
109
  export declare class AutoscaledPool {
152
110
  private readonly log;
153
- private readonly desiredConcurrencyRatio;
154
- private readonly scaleUpStepRatio;
155
- private readonly scaleDownStepRatio;
156
111
  private readonly maybeRunIntervalMillis;
157
- private readonly loggingIntervalMillis;
158
- private readonly autoscaleIntervalMillis;
159
112
  private readonly taskTimeoutMillis;
160
113
  private readonly runTaskFunction;
161
114
  private readonly isFinishedFunction;
162
115
  private readonly isTaskReadyFunction;
163
- private readonly maxTasksPerMinute;
164
- private _minConcurrency;
165
- private _maxConcurrency;
166
- private _desiredConcurrency;
167
- private _currentConcurrency;
116
+ private readonly concurrencySystem;
117
+ private readonly consumer;
168
118
  private isStopped;
169
- private lastLoggingTime?;
170
119
  private resolve;
171
120
  private reject;
172
- private snapshotter;
173
- /** Additional SystemStatus loadSignals - tracked here for initialization and cleanup */
174
- private loadSignals;
175
- private systemStatus;
176
- private autoscaleInterval;
177
121
  private maybeRunInterval;
178
122
  private queryingIsTaskReady;
179
123
  private queryingIsFinished;
180
- private tasksDonePerSecondInterval?;
181
- private _tasksPerMinute;
182
- constructor(options: AutoscaledPoolOptions);
183
124
  /**
184
- * Gets the minimum number of tasks running in parallel.
125
+ * This pool's *own* in-flight task count, as opposed to {@link AutoscaledPool.currentConcurrency}, which is the
126
+ * (possibly shared) governor's total. `pause()` and `maybeFinish()` care only about this pool draining.
185
127
  */
186
- get minConcurrency(): number;
128
+ private ownConcurrency;
129
+ constructor(options: AutoscaledPoolOptions);
187
130
  /**
188
- * Sets the minimum number of tasks running in parallel.
131
+ * The governor backing this pool, as supplied to the constructor exposed as the read-only
132
+ * {@link IConcurrencySystem} contract.
189
133
  *
190
- * *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.
191
- * If you're not sure, just keep the default value and the concurrency will scale up automatically.
192
- */
193
- set minConcurrency(value: number);
194
- /**
195
- * Gets the maximum number of tasks running in parallel.
196
- */
197
- get maxConcurrency(): number;
198
- /**
199
- * Sets the maximum number of tasks running in parallel.
200
- */
201
- set maxConcurrency(value: number);
202
- /**
203
- * Gets the desired concurrency for the pool,
204
- * which is an estimated number of parallel tasks that the system can currently support.
134
+ * This and the two getters below are telemetry only: concurrency is configured and tuned on the concrete
135
+ * {@link ConcurrencySystem} its owner holds, never through the pool.
205
136
  */
137
+ get system(): IConcurrencySystem;
138
+ /** The estimated number of parallel tasks the governor can currently support. */
206
139
  get desiredConcurrency(): number;
207
140
  /**
208
- * Sets the desired concurrency for the pool, i.e. the number of tasks that should be running
209
- * in parallel if there's large enough supply of tasks.
210
- */
211
- set desiredConcurrency(value: number);
212
- /**
213
- * Gets the number of parallel tasks currently running in the pool.
141
+ * The number of parallel tasks currently booked against the governor. When it is shared, this counts every
142
+ * borrowing pool's tasks, not just this one's.
214
143
  */
215
144
  get currentConcurrency(): number;
216
145
  /**
217
146
  * Runs the auto-scaled pool. Returns a promise that gets resolved or rejected once
218
147
  * all the tasks are finished or one of them fails.
148
+ *
149
+ * Throws if the {@link IConcurrencySystem|concurrency system} it borrows was never started — the pool assumes
150
+ * a running governor and cannot start one it does not own.
219
151
  */
220
152
  run(): Promise<void>;
221
153
  /**
@@ -240,6 +172,10 @@ export declare class AutoscaledPool {
240
172
  *
241
173
  * The promise returned from the {@link AutoscaledPool.run} function will not resolve
242
174
  * when `.pause()` is invoked (unlike abort, which resolves it).
175
+ *
176
+ * > *NOTE:* Pausing the pool does not suspend the (possibly shared) {@link ConcurrencySystem} — its
177
+ * autoscaling and resource monitoring keep running, since other pools borrowing it may still be active. To silence
178
+ * it during a long pause, its owner can `stop()` and `start()` it again.
243
179
  */
244
180
  pause(timeoutSecs?: number): Promise<void>;
245
181
  /**
@@ -263,26 +199,6 @@ export declare class AutoscaledPool {
263
199
  * It doesn't allow multiple concurrent runs of this method.
264
200
  */
265
201
  private maybeRunTask;
266
- /**
267
- * Gets called every autoScaleIntervalSecs and evaluates the current system status.
268
- * If the system IS NOT overloaded and the settings allow it, it scales up.
269
- * If the system IS overloaded and the settings allow it, it scales down.
270
- */
271
- private autoscale;
272
- /**
273
- * Scales the pool up by increasing
274
- * the desired concurrency by the scaleUpStepRatio.
275
- *
276
- * @param systemStatus for logging
277
- */
278
- private scaleUp;
279
- /**
280
- * Scales the pool down by decreasing
281
- * the desired concurrency by the scaleDownStepRatio.
282
- *
283
- * @param systemStatus for logging
284
- */
285
- private scaleDown;
286
202
  /**
287
203
  * If there are no running tasks and this.isFinishedFunction() returns true then closes
288
204
  * the pool and resolves the pool's promise returned by the run() method.
@@ -294,6 +210,4 @@ export declare class AutoscaledPool {
294
210
  * Cleans up resources.
295
211
  */
296
212
  private destroy;
297
- private incrementTasksDonePerSecond;
298
- private get isOverMaxRequestLimit();
299
213
  }