@crawlee/core 4.0.0-beta.24 → 4.0.0-beta.240
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 +15 -15
- package/byte-utils.d.ts +17 -0
- package/byte-utils.js +42 -0
- package/configuration.d.ts +77 -235
- package/configuration.js +157 -227
- package/debug.d.ts +36 -0
- package/debug.js +70 -0
- package/errors.d.ts +45 -18
- package/errors.js +58 -27
- package/events/event-manager.d.ts +78 -0
- package/events/{event_manager.js → event-manager.js} +12 -13
- package/events/index.d.ts +3 -3
- package/events/index.js +2 -3
- package/events/local-event-manager.d.ts +32 -0
- package/events/local-event-manager.js +101 -0
- package/events/system-info.d.ts +38 -0
- package/events/system-info.js +1 -0
- package/index.d.ts +9 -12
- package/index.js +10 -11
- package/internal.d.ts +8 -0
- package/internal.js +9 -0
- package/iterables.d.ts +79 -0
- package/iterables.js +134 -0
- package/log.d.ts +77 -1
- package/log.js +134 -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 +43 -0
- package/memory-storage/memory-storage.js +158 -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 +35 -0
- package/memory-storage/resource-clients/dataset.js +105 -0
- package/memory-storage/resource-clients/key-value-store.d.ts +54 -0
- package/memory-storage/resource-clients/key-value-store.js +179 -0
- package/memory-storage/resource-clients/request-queue.d.ts +55 -0
- package/memory-storage/resource-clients/request-queue.js +413 -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 +20 -20
- package/proxy-configuration.d.ts +118 -0
- package/proxy-configuration.js +141 -0
- package/recoverable-state.d.ts +177 -0
- package/recoverable-state.js +268 -0
- package/request.d.ts +48 -93
- package/request.js +112 -230
- package/serialization.d.ts +0 -1
- package/serialization.js +18 -18
- package/service-locator.d.ts +168 -0
- package/service-locator.js +255 -0
- package/storages/batched-adds.d.ts +37 -0
- package/storages/batched-adds.js +73 -0
- package/storages/dataset.d.ts +105 -58
- package/storages/dataset.js +292 -150
- package/storages/index.d.ts +11 -12
- package/storages/index.js +7 -12
- package/storages/key-value-store-codec.d.ts +32 -0
- package/storages/key-value-store-codec.js +108 -0
- package/storages/{key_value_store.d.ts → key-value-store.d.ts} +169 -72
- package/storages/key-value-store.js +767 -0
- package/storages/request-dedup-cache.d.ts +20 -0
- package/storages/request-dedup-cache.js +48 -0
- package/storages/{request_list.d.ts → request-list.d.ts} +33 -173
- package/storages/{request_list.js → request-list.js} +276 -255
- package/storages/request-loader.d.ts +127 -0
- package/storages/request-loader.js +36 -0
- package/storages/request-manager-tandem.d.ts +82 -0
- package/storages/request-manager-tandem.js +200 -0
- package/storages/request-manager.d.ts +119 -0
- package/storages/request-manager.js +1 -0
- package/storages/{request_provider.d.ts → request-queue.d.ts} +128 -159
- package/storages/request-queue.js +870 -0
- package/storages/storage-instance-manager.d.ts +86 -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/transaction.d.ts +270 -0
- package/storages/transaction.js +296 -0
- package/storages/utils.d.ts +59 -11
- package/storages/utils.js +76 -16
- 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 +23 -18
- package/validators.js +14 -18
- package/autoscaling/autoscaled_pool.d.ts +0 -300
- package/autoscaling/autoscaled_pool.d.ts.map +0 -1
- package/autoscaling/autoscaled_pool.js +0 -533
- package/autoscaling/autoscaled_pool.js.map +0 -1
- package/autoscaling/index.d.ts +0 -4
- package/autoscaling/index.d.ts.map +0 -1
- package/autoscaling/index.js +0 -4
- package/autoscaling/index.js.map +0 -1
- package/autoscaling/snapshotter.d.ts +0 -189
- package/autoscaling/snapshotter.d.ts.map +0 -1
- package/autoscaling/snapshotter.js +0 -285
- package/autoscaling/snapshotter.js.map +0 -1
- package/autoscaling/system_status.d.ts +0 -181
- package/autoscaling/system_status.d.ts.map +0 -1
- package/autoscaling/system_status.js +0 -169
- 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 +0 -43
- package/cookie_utils.d.ts.map +0 -1
- package/cookie_utils.js +0 -111
- package/cookie_utils.js.map +0 -1
- package/crawlers/context_pipeline.d.ts +0 -61
- package/crawlers/context_pipeline.d.ts.map +0 -1
- package/crawlers/context_pipeline.js +0 -99
- package/crawlers/context_pipeline.js.map +0 -1
- package/crawlers/crawler_commons.d.ts +0 -191
- package/crawlers/crawler_commons.d.ts.map +0 -1
- package/crawlers/crawler_commons.js +0 -108
- 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 +0 -60
- package/crawlers/error_snapshotter.d.ts.map +0 -1
- package/crawlers/error_snapshotter.js +0 -118
- package/crawlers/error_snapshotter.js.map +0 -1
- package/crawlers/error_tracker.d.ts +0 -55
- package/crawlers/error_tracker.d.ts.map +0 -1
- package/crawlers/error_tracker.js +0 -309
- package/crawlers/error_tracker.js.map +0 -1
- package/crawlers/index.d.ts +0 -7
- package/crawlers/index.d.ts.map +0 -1
- package/crawlers/index.js +0 -7
- package/crawlers/index.js.map +0 -1
- package/crawlers/internals/types.d.ts +0 -8
- package/crawlers/internals/types.d.ts.map +0 -1
- package/crawlers/internals/types.js +0 -2
- package/crawlers/internals/types.js.map +0 -1
- package/crawlers/statistics.d.ts +0 -213
- package/crawlers/statistics.d.ts.map +0 -1
- package/crawlers/statistics.js +0 -349
- package/crawlers/statistics.js.map +0 -1
- package/enqueue_links/enqueue_links.d.ts +0 -249
- package/enqueue_links/enqueue_links.d.ts.map +0 -1
- package/enqueue_links/enqueue_links.js +0 -269
- package/enqueue_links/enqueue_links.js.map +0 -1
- package/enqueue_links/index.d.ts +0 -3
- package/enqueue_links/index.d.ts.map +0 -1
- package/enqueue_links/index.js +0 -3
- package/enqueue_links/index.js.map +0 -1
- package/enqueue_links/shared.d.ts +0 -73
- package/enqueue_links/shared.d.ts.map +0 -1
- package/enqueue_links/shared.js +0 -212
- 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 +0 -52
- 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 +0 -27
- package/events/local_event_manager.d.ts.map +0 -1
- package/events/local_event_manager.js +0 -75
- package/events/local_event_manager.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 +0 -169
- package/proxy_configuration.d.ts.map +0 -1
- package/proxy_configuration.js +0 -247
- package/proxy_configuration.js.map +0 -1
- package/recoverable_state.d.ts +0 -123
- package/recoverable_state.d.ts.map +0 -1
- package/recoverable_state.js +0 -140
- package/recoverable_state.js.map +0 -1
- package/request.d.ts.map +0 -1
- package/request.js.map +0 -1
- package/router.d.ts +0 -134
- package/router.d.ts.map +0 -1
- package/router.js +0 -164
- 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 +0 -4
- package/session_pool/consts.d.ts.map +0 -1
- package/session_pool/consts.js +0 -4
- package/session_pool/consts.js.map +0 -1
- package/session_pool/errors.d.ts +0 -8
- package/session_pool/errors.d.ts.map +0 -1
- package/session_pool/errors.js +0 -12
- 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 +0 -6
- package/session_pool/index.d.ts.map +0 -1
- package/session_pool/index.js +0 -6
- package/session_pool/index.js.map +0 -1
- package/session_pool/session.d.ts +0 -186
- package/session_pool/session.d.ts.map +0 -1
- package/session_pool/session.js +0 -278
- package/session_pool/session.js.map +0 -1
- package/session_pool/session_pool.d.ts +0 -258
- package/session_pool/session_pool.d.ts.map +0 -1
- package/session_pool/session_pool.js +0 -387
- 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 +0 -512
- 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 +0 -68
- package/storages/request_manager_tandem.d.ts.map +0 -1
- package/storages/request_manager_tandem.js +0 -124
- package/storages/request_manager_tandem.js.map +0 -1
- package/storages/request_provider.d.ts.map +0 -1
- package/storages/request_provider.js +0 -591
- package/storages/request_provider.js.map +0 -1
- package/storages/request_queue.d.ts +0 -128
- package/storages/request_queue.d.ts.map +0 -1
- package/storages/request_queue.js +0 -320
- 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 +0 -250
- package/storages/sitemap_request_list.d.ts.map +0 -1
- package/storages/sitemap_request_list.js +0 -431
- package/storages/sitemap_request_list.js.map +0 -1
- package/storages/storage_manager.d.ts +0 -62
- 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,268 @@
|
|
|
1
|
+
import { Readable } from 'node:stream';
|
|
2
|
+
import { addTimeoutToPromise, storage as timeoutStorage } from '@apify/timeout';
|
|
3
|
+
import { StateValidationError } from './errors.js';
|
|
4
|
+
import { EventType } from './events/event-manager.js';
|
|
5
|
+
import { serviceLocator } from './service-locator.js';
|
|
6
|
+
import { KeyValueStore } from './storages/key-value-store.js';
|
|
7
|
+
const DEFAULT_PERSISTENCE_TIMEOUT_MILLIS = 60_000;
|
|
8
|
+
/**
|
|
9
|
+
* Applies a {@link SyncStateConversion}, throwing a {@link StateValidationError} for a schema that rejects
|
|
10
|
+
* the value.
|
|
11
|
+
*
|
|
12
|
+
* @internal
|
|
13
|
+
*/
|
|
14
|
+
export function convertStateSync(conversion, value, persistStateKey) {
|
|
15
|
+
if (typeof conversion === 'function') {
|
|
16
|
+
return conversion(value);
|
|
17
|
+
}
|
|
18
|
+
const result = conversion['~standard'].validate(value);
|
|
19
|
+
if ('then' in result) {
|
|
20
|
+
throw new Error(`The state conversion for '${persistStateKey}' validated asynchronously, which this caller cannot await.`);
|
|
21
|
+
}
|
|
22
|
+
if (result.issues) {
|
|
23
|
+
throw new StateValidationError(persistStateKey, result.issues);
|
|
24
|
+
}
|
|
25
|
+
return result.value;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* A class for managing persistent recoverable state using a plain JavaScript object.
|
|
29
|
+
*
|
|
30
|
+
* This class facilitates state persistence to a `KeyValueStore`, allowing data to be saved and retrieved
|
|
31
|
+
* across migrations or restarts. It manages the loading, saving, and resetting of state data,
|
|
32
|
+
* with optional persistence capabilities.
|
|
33
|
+
*
|
|
34
|
+
* The state is represented by a plain JavaScript object that can be serialized to and deserialized from JSON.
|
|
35
|
+
* The class automatically hooks into the event system to persist state when needed.
|
|
36
|
+
*/
|
|
37
|
+
export class RecoverableState {
|
|
38
|
+
#defaultState;
|
|
39
|
+
#state = null;
|
|
40
|
+
#initialized = false;
|
|
41
|
+
#recordLoaded = false;
|
|
42
|
+
#listening = false;
|
|
43
|
+
#persistenceEnabled;
|
|
44
|
+
#persistStateKey;
|
|
45
|
+
#persistenceTimeoutMillis;
|
|
46
|
+
#configuration;
|
|
47
|
+
#keyValueStore;
|
|
48
|
+
#log;
|
|
49
|
+
#serialize;
|
|
50
|
+
#deserialize;
|
|
51
|
+
#contentType;
|
|
52
|
+
#persistStateQuietly;
|
|
53
|
+
/**
|
|
54
|
+
* Initialize a new recoverable state object.
|
|
55
|
+
*
|
|
56
|
+
* @param options Configuration options for the recoverable state
|
|
57
|
+
*/
|
|
58
|
+
constructor(options) {
|
|
59
|
+
const { defaultState } = options;
|
|
60
|
+
this.#defaultState =
|
|
61
|
+
typeof defaultState === 'function'
|
|
62
|
+
? defaultState
|
|
63
|
+
: () => structuredClone(defaultState);
|
|
64
|
+
this.#persistStateKey = options.persistStateKey;
|
|
65
|
+
this.#persistenceEnabled = options.persistenceEnabled ?? false;
|
|
66
|
+
this.#persistenceTimeoutMillis = options.persistenceTimeoutMillis ?? DEFAULT_PERSISTENCE_TIMEOUT_MILLIS;
|
|
67
|
+
this.#configuration = options.configuration;
|
|
68
|
+
this.#keyValueStore = options.keyValueStore ?? null;
|
|
69
|
+
this.#log = options.logger ?? serviceLocator.getLogger().child({ prefix: 'RecoverableState' });
|
|
70
|
+
this.#contentType = options.contentType;
|
|
71
|
+
if (this.#contentType !== undefined && (options.serialize === undefined || options.deserialize === undefined)) {
|
|
72
|
+
throw new Error(`A 'contentType' for the state persisted under key '${this.#persistStateKey}' requires both 'serialize' and 'deserialize' - the record is no longer JSON the default codec can handle.`);
|
|
73
|
+
}
|
|
74
|
+
this.#serialize = this.#toConversion(options.serialize);
|
|
75
|
+
this.#deserialize = this.#toConversion(options.deserialize);
|
|
76
|
+
// A pending open() may reject before anything here awaits it. Observe the rejection so it surfaces on
|
|
77
|
+
// first use rather than as an unhandled rejection - most immediately when persistence is disabled and
|
|
78
|
+
// nothing ever awaits the store.
|
|
79
|
+
if (this.#keyValueStore !== null) {
|
|
80
|
+
Promise.resolve(this.#keyValueStore).then(undefined, () => { });
|
|
81
|
+
}
|
|
82
|
+
// The automatic persists, where a rejection has nowhere useful to go - the event manager does not catch
|
|
83
|
+
// listener errors, and throwing from teardown would bury the outcome of the work it cleans up after.
|
|
84
|
+
this.#persistStateQuietly = async (eventData) => this.persistState(eventData).catch((error) => this.#log.warning(`Failed to persist the state under key '${this.#persistStateKey}'.`, { error }));
|
|
85
|
+
}
|
|
86
|
+
/** Normalizes a conversion option into a function. Absent conversions pass the value through unchanged. */
|
|
87
|
+
#toConversion(conversion) {
|
|
88
|
+
if (conversion === undefined) {
|
|
89
|
+
return async (value) => value;
|
|
90
|
+
}
|
|
91
|
+
if (typeof conversion === 'function') {
|
|
92
|
+
return async (value) => conversion(value);
|
|
93
|
+
}
|
|
94
|
+
return async (value) => {
|
|
95
|
+
const result = await conversion['~standard'].validate(value);
|
|
96
|
+
if (result.issues) {
|
|
97
|
+
throw new StateValidationError(this.#persistStateKey, result.issues);
|
|
98
|
+
}
|
|
99
|
+
return result.value;
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Initialize the recoverable state.
|
|
104
|
+
*
|
|
105
|
+
* If persistence is enabled, this method loads the saved state and registers the object to listen for
|
|
106
|
+
* PERSIST_STATE events. A state established beforehand by {@link RecoverableState.reset} survives if there
|
|
107
|
+
* is no record to restore.
|
|
108
|
+
*
|
|
109
|
+
* Calling this again after a {@link RecoverableState.teardown} starts a new persistence window - the
|
|
110
|
+
* listener is registered again. The record is not reloaded: the in-memory state is what the teardown wrote, and
|
|
111
|
+
* reloading it would only drop whatever the deserialization leaves out.
|
|
112
|
+
*
|
|
113
|
+
* @returns The loaded state object
|
|
114
|
+
*/
|
|
115
|
+
async initialize() {
|
|
116
|
+
if (this.#initialized) {
|
|
117
|
+
return this.currentValue;
|
|
118
|
+
}
|
|
119
|
+
if (this.#persistenceEnabled) {
|
|
120
|
+
await this.#openKeyValueStore();
|
|
121
|
+
serviceLocator.getEventManager().on(EventType.PERSIST_STATE, this.#persistStateQuietly);
|
|
122
|
+
this.#listening = true;
|
|
123
|
+
}
|
|
124
|
+
// Flipped before the record is loaded, so that a caller catching a `StateValidationError` is left with a
|
|
125
|
+
// fully wired object running on the default state rather than a half-initialized one.
|
|
126
|
+
this.#initialized = true;
|
|
127
|
+
this.#state ??= this.#defaultState();
|
|
128
|
+
if (!this.#recordLoaded) {
|
|
129
|
+
this.#recordLoaded = true;
|
|
130
|
+
await this.#loadSavedState();
|
|
131
|
+
}
|
|
132
|
+
return this.currentValue;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Clean up resources used by the recoverable state.
|
|
136
|
+
*
|
|
137
|
+
* If persistence is enabled, this method deregisters the object from PERSIST_STATE events
|
|
138
|
+
* and persists the current state one last time, warning rather than throwing if that write fails - cleanup
|
|
139
|
+
* runs when the work is already done, and failing it would bury whatever the caller was doing. The in-memory
|
|
140
|
+
* state is left alone, and {@link RecoverableState.initialize} can be called again to open a new
|
|
141
|
+
* persistence window.
|
|
142
|
+
*/
|
|
143
|
+
async teardown() {
|
|
144
|
+
this.#initialized = false;
|
|
145
|
+
if (!this.#persistenceEnabled) {
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
serviceLocator.getEventManager().off(EventType.PERSIST_STATE, this.#persistStateQuietly);
|
|
149
|
+
this.#listening = false;
|
|
150
|
+
await this.#persistStateQuietly();
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Get the current state.
|
|
154
|
+
*
|
|
155
|
+
* Throws until the state has been established, by either {@link RecoverableState.initialize} or the
|
|
156
|
+
* synchronous {@link RecoverableState.reset} - the latter being how a caller that cannot await in its
|
|
157
|
+
* constructor gets a usable state right away.
|
|
158
|
+
*/
|
|
159
|
+
get currentValue() {
|
|
160
|
+
if (this.#state === null) {
|
|
161
|
+
throw new Error('Recoverable state has not yet been loaded - call initialize() or reset() first');
|
|
162
|
+
}
|
|
163
|
+
return this.#state;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Reset the in-memory state to the default values, leaving any persisted record alone.
|
|
167
|
+
*
|
|
168
|
+
* Use {@link RecoverableState.resetStore} to clear the persisted record as well.
|
|
169
|
+
*/
|
|
170
|
+
reset() {
|
|
171
|
+
this.#state = this.#defaultState();
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Clear the persisted state record, leaving the in-memory state alone.
|
|
175
|
+
*
|
|
176
|
+
* This is a between-lifecycles operation - its point is to stop the next {@link RecoverableState.initialize}
|
|
177
|
+
* from restoring the record, so it throws while PERSIST_STATE events are still being handled, where the next
|
|
178
|
+
* one would write the record straight back. Use {@link RecoverableState.reset} to reset the state itself,
|
|
179
|
+
* or {@link RecoverableState.teardown} before clearing the record.
|
|
180
|
+
*
|
|
181
|
+
* A no-op if persistence is disabled.
|
|
182
|
+
*/
|
|
183
|
+
async resetStore() {
|
|
184
|
+
if (this.#listening) {
|
|
185
|
+
throw new Error(`Cannot clear the state persisted under key '${this.#persistStateKey}' while it is still being persisted periodically - the next PERSIST_STATE event would write it straight back. Use reset() to reset the state itself, or teardown() before clearing the record.`);
|
|
186
|
+
}
|
|
187
|
+
if (!this.#persistenceEnabled) {
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
const keyValueStore = await this.#openKeyValueStore();
|
|
191
|
+
await this.#withTimeout(async () => keyValueStore.setValue(this.#persistStateKey, null), 'Clearing the persisted state');
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Persist the current state to the KeyValueStore.
|
|
195
|
+
*
|
|
196
|
+
* This method is typically called in response to a PERSIST_STATE event, but can also be called
|
|
197
|
+
* directly when needed. It is a no-op if persistence is disabled, if no KeyValueStore is available yet, or if
|
|
198
|
+
* there is no state to write. A failed write only rejects here - the periodic and teardown ones warn instead.
|
|
199
|
+
*
|
|
200
|
+
* @param eventData Optional data associated with a PERSIST_STATE event
|
|
201
|
+
*/
|
|
202
|
+
async persistState(eventData) {
|
|
203
|
+
if (!this.#persistenceEnabled || this.#state === null) {
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
const keyValueStore = await this.#resolveKeyValueStore();
|
|
207
|
+
if (keyValueStore === null) {
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
this.#log.debug(`Persisting state of the RecoverableState (eventData=${JSON.stringify(eventData)}).`);
|
|
211
|
+
const serializedState = await this.#serialize(this.currentValue);
|
|
212
|
+
await this.#withTimeout(async () => this.#contentType === undefined
|
|
213
|
+
? keyValueStore.setValue(this.#persistStateKey, serializedState)
|
|
214
|
+
: keyValueStore.setValue(this.#persistStateKey, serializedState, {
|
|
215
|
+
contentType: this.#contentType,
|
|
216
|
+
}), 'Persisting the state');
|
|
217
|
+
}
|
|
218
|
+
/** Falls back to the default store when none was supplied - persistence has to write somewhere. */
|
|
219
|
+
async #openKeyValueStore() {
|
|
220
|
+
this.#keyValueStore ??= KeyValueStore.open(null, {
|
|
221
|
+
configuration: this.#configuration ?? serviceLocator.getConfiguration(),
|
|
222
|
+
});
|
|
223
|
+
return (await this.#resolveKeyValueStore());
|
|
224
|
+
}
|
|
225
|
+
/** Awaits a store handed over as a pending `open()`, keeping the resolved instance for later calls. */
|
|
226
|
+
async #resolveKeyValueStore() {
|
|
227
|
+
if (this.#keyValueStore === null) {
|
|
228
|
+
return null;
|
|
229
|
+
}
|
|
230
|
+
this.#keyValueStore = await this.#keyValueStore;
|
|
231
|
+
return this.#keyValueStore;
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Load the saved state from the KeyValueStore. Leaves the current state alone if there is no record to load.
|
|
235
|
+
*/
|
|
236
|
+
async #loadSavedState() {
|
|
237
|
+
if (!this.#persistenceEnabled) {
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
const keyValueStore = await this.#resolveKeyValueStore();
|
|
241
|
+
if (keyValueStore === null) {
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
// With a content type, the record is whatever `serialize` produced, so the codec's parse is skipped and
|
|
245
|
+
// `deserialize` gets the bytes as a stream - the shape a streaming parser wants.
|
|
246
|
+
// TODO: read the record as a stream instead of buffering it and wrapping (https://github.com/apify/crawlee/issues/2929).
|
|
247
|
+
const storedState = await this.#withTimeout(async () => {
|
|
248
|
+
if (this.#contentType === undefined) {
|
|
249
|
+
return keyValueStore.getValue(this.#persistStateKey);
|
|
250
|
+
}
|
|
251
|
+
const record = await keyValueStore.getRecord(this.#persistStateKey);
|
|
252
|
+
if (record === null) {
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
return Readable.from(Buffer.isBuffer(record.value) ? record.value : Buffer.from(record.value));
|
|
256
|
+
}, 'Loading the persisted state');
|
|
257
|
+
if (storedState === null || storedState === undefined) {
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
this.#state = await this.#deserialize(storedState);
|
|
261
|
+
}
|
|
262
|
+
async #withTimeout(operation, description) {
|
|
263
|
+
// `@apify/timeout` shares one `AbortController` across nested frames and `KeyValueStore` checks it on
|
|
264
|
+
// every operation, so a teardown-time persist running inside an already-expired request handler timeout
|
|
265
|
+
// would be aborted before it started. Hence a fresh timeout context.
|
|
266
|
+
return timeoutStorage.exit(async () => addTimeoutToPromise(operation, this.#persistenceTimeoutMillis, `${description} under key '${this.#persistStateKey}' timed out after ${this.#persistenceTimeoutMillis / 1000} seconds.`));
|
|
267
|
+
}
|
|
268
|
+
}
|
package/request.d.ts
CHANGED
|
@@ -1,21 +1,12 @@
|
|
|
1
1
|
import type { BinaryLike } from 'node:crypto';
|
|
2
|
-
import type { Dictionary } from '@crawlee/types';
|
|
3
|
-
import type {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
export declare enum RequestState {
|
|
7
|
-
UNPROCESSED = 0,
|
|
8
|
-
BEFORE_NAV = 1,
|
|
9
|
-
AFTER_NAV = 2,
|
|
10
|
-
REQUEST_HANDLER = 3,
|
|
11
|
-
DONE = 4,
|
|
12
|
-
ERROR_HANDLER = 5,
|
|
13
|
-
ERROR = 6,
|
|
14
|
-
SKIPPED = 7
|
|
15
|
-
}
|
|
2
|
+
import type { AllowedHttpMethods, Dictionary, RequestSchema } from '@crawlee/types';
|
|
3
|
+
import type { EnqueueStrategy } from '@crawlee/utils';
|
|
4
|
+
/** The `strategy` option accepted by {@link ExtractLinksOptions} and {@link EnqueueUrlsOptions}. */
|
|
5
|
+
export type EnqueueStrategyOption = EnqueueStrategy | 'all' | 'same-domain' | 'same-hostname' | 'same-origin';
|
|
16
6
|
/**
|
|
17
|
-
* Represents a URL to be crawled, optionally including HTTP method, headers, payload and other metadata
|
|
18
|
-
*
|
|
7
|
+
* Represents a URL to be crawled, optionally including HTTP method, headers, payload and other metadata, together
|
|
8
|
+
* with the processing state a request queue keeps about it (`retryCount`, `errorMessages`, `handledAt`, ...).
|
|
9
|
+
* Inside a crawler, requests are {@link CrawlingRequest}s, which add the crawler's own per-request settings.
|
|
19
10
|
*
|
|
20
11
|
* Each `Request` instance has the `uniqueKey` property, which can be either specified
|
|
21
12
|
* manually in the constructor or generated automatically from the URL. Two requests with the same `uniqueKey`
|
|
@@ -31,21 +22,16 @@ export declare enum RequestState {
|
|
|
31
22
|
* const request = new Request({
|
|
32
23
|
* url: 'http://www.example.com',
|
|
33
24
|
* headers: { Accept: 'application/json' },
|
|
25
|
+
* userData: { foo: 'bar' },
|
|
34
26
|
* });
|
|
35
27
|
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
* request.userData.foo = 'bar';
|
|
39
|
-
* request.pushErrorMessage(new Error('Request failed!'));
|
|
40
|
-
*
|
|
41
|
-
* ...
|
|
42
|
-
*
|
|
43
|
-
* const foo = request.userData.foo;
|
|
28
|
+
* await requestQueue.addRequest(request);
|
|
44
29
|
* ```
|
|
45
30
|
* @category Sources
|
|
46
31
|
*/
|
|
47
32
|
declare class CrawleeRequest<UserData extends Dictionary = Dictionary> {
|
|
48
|
-
|
|
33
|
+
#private;
|
|
34
|
+
/** Storage-assigned request ID. Only present on requests that went through a {@link RequestQueue}. */
|
|
49
35
|
id?: string;
|
|
50
36
|
/** URL of the web page to crawl. */
|
|
51
37
|
url: string;
|
|
@@ -75,9 +61,12 @@ declare class CrawleeRequest<UserData extends Dictionary = Dictionary> {
|
|
|
75
61
|
errorMessages: string[];
|
|
76
62
|
/** Object with HTTP headers. Key is header name, value is the value. */
|
|
77
63
|
headers?: Record<string, string>;
|
|
78
|
-
/**
|
|
79
|
-
|
|
80
|
-
|
|
64
|
+
/**
|
|
65
|
+
* Custom user data assigned to the request.
|
|
66
|
+
*
|
|
67
|
+
* All data stored in `userData` must be JSON-serializable.
|
|
68
|
+
* Storing non-serializable values (e.g. functions, symbols) may result in unexpected results.
|
|
69
|
+
*/
|
|
81
70
|
userData: UserData;
|
|
82
71
|
/**
|
|
83
72
|
* ISO datetime string that indicates the time when the request has been processed.
|
|
@@ -86,61 +75,27 @@ declare class CrawleeRequest<UserData extends Dictionary = Dictionary> {
|
|
|
86
75
|
handledAt?: string;
|
|
87
76
|
/**
|
|
88
77
|
* `Request` parameters including the URL, HTTP method and headers, and others.
|
|
78
|
+
*
|
|
79
|
+
* Processing state (`retryCount`, `errorMessages`, `handledAt`, `loadedUrl`, `id`) is not an option;
|
|
80
|
+
* requests coming back from a storage are rebuilt with {@link Request.fromSchema}.
|
|
89
81
|
*/
|
|
90
82
|
constructor(options: RequestOptions<UserData>);
|
|
83
|
+
/**
|
|
84
|
+
* Rebuilds a request from its stored form, including the processing state a
|
|
85
|
+
* {@link RequestOptions} object cannot carry. Subclasses get instances of themselves.
|
|
86
|
+
*/
|
|
87
|
+
static fromSchema<UserData extends Dictionary = Dictionary>(schema: RequestSchema): CrawleeRequest<UserData>;
|
|
91
88
|
/**
|
|
92
89
|
* Converts the Crawlee Request object to a `fetch` API Request object.
|
|
93
90
|
* @returns The native `fetch` API Request object.
|
|
94
91
|
*/
|
|
95
92
|
intoFetchAPIRequest(): Request;
|
|
96
|
-
/** Tells the crawler processing this request to skip the navigation and process the request directly. */
|
|
97
|
-
get skipNavigation(): boolean;
|
|
98
|
-
/** Tells the crawler processing this request to skip the navigation and process the request directly. */
|
|
99
|
-
set skipNavigation(value: boolean);
|
|
100
|
-
/**
|
|
101
|
-
* Depth of the request in the current crawl tree.
|
|
102
|
-
* Note that this is dependent on the crawler setup and might produce unexpected results when used with multiple crawlers.
|
|
103
|
-
*/
|
|
104
|
-
get crawlDepth(): number;
|
|
105
|
-
/**
|
|
106
|
-
* Depth of the request in the current crawl tree.
|
|
107
|
-
* Note that this is dependent on the crawler setup and might produce unexpected results when used with multiple crawlers.
|
|
108
|
-
*/
|
|
109
|
-
set crawlDepth(value: number);
|
|
110
|
-
/** Indicates the number of times the crawling of the request has rotated the session due to a session or a proxy error. */
|
|
111
|
-
get sessionRotationCount(): number;
|
|
112
|
-
/** Indicates the number of times the crawling of the request has rotated the session due to a session or a proxy error. */
|
|
113
|
-
set sessionRotationCount(value: number);
|
|
114
93
|
/** shortcut for getting `request.userData.label` */
|
|
115
94
|
get label(): string | undefined;
|
|
116
95
|
/** shortcut for setting `request.userData.label` */
|
|
117
96
|
set label(value: string | undefined);
|
|
118
|
-
/** Maximum number of retries for this request. Allows to override the global `maxRequestRetries` option of `BasicCrawler`. */
|
|
119
|
-
get maxRetries(): number | undefined;
|
|
120
|
-
/** Maximum number of retries for this request. Allows to override the global `maxRequestRetries` option of `BasicCrawler`. */
|
|
121
|
-
set maxRetries(value: number | undefined);
|
|
122
|
-
/** Describes the request's current lifecycle state. */
|
|
123
|
-
get state(): RequestState;
|
|
124
|
-
/** Describes the request's current lifecycle state. */
|
|
125
|
-
set state(value: RequestState);
|
|
126
|
-
private get enqueueStrategy();
|
|
127
|
-
private set enqueueStrategy(value);
|
|
128
|
-
/**
|
|
129
|
-
* Stores information about an error that occurred during processing of this request.
|
|
130
|
-
*
|
|
131
|
-
* You should always use Error instances when throwing errors in JavaScript.
|
|
132
|
-
*
|
|
133
|
-
* Nevertheless, to improve the debugging experience when using third party libraries
|
|
134
|
-
* that may not always throw an Error instance, the function performs a type
|
|
135
|
-
* inspection of the passed argument and attempts to extract as much information
|
|
136
|
-
* as possible, since just throwing a bad type error makes any debugging rather difficult.
|
|
137
|
-
*
|
|
138
|
-
* @param errorOrMessage Error object or error message to be stored in the request.
|
|
139
|
-
* @param [options]
|
|
140
|
-
*/
|
|
141
|
-
pushErrorMessage(errorOrMessage: unknown, options?: PushErrorMessageOptions): void;
|
|
142
97
|
/** @internal */
|
|
143
|
-
static computeUniqueKey({ url, method, payload, keepUrlFragment, useExtendedUniqueKey, }: ComputeUniqueKeyOptions): string;
|
|
98
|
+
static computeUniqueKey({ url, method, payload, keepUrlFragment, useExtendedUniqueKey, alwaysEnqueue, }: ComputeUniqueKeyOptions): string;
|
|
144
99
|
/** @internal */
|
|
145
100
|
static hashPayload(payload: BinaryLike): string;
|
|
146
101
|
}
|
|
@@ -161,7 +116,7 @@ export interface RequestOptions<UserData extends Dictionary = Dictionary> {
|
|
|
161
116
|
* The `keepUrlFragment` option determines whether URL hash fragment is included in the `uniqueKey` or not.
|
|
162
117
|
*
|
|
163
118
|
* The `useExtendedUniqueKey` options determines whether method and payload are included in the `uniqueKey`,
|
|
164
|
-
* producing a `uniqueKey` in the following format: `METHOD
|
|
119
|
+
* producing a `uniqueKey` in the following format: `METHOD|payloadHash|normalizedUrl`. This is useful
|
|
165
120
|
* when requests point to the same URL, but with different methods and payloads. For example: form submits.
|
|
166
121
|
*
|
|
167
122
|
* Pass an arbitrary non-empty text value to the `uniqueKey` property
|
|
@@ -185,6 +140,9 @@ export interface RequestOptions<UserData extends Dictionary = Dictionary> {
|
|
|
185
140
|
/**
|
|
186
141
|
* Custom user data assigned to the request. Use this to save any request related data to the
|
|
187
142
|
* request's scope, keeping them accessible on retries, failures etc.
|
|
143
|
+
*
|
|
144
|
+
* All data stored in `userData` must be JSON-serializable.
|
|
145
|
+
* Storing non-serializable values (e.g. functions, symbols) may result in unexpected results.
|
|
188
146
|
*/
|
|
189
147
|
userData?: UserData;
|
|
190
148
|
/**
|
|
@@ -206,14 +164,30 @@ export interface RequestOptions<UserData extends Dictionary = Dictionary> {
|
|
|
206
164
|
* @default false
|
|
207
165
|
*/
|
|
208
166
|
useExtendedUniqueKey?: boolean;
|
|
167
|
+
/**
|
|
168
|
+
* If `true` then a random value is included in the `uniqueKey` computation, ensuring the request
|
|
169
|
+
* is always enqueued even if a request with the same URL (and method/payload) is already present
|
|
170
|
+
* in the queue. Cannot be used together with a custom `uniqueKey`.
|
|
171
|
+
* @default false
|
|
172
|
+
*/
|
|
173
|
+
alwaysEnqueue?: boolean;
|
|
209
174
|
/**
|
|
210
175
|
* The `true` value indicates that the request will not be automatically retried on error.
|
|
211
176
|
* @default false
|
|
212
177
|
*/
|
|
213
178
|
noRetry?: boolean;
|
|
179
|
+
/**
|
|
180
|
+
* ID of a session from the crawler's `SessionPool` to use for this request.
|
|
181
|
+
* When set, the crawler will fetch this session from the pool instead of creating a new one.
|
|
182
|
+
*/
|
|
183
|
+
sessionId?: string;
|
|
214
184
|
/**
|
|
215
185
|
* If set to `true` then the crawler processing this request evaluates
|
|
216
186
|
* the `requestHandler` immediately without prior browser navigation.
|
|
187
|
+
*
|
|
188
|
+
* When enabled, the crawling context will not contain the results of the navigation
|
|
189
|
+
* (e.g. `response`, `body`, `contentType`, `$` or `request.loadedUrl`).
|
|
190
|
+
* Accessing these properties will throw a {@link NavigationSkippedError} at runtime.
|
|
217
191
|
* @default false
|
|
218
192
|
*/
|
|
219
193
|
skipNavigation?: boolean;
|
|
@@ -223,31 +197,12 @@ export interface RequestOptions<UserData extends Dictionary = Dictionary> {
|
|
|
223
197
|
* @default 0
|
|
224
198
|
*/
|
|
225
199
|
crawlDepth?: number;
|
|
226
|
-
/**
|
|
227
|
-
* Reason for skipping this request.
|
|
228
|
-
* This is used to provide more information about why the request was skipped.
|
|
229
|
-
* @internal
|
|
230
|
-
*/
|
|
231
|
-
skippedReason?: SkippedRequestReason;
|
|
232
200
|
/**
|
|
233
201
|
* Maximum number of retries for this request. Allows to override the global `maxRequestRetries` option of `BasicCrawler`.
|
|
234
202
|
*/
|
|
235
203
|
maxRetries?: number;
|
|
236
204
|
/** @internal */
|
|
237
|
-
|
|
238
|
-
/** @internal */
|
|
239
|
-
handledAt?: string;
|
|
240
|
-
/** @internal */
|
|
241
|
-
lockExpiresAt?: Date;
|
|
242
|
-
/** @internal */
|
|
243
|
-
enqueueStrategy?: EnqueueLinksOptions['strategy'];
|
|
244
|
-
}
|
|
245
|
-
export interface PushErrorMessageOptions {
|
|
246
|
-
/**
|
|
247
|
-
* Only push the error message without stack trace when true.
|
|
248
|
-
* @default false
|
|
249
|
-
*/
|
|
250
|
-
omitStack?: boolean;
|
|
205
|
+
enqueueStrategy?: EnqueueStrategyOption;
|
|
251
206
|
}
|
|
252
207
|
interface ComputeUniqueKeyOptions {
|
|
253
208
|
url: string;
|
|
@@ -255,6 +210,7 @@ interface ComputeUniqueKeyOptions {
|
|
|
255
210
|
payload?: string | Buffer;
|
|
256
211
|
keepUrlFragment?: boolean;
|
|
257
212
|
useExtendedUniqueKey?: boolean;
|
|
213
|
+
alwaysEnqueue?: boolean;
|
|
258
214
|
}
|
|
259
215
|
export type Source = (Partial<RequestOptions> & {
|
|
260
216
|
requestsFromUrl?: string;
|
|
@@ -266,4 +222,3 @@ export interface InternalSource {
|
|
|
266
222
|
regex?: RegExp;
|
|
267
223
|
}
|
|
268
224
|
export { CrawleeRequest as Request };
|
|
269
|
-
//# sourceMappingURL=request.d.ts.map
|