@crawlee/core 4.0.0-rc.0 → 4.0.0-rc.1
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.
- package/README.md +1 -1
- package/configuration.d.ts +15 -46
- package/configuration.js +8 -20
- package/errors.d.ts +12 -53
- package/errors.js +13 -66
- package/events/index.d.ts +1 -0
- package/events/local_event_manager.d.ts +0 -7
- package/events/local_event_manager.js +8 -8
- package/events/system_info.d.ts +38 -0
- package/index.d.ts +2 -8
- package/index.js +4 -8
- package/internal.d.ts +8 -0
- package/internal.js +9 -0
- package/log.d.ts +10 -11
- package/log.js +53 -25
- package/memory-storage/memory-storage.d.ts +12 -7
- package/memory-storage/memory-storage.js +45 -17
- package/memory-storage/resource-clients/dataset.d.ts +0 -5
- package/memory-storage/resource-clients/dataset.js +17 -20
- package/memory-storage/resource-clients/key-value-store.d.ts +0 -9
- package/memory-storage/resource-clients/key-value-store.js +11 -33
- package/memory-storage/resource-clients/request-queue.d.ts +0 -22
- package/memory-storage/resource-clients/request-queue.js +57 -53
- package/package.json +16 -18
- package/proxy_configuration.d.ts +20 -23
- package/proxy_configuration.js +18 -12
- package/recoverable_state.d.ts +28 -6
- package/recoverable_state.js +51 -14
- package/request.d.ts +18 -104
- package/request.js +41 -220
- package/serialization.js +3 -3
- package/service_locator.d.ts +3 -0
- package/service_locator.js +2 -0
- package/storages/dataset.d.ts +9 -15
- package/storages/dataset.js +22 -14
- package/storages/index.d.ts +3 -4
- package/storages/index.js +1 -4
- package/storages/key_value_store.d.ts +12 -46
- package/storages/key_value_store.js +31 -47
- package/storages/key_value_store_codec.js +6 -11
- package/storages/request_dedup_cache.d.ts +0 -2
- package/storages/request_dedup_cache.js +8 -8
- package/storages/request_list.d.ts +6 -82
- package/storages/request_list.js +175 -179
- package/storages/request_loader.d.ts +48 -22
- package/storages/request_loader.js +36 -1
- package/storages/request_manager.d.ts +86 -0
- package/storages/request_manager_tandem.d.ts +13 -28
- package/storages/request_manager_tandem.js +46 -43
- package/storages/request_queue.d.ts +19 -49
- package/storages/request_queue.js +92 -88
- package/storages/storage_instance_manager.d.ts +1 -2
- package/storages/storage_instance_manager.js +4 -4
- package/storages/transaction.d.ts +27 -9
- package/storages/transaction.js +56 -11
- package/storages/utils.d.ts +2 -2
- package/validators.d.ts +3 -2
- package/validators.js +3 -2
- package/autoscaling/autoscaled_pool.d.ts +0 -195
- package/autoscaling/autoscaled_pool.js +0 -386
- package/autoscaling/concurrency_system.d.ts +0 -268
- package/autoscaling/concurrency_system.js +0 -362
- package/autoscaling/cpu_load_signal.d.ts +0 -43
- package/autoscaling/cpu_load_signal.js +0 -47
- package/autoscaling/event_loop_load_signal.d.ts +0 -51
- package/autoscaling/event_loop_load_signal.js +0 -60
- package/autoscaling/index.d.ts +0 -9
- package/autoscaling/index.js +0 -9
- package/autoscaling/load_signal.d.ts +0 -100
- package/autoscaling/load_signal.js +0 -105
- package/autoscaling/memory_load_signal.d.ts +0 -47
- package/autoscaling/memory_load_signal.js +0 -106
- package/autoscaling/snapshotter.d.ts +0 -84
- package/autoscaling/snapshotter.js +0 -67
- package/autoscaling/storage_backend_load_signal.d.ts +0 -56
- package/autoscaling/storage_backend_load_signal.js +0 -73
- package/autoscaling/system_status.d.ts +0 -159
- package/autoscaling/system_status.js +0 -139
- package/autoscaling/weighted_avg.d.ts +0 -5
- package/autoscaling/weighted_avg.js +0 -14
- package/cookie_utils.d.ts +0 -44
- package/cookie_utils.js +0 -122
- package/crawlers/context_pipeline.d.ts +0 -70
- package/crawlers/context_pipeline.js +0 -122
- package/crawlers/crawler_commons.d.ts +0 -159
- package/crawlers/error_snapshotter.d.ts +0 -57
- package/crawlers/error_snapshotter.js +0 -117
- package/crawlers/error_tracker.d.ts +0 -54
- package/crawlers/error_tracker.js +0 -308
- package/crawlers/index.d.ts +0 -5
- package/crawlers/index.js +0 -4
- package/crawlers/internals/types.d.ts +0 -7
- package/crawlers/internals/types.js +0 -1
- package/crawlers/statistics.d.ts +0 -328
- package/crawlers/statistics.js +0 -536
- package/enqueue_links/enqueue_links.d.ts +0 -156
- package/enqueue_links/enqueue_links.js +0 -78
- package/enqueue_links/index.d.ts +0 -2
- package/enqueue_links/index.js +0 -2
- package/enqueue_links/shared.d.ts +0 -93
- package/enqueue_links/shared.js +0 -239
- package/http.d.ts +0 -9
- package/http.js +0 -28
- package/router.d.ts +0 -306
- package/router.js +0 -309
- package/session_pool/consts.d.ts +0 -3
- package/session_pool/consts.js +0 -3
- package/session_pool/errors.d.ts +0 -7
- package/session_pool/errors.js +0 -11
- package/session_pool/fingerprint.d.ts +0 -9
- package/session_pool/fingerprint.js +0 -30
- package/session_pool/index.d.ts +0 -4
- package/session_pool/index.js +0 -4
- package/session_pool/session.d.ts +0 -150
- package/session_pool/session.js +0 -220
- package/session_pool/session_pool.d.ts +0 -240
- package/session_pool/session_pool.js +0 -394
- package/storages/sitemap_request_loader.d.ts +0 -201
- package/storages/sitemap_request_loader.js +0 -438
- package/storages/throttling_request_manager.d.ts +0 -239
- package/storages/throttling_request_manager.js +0 -646
- /package/{crawlers/crawler_commons.js → events/system_info.js} +0 -0
|
@@ -1,100 +0,0 @@
|
|
|
1
|
-
import type { LoadSignalInfo } from './system_status.js';
|
|
2
|
-
/**
|
|
3
|
-
* A snapshot of a resource's overload state at a point in time.
|
|
4
|
-
*/
|
|
5
|
-
export interface LoadSnapshot {
|
|
6
|
-
createdAt: Date;
|
|
7
|
-
isOverloaded: boolean;
|
|
8
|
-
}
|
|
9
|
-
/**
|
|
10
|
-
* Handed to a {@link LoadSignal} when it starts, so it can size its snapshot retention to what it will actually
|
|
11
|
-
* be asked for — without having to know how the {@link ConcurrencySystem} that drives it is configured.
|
|
12
|
-
*/
|
|
13
|
-
export interface LoadSignalStartContext {
|
|
14
|
-
/**
|
|
15
|
-
* The longest sample window the signal will be queried with (the wider of the task-gating and autoscaling
|
|
16
|
-
* windows). Keeping less history than this contributes a narrower view of the resource than the other signals;
|
|
17
|
-
* keeping more is wasted memory, as the extra snapshots are never sampled.
|
|
18
|
-
*/
|
|
19
|
-
maxSampleWindowMillis: number;
|
|
20
|
-
}
|
|
21
|
-
/**
|
|
22
|
-
* A signal that reports whether a particular resource is overloaded. The {@link ConcurrencySystem} aggregates
|
|
23
|
-
* several of them — if any one reports overload, the system is overloaded.
|
|
24
|
-
*
|
|
25
|
-
* The built-in signals cover memory, CPU, event loop and storage backend rate limits. Implement this interface to add
|
|
26
|
-
* your own (navigation timeouts, proxy health, …) and pass them via
|
|
27
|
-
* {@link LoadSignalsOptions.custom|`loadSignals.custom`}; {@link SnapshotStore} does the time-windowed
|
|
28
|
-
* bookkeeping if you want it. Each built-in is also a public class, so one can be *wrapped* rather than reimplemented
|
|
29
|
-
* — construct it yourself and switch the default off with {@link LoadSignalsOptions.cpu|`cpu: false`} or friends.
|
|
30
|
-
*/
|
|
31
|
-
export interface LoadSignal {
|
|
32
|
-
/**
|
|
33
|
-
* This signal's key in the reported {@link SystemInfo}, also used in logging — so it must be unique among the
|
|
34
|
-
* signals of one {@link ConcurrencySystem}, which throws on a duplicate. The four built-in names (`memInfo`,
|
|
35
|
-
* `eventLoopInfo`, `cpuInfo`, `storageBackendInfo`) land in the correspondingly named `SystemInfo` fields rather
|
|
36
|
-
* than the `loadSignalInfo` bag; taking one over means switching that built-in off.
|
|
37
|
-
*/
|
|
38
|
-
readonly name: string;
|
|
39
|
-
/**
|
|
40
|
-
* Maximum ratio of overloaded snapshots in a sample before the signal
|
|
41
|
-
* is considered overloaded. For example, `0.2` means the signal fires
|
|
42
|
-
* when more than 20% of the sample window is overloaded.
|
|
43
|
-
*/
|
|
44
|
-
readonly overloadedRatio: number;
|
|
45
|
-
/**
|
|
46
|
-
* Start collecting snapshots, retaining at least the sample window named in the `context`. Called when the
|
|
47
|
-
* {@link ConcurrencySystem} starts — which may be a *restart*, so drop anything measured before it.
|
|
48
|
-
*/
|
|
49
|
-
start(context: LoadSignalStartContext): Promise<void>;
|
|
50
|
-
/** Stop collecting snapshots. Called when the {@link ConcurrencySystem} shuts down. */
|
|
51
|
-
stop(): Promise<void>;
|
|
52
|
-
/**
|
|
53
|
-
* Return snapshots for a recent time window (used for "current" status).
|
|
54
|
-
* @param sampleDurationMillis How far back to look, in milliseconds.
|
|
55
|
-
*/
|
|
56
|
-
getSample(sampleDurationMillis?: number): LoadSnapshot[];
|
|
57
|
-
}
|
|
58
|
-
/**
|
|
59
|
-
* A time-pruning, time-windowed store for `LoadSnapshot` values. All four built-in signals compose with one of these,
|
|
60
|
-
* and so can yours — it is the only part of their machinery worth reusing.
|
|
61
|
-
*/
|
|
62
|
-
export declare class SnapshotStore<T extends LoadSnapshot = LoadSnapshot> {
|
|
63
|
-
#private;
|
|
64
|
-
/** Retention window in milliseconds. Unbounded until {@link SnapshotStore.useSampleWindow|`useSampleWindow()`}. */
|
|
65
|
-
private historyMillis;
|
|
66
|
-
/**
|
|
67
|
-
* Sizes retention to the window the signal will be sampled over, as handed to it in
|
|
68
|
-
* {@link LoadSignal.start|`start()`}. Until this is called nothing is pruned at all, so a signal that ignores
|
|
69
|
-
* its start context grows unboundedly.
|
|
70
|
-
*/
|
|
71
|
-
useSampleWindow(maxSampleWindowMillis: number): void;
|
|
72
|
-
/**
|
|
73
|
-
* Add a snapshot and prune entries older than the history window.
|
|
74
|
-
*/
|
|
75
|
-
push(snapshot: T, now?: Date): void;
|
|
76
|
-
/**
|
|
77
|
-
* Return all snapshots, or only those within the given time window.
|
|
78
|
-
*/
|
|
79
|
-
getSample(sampleDurationMillis?: number): T[];
|
|
80
|
-
/**
|
|
81
|
-
* Direct, unwindowed access to the underlying array — used by signals whose handler needs the previous snapshot
|
|
82
|
-
* to compute a delta (e.g. the event loop and storage backend signals read the last entry to measure change since
|
|
83
|
-
* it).
|
|
84
|
-
*/
|
|
85
|
-
getAll(): T[];
|
|
86
|
-
/**
|
|
87
|
-
* Discards every retained snapshot. The built-in signals do this when they *start*, so that a session neither
|
|
88
|
-
* samples nor diffs against measurements from before the preceding downtime — pruning is relative to the newest
|
|
89
|
-
* snapshot rather than the wall clock, so stale entries would otherwise survive indefinitely. Clearing on start
|
|
90
|
-
* rather than on stop leaves a finished session readable.
|
|
91
|
-
*/
|
|
92
|
-
clear(): void;
|
|
93
|
-
}
|
|
94
|
-
/**
|
|
95
|
-
* Evaluate whether a sample of `LoadSnapshot` values exceeds the given
|
|
96
|
-
* overloaded ratio, using a time-weighted average. This is the shared
|
|
97
|
-
* evaluation logic used by `SystemStatus` for all signal types.
|
|
98
|
-
* @internal
|
|
99
|
-
*/
|
|
100
|
-
export declare function evaluateLoadSignalSample(sample: LoadSnapshot[], overloadedRatio: number): LoadSignalInfo;
|
|
@@ -1,105 +0,0 @@
|
|
|
1
|
-
import { weightedAvg } from './weighted_avg.js';
|
|
2
|
-
/**
|
|
3
|
-
* A time-pruning, time-windowed store for `LoadSnapshot` values. All four built-in signals compose with one of these,
|
|
4
|
-
* and so can yours — it is the only part of their machinery worth reusing.
|
|
5
|
-
*/
|
|
6
|
-
export class SnapshotStore {
|
|
7
|
-
#snapshots = [];
|
|
8
|
-
/** Retention window in milliseconds. Unbounded until {@link SnapshotStore.useSampleWindow|`useSampleWindow()`}. */
|
|
9
|
-
// kept as TS-private: concurrency_system tests read this retention window directly
|
|
10
|
-
historyMillis = Infinity;
|
|
11
|
-
/**
|
|
12
|
-
* Sizes retention to the window the signal will be sampled over, as handed to it in
|
|
13
|
-
* {@link LoadSignal.start|`start()`}. Until this is called nothing is pruned at all, so a signal that ignores
|
|
14
|
-
* its start context grows unboundedly.
|
|
15
|
-
*/
|
|
16
|
-
useSampleWindow(maxSampleWindowMillis) {
|
|
17
|
-
this.historyMillis = maxSampleWindowMillis;
|
|
18
|
-
}
|
|
19
|
-
/**
|
|
20
|
-
* Add a snapshot and prune entries older than the history window.
|
|
21
|
-
*/
|
|
22
|
-
push(snapshot, now = snapshot.createdAt) {
|
|
23
|
-
// Inline pruning to avoid private-method transpilation issues
|
|
24
|
-
let oldCount = 0;
|
|
25
|
-
for (let i = 0; i < this.#snapshots.length; i++) {
|
|
26
|
-
const { createdAt } = this.#snapshots[i];
|
|
27
|
-
if (now.getTime() - new Date(createdAt).getTime() > this.historyMillis)
|
|
28
|
-
oldCount++;
|
|
29
|
-
else
|
|
30
|
-
break;
|
|
31
|
-
}
|
|
32
|
-
if (oldCount)
|
|
33
|
-
this.#snapshots.splice(0, oldCount);
|
|
34
|
-
this.#snapshots.push(snapshot);
|
|
35
|
-
}
|
|
36
|
-
/**
|
|
37
|
-
* Return all snapshots, or only those within the given time window.
|
|
38
|
-
*/
|
|
39
|
-
getSample(sampleDurationMillis) {
|
|
40
|
-
if (!sampleDurationMillis)
|
|
41
|
-
return this.#snapshots;
|
|
42
|
-
const sample = [];
|
|
43
|
-
let idx = this.#snapshots.length;
|
|
44
|
-
if (!idx)
|
|
45
|
-
return sample;
|
|
46
|
-
const latestTime = this.#snapshots[idx - 1].createdAt;
|
|
47
|
-
while (idx--) {
|
|
48
|
-
const snapshot = this.#snapshots[idx];
|
|
49
|
-
if (+latestTime - +snapshot.createdAt <= sampleDurationMillis) {
|
|
50
|
-
sample.unshift(snapshot);
|
|
51
|
-
}
|
|
52
|
-
else {
|
|
53
|
-
break;
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
return sample;
|
|
57
|
-
}
|
|
58
|
-
/**
|
|
59
|
-
* Direct, unwindowed access to the underlying array — used by signals whose handler needs the previous snapshot
|
|
60
|
-
* to compute a delta (e.g. the event loop and storage backend signals read the last entry to measure change since
|
|
61
|
-
* it).
|
|
62
|
-
*/
|
|
63
|
-
getAll() {
|
|
64
|
-
return this.#snapshots;
|
|
65
|
-
}
|
|
66
|
-
/**
|
|
67
|
-
* Discards every retained snapshot. The built-in signals do this when they *start*, so that a session neither
|
|
68
|
-
* samples nor diffs against measurements from before the preceding downtime — pruning is relative to the newest
|
|
69
|
-
* snapshot rather than the wall clock, so stale entries would otherwise survive indefinitely. Clearing on start
|
|
70
|
-
* rather than on stop leaves a finished session readable.
|
|
71
|
-
*/
|
|
72
|
-
clear() {
|
|
73
|
-
this.#snapshots = [];
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
/**
|
|
77
|
-
* Evaluate whether a sample of `LoadSnapshot` values exceeds the given
|
|
78
|
-
* overloaded ratio, using a time-weighted average. This is the shared
|
|
79
|
-
* evaluation logic used by `SystemStatus` for all signal types.
|
|
80
|
-
* @internal
|
|
81
|
-
*/
|
|
82
|
-
export function evaluateLoadSignalSample(sample, overloadedRatio) {
|
|
83
|
-
if (sample.length === 0) {
|
|
84
|
-
return {
|
|
85
|
-
isOverloaded: false,
|
|
86
|
-
limitRatio: overloadedRatio,
|
|
87
|
-
actualRatio: 0,
|
|
88
|
-
};
|
|
89
|
-
}
|
|
90
|
-
const weights = [];
|
|
91
|
-
const values = [];
|
|
92
|
-
for (let i = 1; i < sample.length; i++) {
|
|
93
|
-
const previous = sample[i - 1];
|
|
94
|
-
const current = sample[i];
|
|
95
|
-
const weight = +current.createdAt - +previous.createdAt;
|
|
96
|
-
weights.push(weight || 1); // Prevent errors from 0ms long intervals (sync) between snapshots.
|
|
97
|
-
values.push(+current.isOverloaded);
|
|
98
|
-
}
|
|
99
|
-
const wAvg = sample.length === 1 ? +sample[0].isOverloaded : weightedAvg(values, weights);
|
|
100
|
-
return {
|
|
101
|
-
isOverloaded: wAvg > overloadedRatio,
|
|
102
|
-
limitRatio: overloadedRatio,
|
|
103
|
-
actualRatio: Math.round(wAvg * 1000) / 1000,
|
|
104
|
-
};
|
|
105
|
-
}
|
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
import type { LoadSignal, LoadSignalStartContext, LoadSnapshot } from './load_signal.js';
|
|
2
|
-
import type { SystemInfo } from './system_status.js';
|
|
3
|
-
/**
|
|
4
|
-
* A snapshot produced by the built-in memory signal.
|
|
5
|
-
* @internal
|
|
6
|
-
*/
|
|
7
|
-
export interface MemorySnapshot extends LoadSnapshot {
|
|
8
|
-
usedBytes?: number;
|
|
9
|
-
}
|
|
10
|
-
/**
|
|
11
|
-
* Tuning for the built-in **memory** load signal, as accepted both by {@link MemoryLoadSignal} and by the
|
|
12
|
-
* {@link LoadSignalsOptions.memory|`memory`} shorthand on {@link LoadSignalsOptions}.
|
|
13
|
-
*/
|
|
14
|
-
export interface MemoryLoadSignalOptions {
|
|
15
|
-
/**
|
|
16
|
-
* Defines the maximum ratio of total memory that can be used.
|
|
17
|
-
* Exceeding this limit overloads the memory.
|
|
18
|
-
* @default 0.9
|
|
19
|
-
*/
|
|
20
|
-
maxUsedRatio?: number;
|
|
21
|
-
/**
|
|
22
|
-
* Maximum ratio of overloaded snapshots in a sample before memory counts as overloaded.
|
|
23
|
-
* @default 0.2
|
|
24
|
-
*/
|
|
25
|
-
overloadedRatio?: number;
|
|
26
|
-
}
|
|
27
|
-
/**
|
|
28
|
-
* Tracks memory usage via `SYSTEM_INFO` events and reports overload when the used-to-available memory ratio exceeds a
|
|
29
|
-
* threshold. Also warns when memory use becomes critical.
|
|
30
|
-
*
|
|
31
|
-
* Built by default; construct one yourself only to wrap or adapt it — see {@link LoadSignal}.
|
|
32
|
-
*
|
|
33
|
-
* @category Scaling
|
|
34
|
-
*/
|
|
35
|
-
export declare class MemoryLoadSignal implements LoadSignal {
|
|
36
|
-
#private;
|
|
37
|
-
readonly name = "memInfo";
|
|
38
|
-
readonly overloadedRatio: number;
|
|
39
|
-
constructor(options?: MemoryLoadSignalOptions);
|
|
40
|
-
start(context: LoadSignalStartContext): Promise<void>;
|
|
41
|
-
stop(): Promise<void>;
|
|
42
|
-
getSample(sampleDurationMillis?: number): LoadSnapshot[];
|
|
43
|
-
/** @internal Records a snapshot from a `SYSTEM_INFO` payload. Exposed for tests. */
|
|
44
|
-
handle(systemInfo: SystemInfo): void;
|
|
45
|
-
private memoryOverloadWarning;
|
|
46
|
-
private getTotalMemoryBytes;
|
|
47
|
-
}
|
|
@@ -1,106 +0,0 @@
|
|
|
1
|
-
import { EventType } from '../events/event_manager.js';
|
|
2
|
-
import { serviceLocator } from '../service_locator.js';
|
|
3
|
-
import { getMemoryInfo } from '../system-info/memory-info.js';
|
|
4
|
-
import { isContainerized } from '../system-info/runtime.js';
|
|
5
|
-
import { SnapshotStore } from './load_signal.js';
|
|
6
|
-
const RESERVE_MEMORY_RATIO = 0.5;
|
|
7
|
-
const CRITICAL_OVERLOAD_RATE_LIMIT_MILLIS = 10_000;
|
|
8
|
-
/**
|
|
9
|
-
* Tracks memory usage via `SYSTEM_INFO` events and reports overload when the used-to-available memory ratio exceeds a
|
|
10
|
-
* threshold. Also warns when memory use becomes critical.
|
|
11
|
-
*
|
|
12
|
-
* Built by default; construct one yourself only to wrap or adapt it — see {@link LoadSignal}.
|
|
13
|
-
*
|
|
14
|
-
* @category Scaling
|
|
15
|
-
*/
|
|
16
|
-
export class MemoryLoadSignal {
|
|
17
|
-
name = 'memInfo';
|
|
18
|
-
overloadedRatio;
|
|
19
|
-
#store = new SnapshotStore();
|
|
20
|
-
#maxUsedRatio;
|
|
21
|
-
/** All resolved in `start()`, before anything that reads them can fire. */
|
|
22
|
-
#config;
|
|
23
|
-
#log;
|
|
24
|
-
#maxMemoryBytes;
|
|
25
|
-
#events;
|
|
26
|
-
#maxMemoryRatio;
|
|
27
|
-
#lastLoggedCriticalMemoryOverloadAt = null;
|
|
28
|
-
constructor(options = {}) {
|
|
29
|
-
this.#maxUsedRatio = options.maxUsedRatio ?? 0.9;
|
|
30
|
-
this.overloadedRatio = options.overloadedRatio ?? 0.2;
|
|
31
|
-
this.handle = this.handle.bind(this);
|
|
32
|
-
}
|
|
33
|
-
async start(context) {
|
|
34
|
-
this.#store.useSampleWindow(context.maxSampleWindowMillis);
|
|
35
|
-
// A new session starts from a clean slate, so it is not judged on measurements from before the downtime.
|
|
36
|
-
this.#store.clear();
|
|
37
|
-
// Resolved here rather than in the constructor: an instance built ahead of time (to be wrapped, or shared
|
|
38
|
-
// between systems) must not capture whichever services happened to be registered at that moment.
|
|
39
|
-
this.#config = serviceLocator.getConfiguration();
|
|
40
|
-
this.#events = serviceLocator.getEventManager();
|
|
41
|
-
this.#log = serviceLocator.getLogger().child({ prefix: 'MemoryLoadSignal' });
|
|
42
|
-
const memoryMbytes = this.#config.memoryMbytes ?? 0;
|
|
43
|
-
if (memoryMbytes > 0) {
|
|
44
|
-
this.#maxMemoryBytes = memoryMbytes * 1024 * 1024;
|
|
45
|
-
}
|
|
46
|
-
else {
|
|
47
|
-
this.#maxMemoryRatio = this.#config.availableMemoryRatio;
|
|
48
|
-
if (!this.#maxMemoryRatio) {
|
|
49
|
-
throw new Error('availableMemoryRatio is not set in configuration.');
|
|
50
|
-
}
|
|
51
|
-
else {
|
|
52
|
-
this.#log.debug(`Setting max memory of this run to ${this.#maxMemoryRatio * 100} % of available memory. ` +
|
|
53
|
-
'Use the CRAWLEE_MEMORY_MBYTES or CRAWLEE_AVAILABLE_MEMORY_RATIO environment variable to override it.');
|
|
54
|
-
}
|
|
55
|
-
// Fallback memory measurement in case memTotalBytes is missing from SystemInfo.
|
|
56
|
-
this.#maxMemoryBytes = await this.getTotalMemoryBytes();
|
|
57
|
-
}
|
|
58
|
-
this.#events.on(EventType.SYSTEM_INFO, this.handle);
|
|
59
|
-
}
|
|
60
|
-
async stop() {
|
|
61
|
-
this.#events?.off(EventType.SYSTEM_INFO, this.handle);
|
|
62
|
-
this.#events = undefined;
|
|
63
|
-
}
|
|
64
|
-
getSample(sampleDurationMillis) {
|
|
65
|
-
return this.#store.getSample(sampleDurationMillis);
|
|
66
|
-
}
|
|
67
|
-
/** @internal Records a snapshot from a `SYSTEM_INFO` payload. Exposed for tests. */
|
|
68
|
-
handle(systemInfo) {
|
|
69
|
-
const createdAt = systemInfo.createdAt ? new Date(systemInfo.createdAt) : new Date();
|
|
70
|
-
const { memCurrentBytes, memTotalBytes } = systemInfo;
|
|
71
|
-
let maxMemoryBytes = this.#maxMemoryBytes;
|
|
72
|
-
if (this.#maxMemoryRatio !== undefined && this.#maxMemoryRatio > 0) {
|
|
73
|
-
maxMemoryBytes = this.#maxMemoryRatio * (memTotalBytes ?? this.#maxMemoryBytes);
|
|
74
|
-
}
|
|
75
|
-
const snapshot = {
|
|
76
|
-
createdAt,
|
|
77
|
-
isOverloaded: memCurrentBytes / maxMemoryBytes > this.#maxUsedRatio,
|
|
78
|
-
usedBytes: memCurrentBytes,
|
|
79
|
-
};
|
|
80
|
-
this.#store.push(snapshot, createdAt);
|
|
81
|
-
this.memoryOverloadWarning(systemInfo, maxMemoryBytes);
|
|
82
|
-
}
|
|
83
|
-
memoryOverloadWarning(systemInfo, maxMemoryBytes) {
|
|
84
|
-
const effectiveMax = maxMemoryBytes ?? this.#maxMemoryBytes;
|
|
85
|
-
const { memCurrentBytes } = systemInfo;
|
|
86
|
-
const createdAt = systemInfo.createdAt ? new Date(systemInfo.createdAt) : new Date();
|
|
87
|
-
if (this.#lastLoggedCriticalMemoryOverloadAt &&
|
|
88
|
-
+createdAt < +this.#lastLoggedCriticalMemoryOverloadAt + CRITICAL_OVERLOAD_RATE_LIMIT_MILLIS)
|
|
89
|
-
return;
|
|
90
|
-
const maxDesiredMemoryBytes = this.#maxUsedRatio * effectiveMax;
|
|
91
|
-
const reserveMemory = effectiveMax * (1 - this.#maxUsedRatio) * RESERVE_MEMORY_RATIO;
|
|
92
|
-
const criticalOverloadBytes = maxDesiredMemoryBytes + reserveMemory;
|
|
93
|
-
const isCriticalOverload = memCurrentBytes > criticalOverloadBytes;
|
|
94
|
-
if (isCriticalOverload) {
|
|
95
|
-
const usedPercentage = Math.round((memCurrentBytes / effectiveMax) * 100);
|
|
96
|
-
const toMb = (bytes) => Math.round(bytes / 1024 ** 2);
|
|
97
|
-
this.#log.warning('Memory is critically overloaded. ' +
|
|
98
|
-
`Using ${toMb(memCurrentBytes)} MB of ${toMb(effectiveMax)} MB (${usedPercentage}%). Consider increasing available memory.`);
|
|
99
|
-
this.#lastLoggedCriticalMemoryOverloadAt = createdAt;
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
async getTotalMemoryBytes() {
|
|
103
|
-
const containerized = this.#config.containerized ?? (await isContainerized());
|
|
104
|
-
return (await getMemoryInfo({ containerized, logger: serviceLocator.getLogger() })).totalBytes;
|
|
105
|
-
}
|
|
106
|
-
}
|
|
@@ -1,84 +0,0 @@
|
|
|
1
|
-
import type { CpuLoadSignalOptions } from './cpu_load_signal.js';
|
|
2
|
-
import type { EventLoopLoadSignalOptions } from './event_loop_load_signal.js';
|
|
3
|
-
import type { LoadSignal, LoadSignalStartContext } from './load_signal.js';
|
|
4
|
-
import type { MemoryLoadSignalOptions } from './memory_load_signal.js';
|
|
5
|
-
import type { StorageBackendLoadSignalOptions } from './storage_backend_load_signal.js';
|
|
6
|
-
/**
|
|
7
|
-
* The load signals a {@link ConcurrencySystem} watches to decide whether the machine is overloaded.
|
|
8
|
-
*
|
|
9
|
-
* Each of the four built-in signals is configured by passing its options bag — shorthand for constructing the
|
|
10
|
-
* corresponding {@link LoadSignal} class yourself, so `{ cpu: { overloadedRatio: 0.5 } }` is exactly
|
|
11
|
-
* `{ cpu: false, custom: [new CpuLoadSignal({ overloadedRatio: 0.5 })] }`. Pass `false` to leave a resource
|
|
12
|
-
* unwatched, and put anything else you want taken into account in {@link LoadSignalsOptions.custom|`custom`}.
|
|
13
|
-
*
|
|
14
|
-
* How far back the signals are evaluated is *not* set here, but by
|
|
15
|
-
* {@link ConcurrencySystemOptions.snapshotHistorySecs|`snapshotHistorySecs`} and
|
|
16
|
-
* {@link ConcurrencySystemOptions.currentHistorySecs|`currentHistorySecs`}.
|
|
17
|
-
*/
|
|
18
|
-
export interface LoadSignalsOptions {
|
|
19
|
-
/**
|
|
20
|
-
* Tuning for the built-in {@link MemoryLoadSignal} (used-memory limit + overload ratio), or `false` to switch
|
|
21
|
-
* it off.
|
|
22
|
-
*/
|
|
23
|
-
memory?: MemoryLoadSignalOptions | false;
|
|
24
|
-
/**
|
|
25
|
-
* Tuning for the built-in {@link EventLoopLoadSignal} (snapshot interval + blocked-millis limit + overload
|
|
26
|
-
* ratio), or `false` to switch it off — which also stops its measuring interval.
|
|
27
|
-
*/
|
|
28
|
-
eventLoop?: EventLoopLoadSignalOptions | false;
|
|
29
|
-
/**
|
|
30
|
-
* Tuning for the built-in {@link CpuLoadSignal} (overload ratio), or `false` to switch it off.
|
|
31
|
-
*/
|
|
32
|
-
cpu?: CpuLoadSignalOptions | false;
|
|
33
|
-
/**
|
|
34
|
-
* Tuning for the built-in {@link StorageBackendLoadSignal} (snapshot interval + error limit + overload ratio),
|
|
35
|
-
* or `false` to switch it off — worth doing when the storage backend reports no rate-limit statistics, since the
|
|
36
|
-
* signal otherwise polls it every second to no purpose.
|
|
37
|
-
*/
|
|
38
|
-
storageBackend?: StorageBackendLoadSignalOptions | false;
|
|
39
|
-
/**
|
|
40
|
-
* Additional {@link LoadSignal} implementations — e.g. navigation timeouts or proxy health — evaluated
|
|
41
|
-
* alongside the built-in four. If any signal reports overload, the system counts as overloaded. Their lifecycle
|
|
42
|
-
* is driven by the {@link ConcurrencySystem} they are given to, and their {@link LoadSignal.name|names} must
|
|
43
|
-
* not collide with an enabled built-in's.
|
|
44
|
-
*/
|
|
45
|
-
custom?: LoadSignal[];
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
|
-
* An implementation detail of the {@link ConcurrencySystem}: the built-in signal tuning from
|
|
49
|
-
* {@link LoadSignalsOptions}, minus the custom signals, which the system evaluates itself rather than collecting
|
|
50
|
-
* them here.
|
|
51
|
-
* @internal
|
|
52
|
-
*/
|
|
53
|
-
export type SnapshotterOptions = Omit<LoadSignalsOptions, 'custom'>;
|
|
54
|
-
/**
|
|
55
|
-
* Owns the four built-in {@link LoadSignal} instances — {@link MemoryLoadSignal},
|
|
56
|
-
* {@link EventLoopLoadSignal}, {@link CpuLoadSignal} and {@link StorageBackendLoadSignal} — constructing
|
|
57
|
-
* the ones that were not switched off and driving their shared lifecycle.
|
|
58
|
-
*
|
|
59
|
-
* Configured indirectly through {@link ConcurrencySystemOptions.loadSignals|`loadSignals`}, whose per-signal bags
|
|
60
|
-
* are simply forwarded to the corresponding constructor.
|
|
61
|
-
* @internal
|
|
62
|
-
*/
|
|
63
|
-
export declare class Snapshotter {
|
|
64
|
-
#private;
|
|
65
|
-
/**
|
|
66
|
-
* Returns the enabled built-in signals, so `SystemStatus` can iterate them alongside any custom `LoadSignal`
|
|
67
|
-
* instances. Signals switched off through the options are simply absent — the system status reports them as
|
|
68
|
-
* not overloaded.
|
|
69
|
-
*/
|
|
70
|
-
getLoadSignals(): LoadSignal[];
|
|
71
|
-
/**
|
|
72
|
-
* @param [options] All `Snapshotter` configuration options.
|
|
73
|
-
*/
|
|
74
|
-
constructor(options?: SnapshotterOptions);
|
|
75
|
-
/**
|
|
76
|
-
* Starts capturing snapshots at configured intervals. The `context` carries the sample window the signals will
|
|
77
|
-
* be queried with, which is also how much history they retain.
|
|
78
|
-
*/
|
|
79
|
-
start(context: LoadSignalStartContext): Promise<void>;
|
|
80
|
-
/**
|
|
81
|
-
* Stops all resource capturing.
|
|
82
|
-
*/
|
|
83
|
-
stop(): Promise<void>;
|
|
84
|
-
}
|
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
import { CpuLoadSignal } from './cpu_load_signal.js';
|
|
2
|
-
import { EventLoopLoadSignal } from './event_loop_load_signal.js';
|
|
3
|
-
import { MemoryLoadSignal } from './memory_load_signal.js';
|
|
4
|
-
import { StorageBackendLoadSignal } from './storage_backend_load_signal.js';
|
|
5
|
-
/**
|
|
6
|
-
* Owns the four built-in {@link LoadSignal} instances — {@link MemoryLoadSignal},
|
|
7
|
-
* {@link EventLoopLoadSignal}, {@link CpuLoadSignal} and {@link StorageBackendLoadSignal} — constructing
|
|
8
|
-
* the ones that were not switched off and driving their shared lifecycle.
|
|
9
|
-
*
|
|
10
|
-
* Configured indirectly through {@link ConcurrencySystemOptions.loadSignals|`loadSignals`}, whose per-signal bags
|
|
11
|
-
* are simply forwarded to the corresponding constructor.
|
|
12
|
-
* @internal
|
|
13
|
-
*/
|
|
14
|
-
export class Snapshotter {
|
|
15
|
-
// Absent when switched off through the corresponding option (e.g. `storageBackend: false`).
|
|
16
|
-
#memorySignal;
|
|
17
|
-
#eventLoopSignal;
|
|
18
|
-
#cpuSignal;
|
|
19
|
-
#storageBackendSignal;
|
|
20
|
-
/**
|
|
21
|
-
* Returns the enabled built-in signals, so `SystemStatus` can iterate them alongside any custom `LoadSignal`
|
|
22
|
-
* instances. Signals switched off through the options are simply absent — the system status reports them as
|
|
23
|
-
* not overloaded.
|
|
24
|
-
*/
|
|
25
|
-
getLoadSignals() {
|
|
26
|
-
const builtin = [
|
|
27
|
-
this.#memorySignal,
|
|
28
|
-
this.#eventLoopSignal,
|
|
29
|
-
this.#cpuSignal,
|
|
30
|
-
this.#storageBackendSignal,
|
|
31
|
-
];
|
|
32
|
-
return builtin.filter((signal) => signal !== undefined);
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* @param [options] All `Snapshotter` configuration options.
|
|
36
|
-
*/
|
|
37
|
-
constructor(options = {}) {
|
|
38
|
-
const { memory = {}, eventLoop = {}, cpu = {}, storageBackend = {} } = options;
|
|
39
|
-
// Each signal resolves its own ambient dependencies when started, and is told the window it will be sampled
|
|
40
|
-
// over then too - so there is nothing to thread in here beyond the caller's tuning.
|
|
41
|
-
if (memory !== false)
|
|
42
|
-
this.#memorySignal = new MemoryLoadSignal(memory);
|
|
43
|
-
if (eventLoop !== false)
|
|
44
|
-
this.#eventLoopSignal = new EventLoopLoadSignal(eventLoop);
|
|
45
|
-
if (cpu !== false)
|
|
46
|
-
this.#cpuSignal = new CpuLoadSignal(cpu);
|
|
47
|
-
if (storageBackend !== false)
|
|
48
|
-
this.#storageBackendSignal = new StorageBackendLoadSignal(storageBackend);
|
|
49
|
-
}
|
|
50
|
-
/**
|
|
51
|
-
* Starts capturing snapshots at configured intervals. The `context` carries the sample window the signals will
|
|
52
|
-
* be queried with, which is also how much history they retain.
|
|
53
|
-
*/
|
|
54
|
-
async start(context) {
|
|
55
|
-
await Promise.all(this.getLoadSignals().map(async (signal) => signal.start(context)));
|
|
56
|
-
}
|
|
57
|
-
/**
|
|
58
|
-
* Stops all resource capturing.
|
|
59
|
-
*/
|
|
60
|
-
async stop() {
|
|
61
|
-
await Promise.all(this.getLoadSignals().map(async (signal) => signal.stop()));
|
|
62
|
-
// Allow microtask queue to unwind before stop returns.
|
|
63
|
-
await new Promise((resolve) => {
|
|
64
|
-
setImmediate(resolve);
|
|
65
|
-
});
|
|
66
|
-
}
|
|
67
|
-
}
|
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
import type { LoadSignal, LoadSignalStartContext, LoadSnapshot } from './load_signal.js';
|
|
2
|
-
/**
|
|
3
|
-
* A snapshot produced by the built-in storage backend (rate-limit) signal.
|
|
4
|
-
* @internal
|
|
5
|
-
*/
|
|
6
|
-
export interface StorageBackendSnapshot extends LoadSnapshot {
|
|
7
|
-
rateLimitErrorCount: number;
|
|
8
|
-
}
|
|
9
|
-
/**
|
|
10
|
-
* Tuning for the built-in **storage backend** (rate-limit) load signal, as accepted both by
|
|
11
|
-
* {@link StorageBackendLoadSignal} and by the
|
|
12
|
-
* {@link LoadSignalsOptions.storageBackend|`storageBackend`} shorthand on {@link LoadSignalsOptions}.
|
|
13
|
-
*/
|
|
14
|
-
export interface StorageBackendLoadSignalOptions {
|
|
15
|
-
/**
|
|
16
|
-
* Defines the interval of checking the current state of the storage backend, in seconds.
|
|
17
|
-
* @default 1
|
|
18
|
-
*/
|
|
19
|
-
snapshotIntervalSecs?: number;
|
|
20
|
-
/**
|
|
21
|
-
* Defines the maximum number of new rate limit errors within the given interval.
|
|
22
|
-
* @default 3
|
|
23
|
-
*/
|
|
24
|
-
maxErrors?: number;
|
|
25
|
-
/**
|
|
26
|
-
* Maximum ratio of overloaded snapshots in a sample before the storage backend counts as overloaded.
|
|
27
|
-
* @default 0.3
|
|
28
|
-
*/
|
|
29
|
-
overloadedRatio?: number;
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* Periodically checks the storage backend for rate-limit errors (HTTP 429) and reports overload when the error delta
|
|
33
|
-
* exceeds a threshold.
|
|
34
|
-
*
|
|
35
|
-
* Built by default; construct one yourself only to wrap or adapt it — see {@link LoadSignal}.
|
|
36
|
-
*
|
|
37
|
-
* Switch it off entirely ({@link LoadSignalsOptions.storageBackend|`storageBackend: false`}) if the storage backend
|
|
38
|
-
* reports no rate-limit statistics, since it otherwise polls it every second to no purpose.
|
|
39
|
-
*
|
|
40
|
-
* @category Scaling
|
|
41
|
-
*/
|
|
42
|
-
export declare class StorageBackendLoadSignal implements LoadSignal {
|
|
43
|
-
#private;
|
|
44
|
-
readonly name = "storageBackendInfo";
|
|
45
|
-
readonly overloadedRatio: number;
|
|
46
|
-
constructor(options?: StorageBackendLoadSignalOptions);
|
|
47
|
-
start(context: LoadSignalStartContext): Promise<void>;
|
|
48
|
-
stop(): Promise<void>;
|
|
49
|
-
getSample(sampleDurationMillis?: number): LoadSnapshot[];
|
|
50
|
-
/**
|
|
51
|
-
* Records one snapshot, overloaded when rate-limit errors grew by more than the configured limit since the
|
|
52
|
-
* previous one.
|
|
53
|
-
* @internal Also lets tests drive the measurement without waiting on a timer.
|
|
54
|
-
*/
|
|
55
|
-
handle(intervalCallback: () => unknown): void;
|
|
56
|
-
}
|
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
import { betterClearInterval, betterSetInterval } from '@apify/utilities';
|
|
2
|
-
import { serviceLocator } from '../service_locator.js';
|
|
3
|
-
import { SnapshotStore } from './load_signal.js';
|
|
4
|
-
const RATE_LIMIT_ERROR_RETRY_COUNT = 2;
|
|
5
|
-
/**
|
|
6
|
-
* Periodically checks the storage backend for rate-limit errors (HTTP 429) and reports overload when the error delta
|
|
7
|
-
* exceeds a threshold.
|
|
8
|
-
*
|
|
9
|
-
* Built by default; construct one yourself only to wrap or adapt it — see {@link LoadSignal}.
|
|
10
|
-
*
|
|
11
|
-
* Switch it off entirely ({@link LoadSignalsOptions.storageBackend|`storageBackend: false`}) if the storage backend
|
|
12
|
-
* reports no rate-limit statistics, since it otherwise polls it every second to no purpose.
|
|
13
|
-
*
|
|
14
|
-
* @category Scaling
|
|
15
|
-
*/
|
|
16
|
-
export class StorageBackendLoadSignal {
|
|
17
|
-
name = 'storageBackendInfo';
|
|
18
|
-
overloadedRatio;
|
|
19
|
-
#store = new SnapshotStore();
|
|
20
|
-
#intervalMillis;
|
|
21
|
-
#maxErrors;
|
|
22
|
-
#interval;
|
|
23
|
-
#storageBackend;
|
|
24
|
-
constructor(options = {}) {
|
|
25
|
-
this.overloadedRatio = options.overloadedRatio ?? 0.3;
|
|
26
|
-
this.#intervalMillis = (options.snapshotIntervalSecs ?? 1) * 1000;
|
|
27
|
-
this.#maxErrors = options.maxErrors ?? 3;
|
|
28
|
-
this.handle = this.handle.bind(this);
|
|
29
|
-
}
|
|
30
|
-
async start(context) {
|
|
31
|
-
this.#store.useSampleWindow(context.maxSampleWindowMillis);
|
|
32
|
-
// A new session starts from a clean slate, or its first measurement diffs the error count against the previous
|
|
33
|
-
// session's — possibly against a different backend, since it is resolved afresh just below.
|
|
34
|
-
this.#store.clear();
|
|
35
|
-
// Resolved here rather than in the constructor, where asking for the backend would instantiate a default one
|
|
36
|
-
// as a side effect - long before the crawler that owns the run has had a chance to register its own.
|
|
37
|
-
this.#storageBackend = serviceLocator.getStorageBackend();
|
|
38
|
-
this.#interval = betterSetInterval(this.handle, this.#intervalMillis);
|
|
39
|
-
}
|
|
40
|
-
async stop() {
|
|
41
|
-
if (this.#interval)
|
|
42
|
-
betterClearInterval(this.#interval);
|
|
43
|
-
this.#interval = undefined;
|
|
44
|
-
this.#storageBackend = undefined;
|
|
45
|
-
}
|
|
46
|
-
getSample(sampleDurationMillis) {
|
|
47
|
-
return this.#store.getSample(sampleDurationMillis);
|
|
48
|
-
}
|
|
49
|
-
/**
|
|
50
|
-
* Records one snapshot, overloaded when rate-limit errors grew by more than the configured limit since the
|
|
51
|
-
* previous one.
|
|
52
|
-
* @internal Also lets tests drive the measurement without waiting on a timer.
|
|
53
|
-
*/
|
|
54
|
-
handle(intervalCallback) {
|
|
55
|
-
const now = new Date();
|
|
56
|
-
const allErrorCounts = this.#storageBackend?.stats?.rateLimitErrors ?? [];
|
|
57
|
-
const currentErrCount = allErrorCounts[RATE_LIMIT_ERROR_RETRY_COUNT] || 0;
|
|
58
|
-
const snapshot = {
|
|
59
|
-
createdAt: now,
|
|
60
|
-
isOverloaded: false,
|
|
61
|
-
rateLimitErrorCount: currentErrCount,
|
|
62
|
-
};
|
|
63
|
-
const all = this.#store.getAll();
|
|
64
|
-
const previousSnapshot = all[all.length - 1];
|
|
65
|
-
if (previousSnapshot) {
|
|
66
|
-
const delta = currentErrCount - previousSnapshot.rateLimitErrorCount;
|
|
67
|
-
if (delta > this.#maxErrors)
|
|
68
|
-
snapshot.isOverloaded = true;
|
|
69
|
-
}
|
|
70
|
-
this.#store.push(snapshot, now);
|
|
71
|
-
intervalCallback();
|
|
72
|
-
}
|
|
73
|
-
}
|