@crawlee/core 4.0.0-beta.15 → 4.0.0-beta.150
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 +14 -14
- package/autoscaling/autoscaled_pool.d.ts +73 -177
- package/autoscaling/autoscaled_pool.js +182 -329
- package/autoscaling/concurrency_system.d.ts +268 -0
- package/autoscaling/concurrency_system.js +364 -0
- package/autoscaling/cpu_load_signal.d.ts +43 -0
- package/autoscaling/cpu_load_signal.js +47 -0
- package/autoscaling/event_loop_load_signal.d.ts +51 -0
- package/autoscaling/event_loop_load_signal.js +60 -0
- package/autoscaling/index.d.ts +6 -1
- package/autoscaling/index.js +6 -1
- package/autoscaling/load_signal.d.ts +98 -0
- package/autoscaling/load_signal.js +103 -0
- package/autoscaling/memory_load_signal.d.ts +47 -0
- package/autoscaling/memory_load_signal.js +106 -0
- package/autoscaling/snapshotter.d.ts +58 -163
- package/autoscaling/snapshotter.js +45 -263
- package/autoscaling/storage_backend_load_signal.d.ts +56 -0
- package/autoscaling/storage_backend_load_signal.js +73 -0
- package/autoscaling/system_status.d.ts +67 -89
- package/autoscaling/system_status.js +92 -122
- package/autoscaling/weighted_avg.d.ts +5 -0
- package/autoscaling/weighted_avg.js +14 -0
- package/byte_utils.d.ts +17 -0
- package/byte_utils.js +42 -0
- package/configuration.d.ts +96 -223
- package/configuration.js +170 -222
- package/cookie_utils.d.ts +3 -2
- package/cookie_utils.js +18 -7
- package/crawlers/context_pipeline.d.ts +10 -1
- package/crawlers/context_pipeline.js +31 -8
- package/crawlers/crawler_commons.d.ts +90 -126
- package/crawlers/crawler_commons.js +1 -108
- package/crawlers/error_snapshotter.d.ts +2 -5
- package/crawlers/error_snapshotter.js +7 -8
- package/crawlers/error_tracker.d.ts +0 -1
- package/crawlers/error_tracker.js +0 -1
- package/crawlers/index.d.ts +1 -3
- package/crawlers/index.js +0 -3
- package/crawlers/internals/types.d.ts +0 -1
- package/crawlers/internals/types.js +0 -1
- package/crawlers/statistics.d.ts +187 -64
- package/crawlers/statistics.js +354 -165
- package/debug.d.ts +36 -0
- package/debug.js +70 -0
- package/enqueue_links/enqueue_links.d.ts +61 -154
- package/enqueue_links/enqueue_links.js +40 -232
- package/enqueue_links/index.d.ts +0 -1
- package/enqueue_links/index.js +0 -1
- package/enqueue_links/shared.d.ts +55 -28
- package/enqueue_links/shared.js +116 -69
- package/errors.d.ts +72 -4
- package/errors.js +89 -5
- package/events/event_manager.d.ts +35 -9
- package/events/event_manager.js +12 -13
- package/events/index.d.ts +0 -1
- package/events/index.js +0 -1
- package/events/local_event_manager.d.ts +15 -3
- package/events/local_event_manager.js +39 -13
- package/http.d.ts +9 -0
- package/http.js +28 -0
- package/index.d.ts +7 -5
- package/index.js +8 -4
- package/iterables.d.ts +79 -0
- package/iterables.js +134 -0
- package/log.d.ts +77 -1
- package/log.js +104 -1
- package/memory-storage/consts.d.ts +4 -0
- package/memory-storage/consts.js +4 -0
- package/memory-storage/index.d.ts +1 -0
- package/memory-storage/index.js +1 -0
- package/memory-storage/memory-storage.d.ts +44 -0
- package/memory-storage/memory-storage.js +160 -0
- package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
- package/memory-storage/resource-clients/common/base-client.js +6 -0
- package/memory-storage/resource-clients/dataset.d.ts +40 -0
- package/memory-storage/resource-clients/dataset.js +106 -0
- package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
- package/memory-storage/resource-clients/key-value-store.js +199 -0
- package/memory-storage/resource-clients/request-queue.d.ts +77 -0
- package/memory-storage/resource-clients/request-queue.js +407 -0
- package/memory-storage/utils.d.ts +16 -0
- package/memory-storage/utils.js +41 -0
- package/owned_or_injected.d.ts +58 -0
- package/owned_or_injected.js +98 -0
- package/package.json +13 -12
- package/proxy_configuration.d.ts +22 -128
- package/proxy_configuration.js +32 -144
- package/recoverable_state.d.ts +83 -51
- package/recoverable_state.js +163 -72
- package/request.d.ts +57 -16
- package/request.js +130 -69
- package/router.d.ts +193 -21
- package/router.js +188 -43
- package/serialization.d.ts +0 -1
- package/serialization.js +15 -15
- package/service_locator.d.ts +165 -0
- package/service_locator.js +253 -0
- package/session_pool/consts.d.ts +1 -2
- package/session_pool/consts.js +1 -2
- package/session_pool/errors.d.ts +0 -1
- package/session_pool/errors.js +0 -1
- package/session_pool/fingerprint.d.ts +9 -0
- package/session_pool/fingerprint.js +30 -0
- package/session_pool/index.d.ts +0 -2
- package/session_pool/index.js +0 -2
- package/session_pool/session.d.ts +39 -89
- package/session_pool/session.js +102 -159
- package/session_pool/session_pool.d.ts +67 -91
- package/session_pool/session_pool.js +196 -187
- package/storages/batched_adds.d.ts +37 -0
- package/storages/batched_adds.js +73 -0
- package/storages/dataset.d.ts +109 -56
- package/storages/dataset.js +284 -149
- package/storages/index.d.ts +9 -9
- package/storages/index.js +7 -9
- package/storages/key_value_store.d.ts +183 -48
- package/storages/key_value_store.js +444 -171
- package/storages/key_value_store_codec.d.ts +32 -0
- package/storages/key_value_store_codec.js +113 -0
- package/storages/request_dedup_cache.d.ts +22 -0
- package/storages/request_dedup_cache.js +48 -0
- package/storages/request_list.d.ts +53 -115
- package/storages/request_list.js +194 -167
- package/storages/request_loader.d.ts +133 -0
- package/storages/request_loader.js +36 -0
- package/storages/request_manager.d.ts +109 -0
- package/storages/request_manager.js +1 -0
- package/storages/request_manager_tandem.d.ts +55 -23
- package/storages/request_manager_tandem.js +139 -57
- package/storages/request_queue.d.ts +286 -48
- package/storages/request_queue.js +757 -218
- package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +43 -91
- package/storages/sitemap_request_loader.js +439 -0
- package/storages/storage_instance_manager.d.ts +87 -0
- package/storages/storage_instance_manager.js +256 -0
- package/storages/storage_stats.d.ts +48 -0
- package/storages/storage_stats.js +29 -0
- package/storages/throttling_request_manager.d.ts +222 -0
- package/storages/throttling_request_manager.js +780 -0
- package/storages/transaction.d.ts +252 -0
- package/storages/transaction.js +251 -0
- package/storages/utils.d.ts +59 -11
- package/storages/utils.js +75 -15
- package/system-info/cpu-info.d.ts +67 -0
- package/system-info/cpu-info.js +216 -0
- package/system-info/memory-info.d.ts +31 -0
- package/system-info/memory-info.js +115 -0
- package/system-info/ps-tree.d.ts +17 -0
- package/system-info/ps-tree.js +144 -0
- package/system-info/runtime.d.ts +14 -0
- package/system-info/runtime.js +80 -0
- package/typedefs.d.ts +0 -6
- package/typedefs.js +0 -1
- package/url.d.ts +9 -0
- package/url.js +11 -0
- package/validators.d.ts +22 -18
- package/validators.js +13 -18
- package/autoscaling/autoscaled_pool.d.ts.map +0 -1
- package/autoscaling/autoscaled_pool.js.map +0 -1
- package/autoscaling/index.d.ts.map +0 -1
- package/autoscaling/index.js.map +0 -1
- package/autoscaling/snapshotter.d.ts.map +0 -1
- package/autoscaling/snapshotter.js.map +0 -1
- package/autoscaling/system_status.d.ts.map +0 -1
- package/autoscaling/system_status.js.map +0 -1
- package/configuration.d.ts.map +0 -1
- package/configuration.js.map +0 -1
- package/cookie_utils.d.ts.map +0 -1
- package/cookie_utils.js.map +0 -1
- package/crawlers/context_pipeline.d.ts.map +0 -1
- package/crawlers/context_pipeline.js.map +0 -1
- package/crawlers/crawler_commons.d.ts.map +0 -1
- package/crawlers/crawler_commons.js.map +0 -1
- package/crawlers/crawler_utils.d.ts +0 -10
- package/crawlers/crawler_utils.d.ts.map +0 -1
- package/crawlers/crawler_utils.js +0 -12
- package/crawlers/crawler_utils.js.map +0 -1
- package/crawlers/error_snapshotter.d.ts.map +0 -1
- package/crawlers/error_snapshotter.js.map +0 -1
- package/crawlers/error_tracker.d.ts.map +0 -1
- package/crawlers/error_tracker.js.map +0 -1
- package/crawlers/index.d.ts.map +0 -1
- package/crawlers/index.js.map +0 -1
- package/crawlers/internals/types.d.ts.map +0 -1
- package/crawlers/internals/types.js.map +0 -1
- package/crawlers/statistics.d.ts.map +0 -1
- package/crawlers/statistics.js.map +0 -1
- package/enqueue_links/enqueue_links.d.ts.map +0 -1
- package/enqueue_links/enqueue_links.js.map +0 -1
- package/enqueue_links/index.d.ts.map +0 -1
- package/enqueue_links/index.js.map +0 -1
- package/enqueue_links/shared.d.ts.map +0 -1
- package/enqueue_links/shared.js.map +0 -1
- package/errors.d.ts.map +0 -1
- package/errors.js.map +0 -1
- package/events/event_manager.d.ts.map +0 -1
- package/events/event_manager.js.map +0 -1
- package/events/index.d.ts.map +0 -1
- package/events/index.js.map +0 -1
- package/events/local_event_manager.d.ts.map +0 -1
- package/events/local_event_manager.js.map +0 -1
- package/http_clients/base-http-client.d.ts +0 -140
- package/http_clients/base-http-client.d.ts.map +0 -1
- package/http_clients/base-http-client.js +0 -40
- package/http_clients/base-http-client.js.map +0 -1
- package/http_clients/form-data-like.d.ts +0 -67
- package/http_clients/form-data-like.d.ts.map +0 -1
- package/http_clients/form-data-like.js +0 -5
- package/http_clients/form-data-like.js.map +0 -1
- package/http_clients/got-scraping-http-client.d.ts +0 -20
- package/http_clients/got-scraping-http-client.d.ts.map +0 -1
- package/http_clients/got-scraping-http-client.js +0 -85
- package/http_clients/got-scraping-http-client.js.map +0 -1
- package/http_clients/index.d.ts +0 -3
- package/http_clients/index.d.ts.map +0 -1
- package/http_clients/index.js +0 -3
- package/http_clients/index.js.map +0 -1
- package/index.d.ts.map +0 -1
- package/index.js.map +0 -1
- package/log.d.ts.map +0 -1
- package/log.js.map +0 -1
- package/proxy_configuration.d.ts.map +0 -1
- package/proxy_configuration.js.map +0 -1
- package/recoverable_state.d.ts.map +0 -1
- package/recoverable_state.js.map +0 -1
- package/request.d.ts.map +0 -1
- package/request.js.map +0 -1
- package/router.d.ts.map +0 -1
- package/router.js.map +0 -1
- package/serialization.d.ts.map +0 -1
- package/serialization.js.map +0 -1
- package/session_pool/consts.d.ts.map +0 -1
- package/session_pool/consts.js.map +0 -1
- package/session_pool/errors.d.ts.map +0 -1
- package/session_pool/errors.js.map +0 -1
- package/session_pool/events.d.ts +0 -3
- package/session_pool/events.d.ts.map +0 -1
- package/session_pool/events.js +0 -3
- package/session_pool/events.js.map +0 -1
- package/session_pool/index.d.ts.map +0 -1
- package/session_pool/index.js.map +0 -1
- package/session_pool/session.d.ts.map +0 -1
- package/session_pool/session.js.map +0 -1
- package/session_pool/session_pool.d.ts.map +0 -1
- package/session_pool/session_pool.js.map +0 -1
- package/storages/access_checking.d.ts +0 -13
- package/storages/access_checking.d.ts.map +0 -1
- package/storages/access_checking.js +0 -14
- package/storages/access_checking.js.map +0 -1
- package/storages/dataset.d.ts.map +0 -1
- package/storages/dataset.js.map +0 -1
- package/storages/index.d.ts.map +0 -1
- package/storages/index.js.map +0 -1
- package/storages/key_value_store.d.ts.map +0 -1
- package/storages/key_value_store.js.map +0 -1
- package/storages/request_list.d.ts.map +0 -1
- package/storages/request_list.js.map +0 -1
- package/storages/request_list_adapter.d.ts +0 -58
- package/storages/request_list_adapter.d.ts.map +0 -1
- package/storages/request_list_adapter.js +0 -81
- package/storages/request_list_adapter.js.map +0 -1
- package/storages/request_manager_tandem.d.ts.map +0 -1
- package/storages/request_manager_tandem.js.map +0 -1
- package/storages/request_provider.d.ts +0 -371
- package/storages/request_provider.d.ts.map +0 -1
- package/storages/request_provider.js +0 -585
- package/storages/request_provider.js.map +0 -1
- package/storages/request_queue.d.ts.map +0 -1
- package/storages/request_queue.js.map +0 -1
- package/storages/request_queue_v2.d.ts +0 -87
- package/storages/request_queue_v2.d.ts.map +0 -1
- package/storages/request_queue_v2.js +0 -438
- package/storages/request_queue_v2.js.map +0 -1
- package/storages/sitemap_request_list.d.ts.map +0 -1
- package/storages/sitemap_request_list.js +0 -430
- package/storages/sitemap_request_list.js.map +0 -1
- package/storages/storage_manager.d.ts +0 -58
- package/storages/storage_manager.d.ts.map +0 -1
- package/storages/storage_manager.js +0 -105
- package/storages/storage_manager.js.map +0 -1
- package/storages/utils.d.ts.map +0 -1
- package/storages/utils.js.map +0 -1
- package/typedefs.d.ts.map +0 -1
- package/typedefs.js.map +0 -1
- package/validators.d.ts.map +0 -1
- package/validators.js.map +0 -1
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type { Constructor, DatasetBackend, KeyValueStoreBackend, RequestQueueBackend, StorageBackend, StorageIdentifier } from '@crawlee/types';
|
|
2
|
+
export type { StorageIdentifier } from '@crawlee/types';
|
|
3
|
+
/**
|
|
4
|
+
* Matches an `IStorage` – a storage "frontend" (Dataset, KeyValueStore, RequestQueue).
|
|
5
|
+
*/
|
|
6
|
+
export interface IStorage {
|
|
7
|
+
id: string;
|
|
8
|
+
name?: string;
|
|
9
|
+
}
|
|
10
|
+
type Hashable = string;
|
|
11
|
+
/**
|
|
12
|
+
* Unified manager for opening and caching storage instances (Dataset, KeyValueStore, RequestQueue).
|
|
13
|
+
*
|
|
14
|
+
* A single instance manages all storage types. Instances are cached by
|
|
15
|
+
* `(storageClass, id/name/alias, backendCacheKey)` so the same storage is never opened twice.
|
|
16
|
+
*
|
|
17
|
+
* The manager itself does not resolve identifiers — callers pass explicit `id`, `name`, or `alias` (at most one),
|
|
18
|
+
* and a pre-bound `backendOpener` promise. When none of `id`, `name`, `alias` are provided, the manager automatically
|
|
19
|
+
* assigns a reserved default alias.
|
|
20
|
+
*/
|
|
21
|
+
export declare class StorageInstanceManager {
|
|
22
|
+
#private;
|
|
23
|
+
/**
|
|
24
|
+
* Open (or retrieve from cache) a storage instance.
|
|
25
|
+
*
|
|
26
|
+
* @param cls The storage class constructor (e.g. `Dataset`, `KeyValueStore`, `RequestQueue`).
|
|
27
|
+
* @param id Storage ID (mutually exclusive with `name` and `alias`).
|
|
28
|
+
* @param name Storage name (mutually exclusive with `id` and `alias`).
|
|
29
|
+
* @param alias Run-scoped alias (mutually exclusive with `id` and `name`).
|
|
30
|
+
* Automatically assigned when no identifier is provided.
|
|
31
|
+
* @param backendOpener A **lazy** factory that creates the sub-backend.
|
|
32
|
+
* Only called on a cache miss.
|
|
33
|
+
* @param backendCacheKey Opaque key identifying the storage backend, so that the same logical
|
|
34
|
+
* storage opened through different clients is cached separately.
|
|
35
|
+
*/
|
|
36
|
+
openStorage<TStorage extends IStorage>(cls: Constructor<TStorage>, { id, name, alias, backendOpener, backendCacheKey, }: (ExplicitStorageIdentifier | DefaultStorageIdentifier) & {
|
|
37
|
+
backendOpener: () => Promise<DatasetBackend | KeyValueStoreBackend | RequestQueueBackend>;
|
|
38
|
+
backendCacheKey: Hashable;
|
|
39
|
+
}): Promise<TStorage>;
|
|
40
|
+
/**
|
|
41
|
+
* Remove a storage instance from the cache (called from `storage.drop()`).
|
|
42
|
+
*/
|
|
43
|
+
removeFromCache(instance: IStorage): void;
|
|
44
|
+
/**
|
|
45
|
+
* Clear the entire cache. Also calls `clearCache()` on any cached KeyValueStore
|
|
46
|
+
* instances (duck-typed to avoid importing KeyValueStore and circular dependencies).
|
|
47
|
+
* Called during service locator reset.
|
|
48
|
+
*/
|
|
49
|
+
clearCache(): void;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* A storage identifier where exactly one of `id`, `name`, or `alias` is specified.
|
|
53
|
+
* Produced by {@link resolveStorageIdentifier} from ambiguous user input.
|
|
54
|
+
*/
|
|
55
|
+
export type ExplicitStorageIdentifier = {
|
|
56
|
+
id: string;
|
|
57
|
+
name?: never;
|
|
58
|
+
alias?: never;
|
|
59
|
+
} | {
|
|
60
|
+
id?: never;
|
|
61
|
+
name: string;
|
|
62
|
+
alias?: never;
|
|
63
|
+
} | {
|
|
64
|
+
id?: never;
|
|
65
|
+
name?: never;
|
|
66
|
+
alias: string;
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* Represents the case where no identifier was provided — the caller wants the default storage.
|
|
70
|
+
*/
|
|
71
|
+
export interface DefaultStorageIdentifier {
|
|
72
|
+
id?: never;
|
|
73
|
+
name?: never;
|
|
74
|
+
alias?: never;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Decompose a user-provided `identifier` (the `Dataset.open()` / `KeyValueStore.open()` /
|
|
78
|
+
* `RequestQueue.open()` argument) into separate `id`, `name`, and `alias` fields that
|
|
79
|
+
* the `StorageInstanceManager` and `StorageBackend.create*Client` expect.
|
|
80
|
+
*
|
|
81
|
+
* - `null` / `undefined` / `{}` → default storage alias
|
|
82
|
+
* - `string` → resolved via `storageExists` (ID-first, then name)
|
|
83
|
+
* - `{ id }` → `{ id }`
|
|
84
|
+
* - `{ name }` → `{ name }`
|
|
85
|
+
* - `{ alias }` → `{ alias }`
|
|
86
|
+
*/
|
|
87
|
+
export declare function resolveStorageIdentifier(identifier: string | StorageIdentifier | null | undefined, storageBackend: StorageBackend, storageType: 'Dataset' | 'KeyValueStore' | 'RequestQueue'): Promise<ExplicitStorageIdentifier>;
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import { AsyncQueue } from '@sapphire/async-queue';
|
|
2
|
+
/** Reserved alias for the default (unnamed) storage. */
|
|
3
|
+
const DEFAULT_STORAGE_ALIAS = '__default__';
|
|
4
|
+
/**
|
|
5
|
+
* Three-tier cache for storage instances, modelled after crawlee-python's `_StorageCache`.
|
|
6
|
+
*
|
|
7
|
+
* Each tier maps `[storageClass][key][backendCacheKey] → instance`:
|
|
8
|
+
* - `byId` — keyed by the backend-assigned storage id
|
|
9
|
+
* - `byName` — keyed by the persistent storage name
|
|
10
|
+
* - `byAlias` — keyed by a run-scoped alias (e.g. `'__default__'` for unnamed storages)
|
|
11
|
+
*/
|
|
12
|
+
class StorageCache {
|
|
13
|
+
byId = new Map();
|
|
14
|
+
byName = new Map();
|
|
15
|
+
byAlias = new Map();
|
|
16
|
+
get(cls, { id, name, alias, backendCacheKey, }) {
|
|
17
|
+
for (const [tier, key] of [
|
|
18
|
+
[this.byId, id],
|
|
19
|
+
[this.byName, name],
|
|
20
|
+
[this.byAlias, alias],
|
|
21
|
+
]) {
|
|
22
|
+
if (key === undefined)
|
|
23
|
+
continue;
|
|
24
|
+
const cached = tier.get(cls)?.get(key)?.get(backendCacheKey);
|
|
25
|
+
if (cached) {
|
|
26
|
+
if (cached instanceof cls) {
|
|
27
|
+
return cached;
|
|
28
|
+
}
|
|
29
|
+
throw new Error('Cached storage instance type mismatch.');
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
/** Write a single entry into a given tier. */
|
|
35
|
+
setInMap(tier, cls, key, instance, backendCacheKey) {
|
|
36
|
+
if (!tier.has(cls))
|
|
37
|
+
tier.set(cls, new Map());
|
|
38
|
+
const keyMap = tier.get(cls);
|
|
39
|
+
if (!keyMap.has(key))
|
|
40
|
+
keyMap.set(key, new Map());
|
|
41
|
+
keyMap.get(key).set(backendCacheKey, instance);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Cache an instance under its actual id, name, and an optional alias.
|
|
45
|
+
*/
|
|
46
|
+
set(cls, instance, backendCacheKey, alias) {
|
|
47
|
+
// Always cache by id.
|
|
48
|
+
this.setInMap(this.byId, cls, instance.id, instance, backendCacheKey);
|
|
49
|
+
// Cache by name — only for named storages.
|
|
50
|
+
if (instance.name) {
|
|
51
|
+
this.setInMap(this.byName, cls, instance.name, instance, backendCacheKey);
|
|
52
|
+
}
|
|
53
|
+
// Cache by alias — only for unnamed storages opened via alias.
|
|
54
|
+
if (alias !== undefined) {
|
|
55
|
+
this.setInMap(this.byAlias, cls, alias, instance, backendCacheKey);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
removeFromCache(instance) {
|
|
59
|
+
const storageType = instance.constructor;
|
|
60
|
+
for (const tier of [this.byId, this.byName, this.byAlias]) {
|
|
61
|
+
const classMap = tier.get(storageType);
|
|
62
|
+
if (!classMap)
|
|
63
|
+
continue;
|
|
64
|
+
for (const keyMap of classMap.values()) {
|
|
65
|
+
for (const [cacheKey, cached] of keyMap) {
|
|
66
|
+
if (cached === instance) {
|
|
67
|
+
keyMap.delete(cacheKey);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Ensure that the same string is not used as both a name and an alias for the same
|
|
75
|
+
* storage class + backend combination. Mirrors crawlee-python's `_check_name_alias_conflict`.
|
|
76
|
+
*/
|
|
77
|
+
checkNameAliasConflict(cls, { name, alias, backendCacheKey }) {
|
|
78
|
+
if (alias) {
|
|
79
|
+
const existingByName = this.byName.get(cls)?.get(alias)?.get(backendCacheKey);
|
|
80
|
+
if (existingByName) {
|
|
81
|
+
throw new Error(`Cannot open storage with alias "${alias}" because a named storage with the same identifier already exists.`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (name) {
|
|
85
|
+
const existingByAlias = this.byAlias.get(cls)?.get(name)?.get(backendCacheKey);
|
|
86
|
+
if (existingByAlias) {
|
|
87
|
+
throw new Error(`Cannot open storage with name "${name}" because an alias storage with the same identifier already exists.` +
|
|
88
|
+
` If you meant to open the alias storage, use { alias: "${name}" } instead.`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/** Iterate all cached instances across all storage types. */
|
|
93
|
+
*allValues() {
|
|
94
|
+
const seen = new Set();
|
|
95
|
+
for (const classMap of this.byId.values()) {
|
|
96
|
+
for (const keyMap of classMap.values()) {
|
|
97
|
+
for (const instance of keyMap.values()) {
|
|
98
|
+
if (!seen.has(instance)) {
|
|
99
|
+
seen.add(instance);
|
|
100
|
+
yield instance;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
clear() {
|
|
107
|
+
this.byId.clear();
|
|
108
|
+
this.byName.clear();
|
|
109
|
+
this.byAlias.clear();
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Unified manager for opening and caching storage instances (Dataset, KeyValueStore, RequestQueue).
|
|
114
|
+
*
|
|
115
|
+
* A single instance manages all storage types. Instances are cached by
|
|
116
|
+
* `(storageClass, id/name/alias, backendCacheKey)` so the same storage is never opened twice.
|
|
117
|
+
*
|
|
118
|
+
* The manager itself does not resolve identifiers — callers pass explicit `id`, `name`, or `alias` (at most one),
|
|
119
|
+
* and a pre-bound `backendOpener` promise. When none of `id`, `name`, `alias` are provided, the manager automatically
|
|
120
|
+
* assigns a reserved default alias.
|
|
121
|
+
*/
|
|
122
|
+
export class StorageInstanceManager {
|
|
123
|
+
#cache = new StorageCache();
|
|
124
|
+
#openerLocks = new Map();
|
|
125
|
+
/**
|
|
126
|
+
* Open (or retrieve from cache) a storage instance.
|
|
127
|
+
*
|
|
128
|
+
* @param cls The storage class constructor (e.g. `Dataset`, `KeyValueStore`, `RequestQueue`).
|
|
129
|
+
* @param id Storage ID (mutually exclusive with `name` and `alias`).
|
|
130
|
+
* @param name Storage name (mutually exclusive with `id` and `alias`).
|
|
131
|
+
* @param alias Run-scoped alias (mutually exclusive with `id` and `name`).
|
|
132
|
+
* Automatically assigned when no identifier is provided.
|
|
133
|
+
* @param backendOpener A **lazy** factory that creates the sub-backend.
|
|
134
|
+
* Only called on a cache miss.
|
|
135
|
+
* @param backendCacheKey Opaque key identifying the storage backend, so that the same logical
|
|
136
|
+
* storage opened through different clients is cached separately.
|
|
137
|
+
*/
|
|
138
|
+
async openStorage(cls, { id, name, alias, backendOpener, backendCacheKey, }) {
|
|
139
|
+
// Auto-set alias='__default__' when no parameters are specified (mirrors crawlee-python).
|
|
140
|
+
if (!id && !name && !alias) {
|
|
141
|
+
alias = DEFAULT_STORAGE_ALIAS;
|
|
142
|
+
}
|
|
143
|
+
// Fast-path cache check (no lock).
|
|
144
|
+
if (alias !== undefined) {
|
|
145
|
+
const cached = this.#cache.get(cls, { alias, backendCacheKey });
|
|
146
|
+
if (cached)
|
|
147
|
+
return cached;
|
|
148
|
+
}
|
|
149
|
+
else if (id) {
|
|
150
|
+
const cached = this.#cache.get(cls, { id, backendCacheKey });
|
|
151
|
+
if (cached)
|
|
152
|
+
return cached;
|
|
153
|
+
}
|
|
154
|
+
else if (name) {
|
|
155
|
+
const cached = this.#cache.get(cls, { name, backendCacheKey });
|
|
156
|
+
if (cached)
|
|
157
|
+
return cached;
|
|
158
|
+
}
|
|
159
|
+
const identifierKey = id ?? name ?? alias ?? DEFAULT_STORAGE_ALIAS;
|
|
160
|
+
const lockKey = `${cls.name}:${identifierKey}:${backendCacheKey}`;
|
|
161
|
+
if (!this.#openerLocks.has(lockKey)) {
|
|
162
|
+
this.#openerLocks.set(lockKey, new AsyncQueue());
|
|
163
|
+
}
|
|
164
|
+
const queue = this.#openerLocks.get(lockKey);
|
|
165
|
+
await queue.wait();
|
|
166
|
+
try {
|
|
167
|
+
// Double-check cache under lock (another caller may have filled it while we waited).
|
|
168
|
+
if (alias !== undefined) {
|
|
169
|
+
const cached = this.#cache.get(cls, { alias, backendCacheKey });
|
|
170
|
+
if (cached)
|
|
171
|
+
return cached;
|
|
172
|
+
}
|
|
173
|
+
else if (id) {
|
|
174
|
+
const cached = this.#cache.get(cls, { id, backendCacheKey });
|
|
175
|
+
if (cached)
|
|
176
|
+
return cached;
|
|
177
|
+
}
|
|
178
|
+
else if (name) {
|
|
179
|
+
const cached = this.#cache.get(cls, { name, backendCacheKey });
|
|
180
|
+
if (cached)
|
|
181
|
+
return cached;
|
|
182
|
+
}
|
|
183
|
+
// Prevent the same string from being used as both a name and an alias.
|
|
184
|
+
this.#cache.checkNameAliasConflict(cls, { name, alias, backendCacheKey });
|
|
185
|
+
// Cache miss — create the sub-backend and storage instance.
|
|
186
|
+
const subBackend = await backendOpener();
|
|
187
|
+
const storageInfo = await subBackend.getMetadata();
|
|
188
|
+
// Storage frontends are thin wrappers over the backend. We hand them the resolved metadata
|
|
189
|
+
// we just fetched (so `id`/`name` etc. are available synchronously) along with the backend.
|
|
190
|
+
const instance = new cls({ metadata: storageInfo, backend: subBackend });
|
|
191
|
+
// Atomic cache writes (no awaits between these).
|
|
192
|
+
this.#cache.set(cls, instance, backendCacheKey, alias);
|
|
193
|
+
return instance;
|
|
194
|
+
}
|
|
195
|
+
finally {
|
|
196
|
+
queue.shift();
|
|
197
|
+
// Clean up idle locks so the map doesn't grow unboundedly
|
|
198
|
+
// (mirrors crawlee-python's WeakValueDictionary behaviour).
|
|
199
|
+
if (queue.remaining === 0) {
|
|
200
|
+
this.#openerLocks.delete(lockKey);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Remove a storage instance from the cache (called from `storage.drop()`).
|
|
206
|
+
*/
|
|
207
|
+
removeFromCache(instance) {
|
|
208
|
+
this.#cache.removeFromCache(instance);
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Clear the entire cache. Also calls `clearCache()` on any cached KeyValueStore
|
|
212
|
+
* instances (duck-typed to avoid importing KeyValueStore and circular dependencies).
|
|
213
|
+
* Called during service locator reset.
|
|
214
|
+
*/
|
|
215
|
+
clearCache() {
|
|
216
|
+
for (const instance of this.#cache.allValues()) {
|
|
217
|
+
if ('clearCache' in instance && typeof instance.clearCache === 'function') {
|
|
218
|
+
instance.clearCache();
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
this.#cache.clear();
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Decompose a user-provided `identifier` (the `Dataset.open()` / `KeyValueStore.open()` /
|
|
226
|
+
* `RequestQueue.open()` argument) into separate `id`, `name`, and `alias` fields that
|
|
227
|
+
* the `StorageInstanceManager` and `StorageBackend.create*Client` expect.
|
|
228
|
+
*
|
|
229
|
+
* - `null` / `undefined` / `{}` → default storage alias
|
|
230
|
+
* - `string` → resolved via `storageExists` (ID-first, then name)
|
|
231
|
+
* - `{ id }` → `{ id }`
|
|
232
|
+
* - `{ name }` → `{ name }`
|
|
233
|
+
* - `{ alias }` → `{ alias }`
|
|
234
|
+
*/
|
|
235
|
+
export async function resolveStorageIdentifier(identifier, storageBackend, storageType) {
|
|
236
|
+
if (identifier === null || identifier === undefined) {
|
|
237
|
+
return { alias: DEFAULT_STORAGE_ALIAS };
|
|
238
|
+
}
|
|
239
|
+
if (typeof identifier === 'string') {
|
|
240
|
+
if (storageBackend.storageExists && (await storageBackend.storageExists(identifier, storageType))) {
|
|
241
|
+
return { id: identifier };
|
|
242
|
+
}
|
|
243
|
+
return { name: identifier };
|
|
244
|
+
}
|
|
245
|
+
if (identifier.id) {
|
|
246
|
+
return { id: identifier.id };
|
|
247
|
+
}
|
|
248
|
+
if (identifier.name) {
|
|
249
|
+
return { name: identifier.name };
|
|
250
|
+
}
|
|
251
|
+
if ('alias' in identifier && identifier.alias) {
|
|
252
|
+
return { alias: identifier.alias };
|
|
253
|
+
}
|
|
254
|
+
// Empty object — treated as default storage.
|
|
255
|
+
return { alias: DEFAULT_STORAGE_ALIAS };
|
|
256
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Backend-independent usage counters tracked by the storage frontend classes
|
|
3
|
+
* ({@link Dataset}, {@link KeyValueStore}, {@link RequestQueue}).
|
|
4
|
+
*
|
|
5
|
+
* These count the operations the frontend issues against its underlying storage backend, so they are
|
|
6
|
+
* meaningful for any storage backend (memory, file system, cloud). They are tallied per client call
|
|
7
|
+
* — e.g. iterating a key-value store increments `readCount` once per record fetched and `listCount`
|
|
8
|
+
* once per listed page. Backend-specific figures that the frontend cannot compute (such as the number
|
|
9
|
+
* of bytes stored) are intentionally not included here; read those from the backend's own API instead.
|
|
10
|
+
*/
|
|
11
|
+
/** Usage counters for a {@link Dataset}. */
|
|
12
|
+
export interface DatasetStats {
|
|
13
|
+
/** Number of read operations issued to the dataset client (e.g. `getData`). */
|
|
14
|
+
readCount: number;
|
|
15
|
+
/** Number of write operations issued to the dataset client (e.g. `pushData`). */
|
|
16
|
+
writeCount: number;
|
|
17
|
+
}
|
|
18
|
+
/** Usage counters for a {@link KeyValueStore}. */
|
|
19
|
+
export interface KeyValueStoreStats {
|
|
20
|
+
/** Number of read operations issued to the key-value store client (e.g. `getValue`). */
|
|
21
|
+
readCount: number;
|
|
22
|
+
/** Number of write operations issued to the key-value store client (e.g. `setValue`). */
|
|
23
|
+
writeCount: number;
|
|
24
|
+
/** Number of delete operations issued to the key-value store client (e.g. `deleteValue`). */
|
|
25
|
+
deleteCount: number;
|
|
26
|
+
/** Number of listing operations issued to the key-value store client (e.g. `listKeys`). */
|
|
27
|
+
listCount: number;
|
|
28
|
+
}
|
|
29
|
+
/** Usage counters for a {@link RequestQueue}. */
|
|
30
|
+
export interface RequestQueueStats {
|
|
31
|
+
/** Number of write operations issued to the request queue client (add / handle / reclaim). */
|
|
32
|
+
writeCount: number;
|
|
33
|
+
/** Number of queue-head reads issued to the request queue client (`fetchNextRequest`). */
|
|
34
|
+
headItemReadCount: number;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* A tiny mutable counter that the storage frontends increment on each client call and expose through
|
|
38
|
+
* a read-only `stats` snapshot. Generic over the concrete counter shape so each storage type gets only
|
|
39
|
+
* the buckets that make sense for it.
|
|
40
|
+
*/
|
|
41
|
+
export declare class StorageStatsTracker<T extends Record<keyof T, number>> {
|
|
42
|
+
#private;
|
|
43
|
+
constructor(initial: T);
|
|
44
|
+
/** Increment a counter bucket by `by` (default `1`). */
|
|
45
|
+
add(key: keyof T, by?: number): void;
|
|
46
|
+
/** Return a snapshot of the current counters. The returned object is a copy and safe to keep. */
|
|
47
|
+
get current(): T;
|
|
48
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Backend-independent usage counters tracked by the storage frontend classes
|
|
3
|
+
* ({@link Dataset}, {@link KeyValueStore}, {@link RequestQueue}).
|
|
4
|
+
*
|
|
5
|
+
* These count the operations the frontend issues against its underlying storage backend, so they are
|
|
6
|
+
* meaningful for any storage backend (memory, file system, cloud). They are tallied per client call
|
|
7
|
+
* — e.g. iterating a key-value store increments `readCount` once per record fetched and `listCount`
|
|
8
|
+
* once per listed page. Backend-specific figures that the frontend cannot compute (such as the number
|
|
9
|
+
* of bytes stored) are intentionally not included here; read those from the backend's own API instead.
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* A tiny mutable counter that the storage frontends increment on each client call and expose through
|
|
13
|
+
* a read-only `stats` snapshot. Generic over the concrete counter shape so each storage type gets only
|
|
14
|
+
* the buckets that make sense for it.
|
|
15
|
+
*/
|
|
16
|
+
export class StorageStatsTracker {
|
|
17
|
+
#counters;
|
|
18
|
+
constructor(initial) {
|
|
19
|
+
this.#counters = { ...initial };
|
|
20
|
+
}
|
|
21
|
+
/** Increment a counter bucket by `by` (default `1`). */
|
|
22
|
+
add(key, by = 1) {
|
|
23
|
+
this.#counters[key] += by;
|
|
24
|
+
}
|
|
25
|
+
/** Return a snapshot of the current counters. The returned object is a copy and safe to keep. */
|
|
26
|
+
get current() {
|
|
27
|
+
return { ...this.#counters };
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import type { Dictionary } from '@crawlee/types';
|
|
2
|
+
import type { Configuration } from '../configuration.js';
|
|
3
|
+
import type { Request, Source } from '../request.js';
|
|
4
|
+
import type { RequestSourceStatus } from './request_loader.js';
|
|
5
|
+
import type { IRequestManager, PacingSignal, RequestsLike } from './request_manager.js';
|
|
6
|
+
import type { AddRequestsBatchedOptions, AddRequestsBatchedResult, RequestQueueOperationInfo, RequestQueueOperationOptions } from './request_queue.js';
|
|
7
|
+
import type { StorageIdentifier } from './storage_instance_manager.js';
|
|
8
|
+
import type { StorageOpenOptions } from './utils.js';
|
|
9
|
+
/**
|
|
10
|
+
* Opens a request manager, matching the shape of storage `open` methods such as
|
|
11
|
+
* {@link RequestQueue.open|`RequestQueue.open`}.
|
|
12
|
+
*
|
|
13
|
+
* {@link ThrottlingRequestManager} calls this once per configured domain, so every per-domain queue shares the
|
|
14
|
+
* concrete type and storage backend of the manager being wrapped.
|
|
15
|
+
*/
|
|
16
|
+
export type RequestManagerOpener<T extends IRequestManager = IRequestManager> = (identifier?: string | StorageIdentifier | null, options?: StorageOpenOptions) => Promise<T>;
|
|
17
|
+
/** Options for {@link ThrottlingRequestManager}. */
|
|
18
|
+
export interface ThrottlingRequestManagerOptions<T extends IRequestManager = IRequestManager> {
|
|
19
|
+
/**
|
|
20
|
+
* The request manager to wrap, usually a {@link RequestQueue}. Requests for domains that are not throttled
|
|
21
|
+
* are stored here. May be a factory, so that the throttler can be constructed synchronously and the manager
|
|
22
|
+
* under it opened only on first use.
|
|
23
|
+
*
|
|
24
|
+
* Omitted, the default request queue is opened on first use through
|
|
25
|
+
* {@link ThrottlingRequestManagerOptions.requestManagerOpener|`requestManagerOpener`}.
|
|
26
|
+
*/
|
|
27
|
+
inner?: T | (() => T | Promise<T>);
|
|
28
|
+
/**
|
|
29
|
+
* Which domains to throttle: a list of hostnames, or `'all'` for every domain the crawl encounters.
|
|
30
|
+
*
|
|
31
|
+
* Matching a listed hostname is case-insensitive and exact - wildcards such as `*.example.com` are not
|
|
32
|
+
* supported, so list each subdomain you care about (or set
|
|
33
|
+
* {@link ThrottlingRequestManagerOptions.throttleBy|`throttleBy: 'registrableDomain'`}). An
|
|
34
|
+
* internationalized domain may be given in either its unicode or its punycode form, and an IPv6 address has
|
|
35
|
+
* to be bracketed (`[::1]`). Requests for any other domain bypass throttling entirely.
|
|
36
|
+
*
|
|
37
|
+
* `'all'` gives each domain a queue of its own the first time it is seen, so that it can be held back
|
|
38
|
+
* without its requests being repeatedly popped and re-enqueued. One request queue per domain is not free,
|
|
39
|
+
* which is what {@link ThrottlingRequestManagerOptions.maxThrottledDomains|`maxThrottledDomains`} is
|
|
40
|
+
* there to bound.
|
|
41
|
+
*/
|
|
42
|
+
domains: string[] | 'all';
|
|
43
|
+
/**
|
|
44
|
+
* A floor under the crawl delay of every throttled domain, in seconds - the proactive clock described on
|
|
45
|
+
* {@link ThrottlingRequestManager}. A domain whose robots.txt asks for a longer `Crawl-delay` gets the
|
|
46
|
+
* longer one; this is a minimum, not an override. A `minIntervalEverywhere` {@link PacingSignal} raises
|
|
47
|
+
* this floor at runtime, and never lowers it.
|
|
48
|
+
* @default 0
|
|
49
|
+
*/
|
|
50
|
+
minCrawlDelaySecs?: number;
|
|
51
|
+
/**
|
|
52
|
+
* What counts as "the same domain": the exact hostname, or the registrable domain it belongs to
|
|
53
|
+
* (`example.com` for `www.example.com`, `a.example.co.uk` and so on). Hosts with no registrable domain -
|
|
54
|
+
* IP addresses, `localhost` - are always throttled per hostname.
|
|
55
|
+
*
|
|
56
|
+
* Grouping by registrable domain gives subdomains a single pair of clocks and a single queue, which is what
|
|
57
|
+
* you want when the pacing is there to be polite to one server rather than to satisfy a specific host's
|
|
58
|
+
* rate limit.
|
|
59
|
+
* @default 'hostname'
|
|
60
|
+
*/
|
|
61
|
+
throttleBy?: 'hostname' | 'registrableDomain';
|
|
62
|
+
/**
|
|
63
|
+
* The most domains a run may throttle at once. Exceeding it throws, rather than silently letting the
|
|
64
|
+
* throttling lapse - one request queue per domain is not free, and a crawl that discovers domains without
|
|
65
|
+
* bound would drown the storage backend in them.
|
|
66
|
+
*
|
|
67
|
+
* Only domains discovered under `domains: 'all'` count against this; an explicit list is taken at face value.
|
|
68
|
+
* @default 100
|
|
69
|
+
*/
|
|
70
|
+
maxThrottledDomains?: number;
|
|
71
|
+
/**
|
|
72
|
+
* The key under which the discovered domain list is kept in the default key-value store, so that a restart
|
|
73
|
+
* with `purgeOnStart` disabled reopens their queues instead of stranding whatever they still hold. Only
|
|
74
|
+
* written under `domains: 'all'`.
|
|
75
|
+
*
|
|
76
|
+
* Give each manager its own key when running several of them against the same storage.
|
|
77
|
+
* @default 'CRAWLEE_THROTTLED_DOMAINS'
|
|
78
|
+
*/
|
|
79
|
+
persistStateKey?: string;
|
|
80
|
+
/**
|
|
81
|
+
* Opens the per-domain queues, one per throttled domain, each under the alias `throttled-<domain>`.
|
|
82
|
+
* @default RequestQueue.open
|
|
83
|
+
*/
|
|
84
|
+
requestManagerOpener?: RequestManagerOpener<T>;
|
|
85
|
+
/**
|
|
86
|
+
* The delay applied after a domain's first HTTP 429, doubled on each subsequent one.
|
|
87
|
+
* @default 2
|
|
88
|
+
*/
|
|
89
|
+
baseDelaySecs?: number;
|
|
90
|
+
/**
|
|
91
|
+
* Upper bound on the delay between requests to a rate-limited domain, applied to both the exponential
|
|
92
|
+
* backoff and a `Retry-After` value.
|
|
93
|
+
* @default 60
|
|
94
|
+
*/
|
|
95
|
+
maxDelaySecs?: number;
|
|
96
|
+
/**
|
|
97
|
+
* How long a domain may rate-limit us without a single request getting through before the crawl is
|
|
98
|
+
* abandoned with a {@link PersistentRateLimitError}.
|
|
99
|
+
*
|
|
100
|
+
* A domain that keeps answering 429 for this long is not going to be crawled by waiting longer - the
|
|
101
|
+
* concurrency is too high for it, or it has blocked us outright. Its requests are deliberately left in
|
|
102
|
+
* their queue, so re-running the crawl with `purgeOnStart` disabled picks them up once the domain recovers.
|
|
103
|
+
*
|
|
104
|
+
* A crawler running with `keepAlive` is exempt - outliving a domain that will not let us through is the
|
|
105
|
+
* whole point there.
|
|
106
|
+
* @default 900
|
|
107
|
+
*/
|
|
108
|
+
maxDomainStallSecs?: number;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* A request manager that wraps another one and paces requests per domain.
|
|
112
|
+
*
|
|
113
|
+
* Requests for a throttled domain are routed into their own queue when they are added, so each request lives in
|
|
114
|
+
* exactly one place and deduplication keeps working. Everything else goes to the wrapped manager untouched.
|
|
115
|
+
*
|
|
116
|
+
* {@link ThrottlingRequestManager.fetchNextRequest|`fetchNextRequest()`} serves the domain that has been waiting
|
|
117
|
+
* longest and skips any that are backing off, falling back to the wrapped manager. It never blocks: while every
|
|
118
|
+
* remaining request belongs to a throttled domain it returns `null` and
|
|
119
|
+
* {@link ThrottlingRequestManager.checkReadiness|`checkReadiness()`} reports `waiting` with the moment the
|
|
120
|
+
* earliest of them comes due, so the crawler idles instead of holding a concurrency slot open.
|
|
121
|
+
*
|
|
122
|
+
* Each throttled domain runs two independent clocks, and may be dispatched to once **both** have run out:
|
|
123
|
+
* - **Backoff**, set by HTTP 429 responses - honouring `Retry-After`, and otherwise doubling from `baseDelaySecs`.
|
|
124
|
+
* Reactive and temporary: it decays once the domain stops turning us away. The crawlers report the 429s
|
|
125
|
+
* themselves; a request held back this way is retried later without counting against `maxRequestRetries` and
|
|
126
|
+
* without penalising its session.
|
|
127
|
+
* - **Crawl delay**, the minimum interval between two dispatches to the domain, armed after each one. Proactive
|
|
128
|
+
* and constant: whatever the domain's robots.txt asks for, floored by
|
|
129
|
+
* {@link ThrottlingRequestManagerOptions.minCrawlDelaySecs|`minCrawlDelaySecs`}. Either may be absent, in
|
|
130
|
+
* which case the other one is the delay.
|
|
131
|
+
*
|
|
132
|
+
* Which domains get those clocks is {@link ThrottlingRequestManagerOptions.domains|`domains`} - a list, or
|
|
133
|
+
* `'all'` for every domain the crawl encounters.
|
|
134
|
+
*
|
|
135
|
+
* Pass one as a crawler's `requestManager`; the `sameDomainDelaySecs` shorthand builds one with `domains: 'all'`
|
|
136
|
+
* and `throttleBy: 'registrableDomain'`. Construct it yourself to name the domains or tune the delays - one
|
|
137
|
+
* covering every domain also makes `sameDomainDelaySecs` land on it as a floor rather than adding a second pacer.
|
|
138
|
+
*
|
|
139
|
+
* Signals - 429s, robots.txt `Crawl-delay`, that floor - arrive through
|
|
140
|
+
* {@link IRequestManager.recordPacingSignal|`recordPacingSignal`}, which wrapping managers forward, so this
|
|
141
|
+
* works wherever it sits in a composition, including inside a {@link RequestManagerTandem}.
|
|
142
|
+
*
|
|
143
|
+
* **Example usage:**
|
|
144
|
+
*
|
|
145
|
+
* ```ts
|
|
146
|
+
* const crawler = new CheerioCrawler({
|
|
147
|
+
* requestManager: new ThrottlingRequestManager({
|
|
148
|
+
* domains: ['api.example.com', 'slow-site.org'],
|
|
149
|
+
* }),
|
|
150
|
+
* requestHandler: async ({ request }) => { ... },
|
|
151
|
+
* });
|
|
152
|
+
* ```
|
|
153
|
+
*
|
|
154
|
+
* @category Sources
|
|
155
|
+
*/
|
|
156
|
+
export declare class ThrottlingRequestManager<T extends IRequestManager = IRequestManager> implements IRequestManager {
|
|
157
|
+
#private;
|
|
158
|
+
private readonly config;
|
|
159
|
+
private readonly domainStates;
|
|
160
|
+
private readonly log;
|
|
161
|
+
constructor(options: ThrottlingRequestManagerOptions<T>, config?: Configuration);
|
|
162
|
+
/**
|
|
163
|
+
* The wrapped manager, holding every request whose domain is not throttled. `undefined` until an `inner`
|
|
164
|
+
* passed as a factory is resolved - reading this never forces it, because a getter should not open a queue
|
|
165
|
+
* behind a caller's back.
|
|
166
|
+
*/
|
|
167
|
+
get innerManager(): T | undefined;
|
|
168
|
+
/**
|
|
169
|
+
* Records a pacing signal: a refusal puts the URL's domain into backoff, a declared interval becomes its
|
|
170
|
+
* crawl delay, and a crawl-wide floor raises {@link recordEverywhereFloor|the floor under all of them}.
|
|
171
|
+
*
|
|
172
|
+
* @returns `false` if the domain the signal covers is not throttled, in which case this is a no-op.
|
|
173
|
+
* @throws If the signal's scope is one this manager cannot honour - see {@link assertScopeHonourable}.
|
|
174
|
+
* @inheritdoc
|
|
175
|
+
*/
|
|
176
|
+
recordPacingSignal(signal: PacingSignal): boolean;
|
|
177
|
+
addRequest(requestLike: Source, options?: RequestQueueOperationOptions): Promise<RequestQueueOperationInfo>;
|
|
178
|
+
/**
|
|
179
|
+
* Adds requests in batches, routing each one to the manager that owns its domain.
|
|
180
|
+
*
|
|
181
|
+
* Batching, validation, deduplication and `Retry-After`-free bookkeeping are all delegated to the target
|
|
182
|
+
* managers - this only decides where each request goes, one batch at a time, so a lazy or unbounded input
|
|
183
|
+
* iterable is never fully materialized.
|
|
184
|
+
*/
|
|
185
|
+
addRequestsBatched(requests: RequestsLike, options?: AddRequestsBatchedOptions): Promise<AddRequestsBatchedResult>;
|
|
186
|
+
reclaimRequest(request: Request, options?: RequestQueueOperationOptions): Promise<RequestQueueOperationInfo | null>;
|
|
187
|
+
markRequestAsHandled(request: Request): Promise<RequestQueueOperationInfo | void | null>;
|
|
188
|
+
getTotalCount(): Promise<number>;
|
|
189
|
+
getPendingCount(): Promise<number>;
|
|
190
|
+
getHandledCount(): Promise<number>;
|
|
191
|
+
/**
|
|
192
|
+
* Reports whether anything can be dispatched right now, and if not, when — or why never.
|
|
193
|
+
*
|
|
194
|
+
* One traversal of the domain clocks answers all of it: only domains whose delays have run out are probed,
|
|
195
|
+
* the rest merely contribute the moment they come due. Throttled requests count as outstanding work, so a
|
|
196
|
+
* crawler gated on this idles for the backoff instead of concluding it is done.
|
|
197
|
+
*
|
|
198
|
+
* `ready` from anywhere else outranks a stalling domain and is returned without looking at the stall clocks,
|
|
199
|
+
* so one hopeless domain never ends a crawl making progress elsewhere. It cannot outrank itself, though -
|
|
200
|
+
* see the traversal.
|
|
201
|
+
*/
|
|
202
|
+
checkReadiness(): Promise<RequestSourceStatus>;
|
|
203
|
+
/**
|
|
204
|
+
* Empties every manager and clears the accumulated backoff. A robots.txt `Crawl-delay` is a property of the
|
|
205
|
+
* site rather than of the run, so it survives.
|
|
206
|
+
*/
|
|
207
|
+
purge(): Promise<void>;
|
|
208
|
+
setExpectedRequestProcessingTimeSecs(secs: number): Promise<void>;
|
|
209
|
+
/**
|
|
210
|
+
* Returns the next request from a domain that is not backing off, or from the inner manager.
|
|
211
|
+
*
|
|
212
|
+
* Returns `null` while every remaining request belongs to a throttled domain - it never waits the backoff
|
|
213
|
+
* out, because a consumer parked in here holds a concurrency slot, which the autoscaler reads as spare
|
|
214
|
+
* capacity and answers by scaling up. Callers poll instead, and
|
|
215
|
+
* {@link ThrottlingRequestManager.checkReadiness|`checkReadiness()`} reports `waiting` meanwhile so the
|
|
216
|
+
* crawler's task loop idles rather than spins.
|
|
217
|
+
*/
|
|
218
|
+
fetchNextRequest<R extends Dictionary = Dictionary>(): Promise<Request<R> | null>;
|
|
219
|
+
[Symbol.asyncIterator](): AsyncGenerator<Request<Dictionary>, void, unknown>;
|
|
220
|
+
persistState(): Promise<void>;
|
|
221
|
+
drop(): Promise<void>;
|
|
222
|
+
}
|