@crawlee/core 4.0.0-beta.99 → 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 +16 -47
- package/configuration.js +13 -25
- package/debug.js +4 -4
- package/errors.d.ts +28 -38
- package/errors.js +33 -47
- package/events/event_manager.d.ts +2 -2
- package/events/event_manager.js +7 -6
- package/events/index.d.ts +1 -0
- package/events/local_event_manager.d.ts +1 -8
- package/events/local_event_manager.js +13 -13
- 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 +52 -20
- package/memory-storage/memory-storage.d.ts +15 -18
- package/memory-storage/memory-storage.js +80 -58
- package/memory-storage/resource-clients/dataset.d.ts +1 -6
- package/memory-storage/resource-clients/dataset.js +23 -31
- package/memory-storage/resource-clients/key-value-store.d.ts +1 -10
- package/memory-storage/resource-clients/key-value-store.js +43 -67
- package/memory-storage/resource-clients/request-queue.d.ts +1 -42
- package/memory-storage/resource-clients/request-queue.js +109 -117
- package/owned_or_injected.d.ts +1 -3
- package/owned_or_injected.js +17 -17
- package/package.json +17 -20
- package/proxy_configuration.d.ts +21 -26
- package/proxy_configuration.js +35 -25
- package/recoverable_state.d.ts +104 -47
- package/recoverable_state.js +199 -74
- package/request.d.ts +20 -107
- package/request.js +78 -244
- package/serialization.js +17 -16
- package/service_locator.d.ts +22 -10
- package/service_locator.js +59 -48
- package/storages/batched_adds.d.ts +37 -0
- package/storages/batched_adds.js +73 -0
- package/storages/dataset.d.ts +13 -8
- package/storages/dataset.js +149 -40
- package/storages/index.d.ts +4 -4
- package/storages/index.js +2 -4
- package/storages/key_value_store.d.ts +16 -35
- package/storages/key_value_store.js +223 -110
- package/storages/key_value_store_codec.js +6 -11
- package/storages/request_dedup_cache.d.ts +1 -4
- package/storages/request_dedup_cache.js +15 -15
- package/storages/request_list.d.ts +9 -104
- package/storages/request_list.js +236 -233
- package/storages/request_loader.d.ts +49 -18
- package/storages/request_loader.js +36 -1
- package/storages/request_manager.d.ts +86 -0
- package/storages/request_manager_tandem.d.ts +14 -38
- package/storages/request_manager_tandem.js +67 -64
- package/storages/request_queue.d.ts +23 -50
- package/storages/request_queue.js +371 -226
- package/storages/storage_instance_manager.d.ts +2 -4
- package/storages/storage_instance_manager.js +21 -21
- package/storages/storage_stats.d.ts +1 -1
- package/storages/storage_stats.js +4 -4
- package/storages/transaction.d.ts +270 -0
- package/storages/transaction.js +296 -0
- package/storages/utils.d.ts +6 -3
- package/storages/utils.js +11 -2
- package/system-info/runtime.js +7 -7
- package/url.d.ts +9 -0
- package/url.js +11 -0
- package/validators.d.ts +23 -25
- package/validators.js +14 -25
- package/autoscaling/autoscaled_pool.d.ts +0 -213
- package/autoscaling/autoscaled_pool.js +0 -378
- package/autoscaling/client_load_signal.d.ts +0 -59
- package/autoscaling/client_load_signal.js +0 -73
- package/autoscaling/concurrency_system.d.ts +0 -283
- package/autoscaling/concurrency_system.js +0 -350
- package/autoscaling/cpu_load_signal.d.ts +0 -44
- package/autoscaling/cpu_load_signal.js +0 -46
- package/autoscaling/event_loop_load_signal.d.ts +0 -54
- 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 -99
- package/autoscaling/load_signal.js +0 -103
- package/autoscaling/memory_load_signal.d.ts +0 -56
- package/autoscaling/memory_load_signal.js +0 -106
- package/autoscaling/snapshotter.d.ts +0 -87
- package/autoscaling/snapshotter.js +0 -67
- package/autoscaling/system_status.d.ts +0 -161
- 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 -257
- package/crawlers/crawler_commons.js +0 -107
- package/crawlers/error_snapshotter.d.ts +0 -59
- 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 -5
- package/crawlers/internals/types.d.ts +0 -7
- package/crawlers/statistics.d.ts +0 -209
- package/crawlers/statistics.js +0 -350
- package/enqueue_links/enqueue_links.d.ts +0 -264
- package/enqueue_links/enqueue_links.js +0 -271
- package/enqueue_links/index.d.ts +0 -2
- package/enqueue_links/index.js +0 -2
- package/enqueue_links/shared.d.ts +0 -83
- package/enqueue_links/shared.js +0 -221
- package/router.d.ts +0 -309
- 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 -161
- package/session_pool/session.js +0 -218
- package/session_pool/session_pool.d.ts +0 -246
- package/session_pool/session_pool.js +0 -386
- package/storages/access_checking.d.ts +0 -12
- package/storages/access_checking.js +0 -17
- package/storages/sitemap_request_loader.d.ts +0 -249
- package/storages/sitemap_request_loader.js +0 -432
- /package/{crawlers/internals/types.js → events/system_info.js} +0 -0
package/recoverable_state.js
CHANGED
|
@@ -1,4 +1,29 @@
|
|
|
1
|
-
import {
|
|
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
|
+
}
|
|
2
27
|
/**
|
|
3
28
|
* A class for managing persistent recoverable state using a plain JavaScript object.
|
|
4
29
|
*
|
|
@@ -10,134 +35,234 @@ import { KeyValueStore, serviceLocator } from '@crawlee/core';
|
|
|
10
35
|
* The class automatically hooks into the event system to persist state when needed.
|
|
11
36
|
*/
|
|
12
37
|
export class RecoverableState {
|
|
13
|
-
defaultState;
|
|
14
|
-
state = null;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
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;
|
|
23
53
|
/**
|
|
24
54
|
* Initialize a new recoverable state object.
|
|
25
55
|
*
|
|
26
56
|
* @param options Configuration options for the recoverable state
|
|
27
57
|
*/
|
|
28
58
|
constructor(options) {
|
|
29
|
-
|
|
30
|
-
this
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
this
|
|
35
|
-
this
|
|
36
|
-
this
|
|
37
|
-
this
|
|
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
|
+
};
|
|
38
101
|
}
|
|
39
102
|
/**
|
|
40
103
|
* Initialize the recoverable state.
|
|
41
104
|
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
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.
|
|
44
112
|
*
|
|
45
113
|
* @returns The loaded state object
|
|
46
114
|
*/
|
|
47
115
|
async initialize() {
|
|
48
|
-
if (this
|
|
49
|
-
return this.currentValue;
|
|
50
|
-
}
|
|
51
|
-
if (!this.persistenceEnabled) {
|
|
52
|
-
this.state = this.deserialize(this.serialize(this.defaultState));
|
|
116
|
+
if (this.#initialized) {
|
|
53
117
|
return this.currentValue;
|
|
54
118
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
119
|
+
if (this.#persistenceEnabled) {
|
|
120
|
+
await this.#openKeyValueStore();
|
|
121
|
+
serviceLocator.getEventManager().on(EventType.PERSIST_STATE, this.#persistStateQuietly);
|
|
122
|
+
this.#listening = true;
|
|
58
123
|
}
|
|
59
|
-
|
|
60
|
-
|
|
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();
|
|
61
131
|
}
|
|
62
|
-
this.keyValueStore = await KeyValueStore.open(kvsIdentifier, {
|
|
63
|
-
configuration: serviceLocator.getConfiguration(),
|
|
64
|
-
});
|
|
65
|
-
await this.loadSavedState();
|
|
66
|
-
// Register for persist state events
|
|
67
|
-
const eventManager = serviceLocator.getEventManager();
|
|
68
|
-
eventManager.on("persistState" /* EventType.PERSIST_STATE */, this.persistState);
|
|
69
132
|
return this.currentValue;
|
|
70
133
|
}
|
|
71
134
|
/**
|
|
72
135
|
* Clean up resources used by the recoverable state.
|
|
73
136
|
*
|
|
74
137
|
* If persistence is enabled, this method deregisters the object from PERSIST_STATE events
|
|
75
|
-
* and persists the current state one last time
|
|
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.
|
|
76
142
|
*/
|
|
77
143
|
async teardown() {
|
|
78
|
-
|
|
144
|
+
this.#initialized = false;
|
|
145
|
+
if (!this.#persistenceEnabled) {
|
|
79
146
|
return;
|
|
80
147
|
}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
await this
|
|
148
|
+
serviceLocator.getEventManager().off(EventType.PERSIST_STATE, this.#persistStateQuietly);
|
|
149
|
+
this.#listening = false;
|
|
150
|
+
await this.#persistStateQuietly();
|
|
84
151
|
}
|
|
85
152
|
/**
|
|
86
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.
|
|
87
158
|
*/
|
|
88
159
|
get currentValue() {
|
|
89
|
-
if (this
|
|
90
|
-
throw new Error('Recoverable state has not yet been loaded');
|
|
160
|
+
if (this.#state === null) {
|
|
161
|
+
throw new Error('Recoverable state has not yet been loaded - call initialize() or reset() first');
|
|
91
162
|
}
|
|
92
|
-
return this
|
|
163
|
+
return this.#state;
|
|
93
164
|
}
|
|
94
165
|
/**
|
|
95
|
-
* Reset the state to the default values
|
|
166
|
+
* Reset the in-memory state to the default values, leaving any persisted record alone.
|
|
96
167
|
*
|
|
97
|
-
*
|
|
98
|
-
* clears the persisted state from the KeyValueStore.
|
|
168
|
+
* Use {@link RecoverableState.resetStore} to clear the persisted record as well.
|
|
99
169
|
*/
|
|
100
|
-
|
|
101
|
-
this
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
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;
|
|
107
189
|
}
|
|
190
|
+
const keyValueStore = await this.#openKeyValueStore();
|
|
191
|
+
await this.#withTimeout(async () => keyValueStore.setValue(this.#persistStateKey, null), 'Clearing the persisted state');
|
|
108
192
|
}
|
|
109
193
|
/**
|
|
110
194
|
* Persist the current state to the KeyValueStore.
|
|
111
195
|
*
|
|
112
196
|
* This method is typically called in response to a PERSIST_STATE event, but can also be called
|
|
113
|
-
* directly when needed.
|
|
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.
|
|
114
199
|
*
|
|
115
200
|
* @param eventData Optional data associated with a PERSIST_STATE event
|
|
116
201
|
*/
|
|
117
202
|
async persistState(eventData) {
|
|
118
|
-
this
|
|
119
|
-
|
|
120
|
-
throw new Error('Recoverable state has not yet been initialized');
|
|
203
|
+
if (!this.#persistenceEnabled || this.#state === null) {
|
|
204
|
+
return;
|
|
121
205
|
}
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
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;
|
|
126
229
|
}
|
|
230
|
+
this.#keyValueStore = await this.#keyValueStore;
|
|
231
|
+
return this.#keyValueStore;
|
|
127
232
|
}
|
|
128
233
|
/**
|
|
129
|
-
* Load the saved state from the KeyValueStore
|
|
234
|
+
* Load the saved state from the KeyValueStore. Leaves the current state alone if there is no record to load.
|
|
130
235
|
*/
|
|
131
|
-
async loadSavedState() {
|
|
132
|
-
if (this
|
|
133
|
-
|
|
236
|
+
async #loadSavedState() {
|
|
237
|
+
if (!this.#persistenceEnabled) {
|
|
238
|
+
return;
|
|
134
239
|
}
|
|
135
|
-
const
|
|
136
|
-
if (
|
|
137
|
-
|
|
240
|
+
const keyValueStore = await this.#resolveKeyValueStore();
|
|
241
|
+
if (keyValueStore === null) {
|
|
242
|
+
return;
|
|
138
243
|
}
|
|
139
|
-
|
|
140
|
-
|
|
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;
|
|
141
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.`));
|
|
142
267
|
}
|
|
143
268
|
}
|
package/request.d.ts
CHANGED
|
@@ -1,20 +1,12 @@
|
|
|
1
1
|
import type { BinaryLike } from 'node:crypto';
|
|
2
|
-
import type { AllowedHttpMethods, Dictionary } from '@crawlee/types';
|
|
3
|
-
import type {
|
|
4
|
-
|
|
5
|
-
export
|
|
6
|
-
UNPROCESSED = 0,
|
|
7
|
-
BEFORE_NAV = 1,
|
|
8
|
-
AFTER_NAV = 2,
|
|
9
|
-
REQUEST_HANDLER = 3,
|
|
10
|
-
DONE = 4,
|
|
11
|
-
ERROR_HANDLER = 5,
|
|
12
|
-
ERROR = 6,
|
|
13
|
-
SKIPPED = 7
|
|
14
|
-
}
|
|
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';
|
|
15
6
|
/**
|
|
16
|
-
* Represents a URL to be crawled, optionally including HTTP method, headers, payload and other metadata
|
|
17
|
-
*
|
|
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.
|
|
18
10
|
*
|
|
19
11
|
* Each `Request` instance has the `uniqueKey` property, which can be either specified
|
|
20
12
|
* manually in the constructor or generated automatically from the URL. Two requests with the same `uniqueKey`
|
|
@@ -30,21 +22,16 @@ export declare enum RequestState {
|
|
|
30
22
|
* const request = new Request({
|
|
31
23
|
* url: 'http://www.example.com',
|
|
32
24
|
* headers: { Accept: 'application/json' },
|
|
25
|
+
* userData: { foo: 'bar' },
|
|
33
26
|
* });
|
|
34
27
|
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
* request.userData.foo = 'bar';
|
|
38
|
-
* request.pushErrorMessage(new Error('Request failed!'));
|
|
39
|
-
*
|
|
40
|
-
* ...
|
|
41
|
-
*
|
|
42
|
-
* const foo = request.userData.foo;
|
|
28
|
+
* await requestQueue.addRequest(request);
|
|
43
29
|
* ```
|
|
44
30
|
* @category Sources
|
|
45
31
|
*/
|
|
46
32
|
declare class CrawleeRequest<UserData extends Dictionary = Dictionary> {
|
|
47
|
-
|
|
33
|
+
#private;
|
|
34
|
+
/** Storage-assigned request ID. Only present on requests that went through a {@link RequestQueue}. */
|
|
48
35
|
id?: string;
|
|
49
36
|
/** URL of the web page to crawl. */
|
|
50
37
|
url: string;
|
|
@@ -74,8 +61,6 @@ declare class CrawleeRequest<UserData extends Dictionary = Dictionary> {
|
|
|
74
61
|
errorMessages: string[];
|
|
75
62
|
/** Object with HTTP headers. Key is header name, value is the value. */
|
|
76
63
|
headers?: Record<string, string>;
|
|
77
|
-
/** Private store for the custom user data assigned to the request. */
|
|
78
|
-
private _userData;
|
|
79
64
|
/**
|
|
80
65
|
* Custom user data assigned to the request.
|
|
81
66
|
*
|
|
@@ -90,78 +75,25 @@ declare class CrawleeRequest<UserData extends Dictionary = Dictionary> {
|
|
|
90
75
|
handledAt?: string;
|
|
91
76
|
/**
|
|
92
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}.
|
|
93
81
|
*/
|
|
94
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>;
|
|
95
88
|
/**
|
|
96
89
|
* Converts the Crawlee Request object to a `fetch` API Request object.
|
|
97
90
|
* @returns The native `fetch` API Request object.
|
|
98
91
|
*/
|
|
99
92
|
intoFetchAPIRequest(): Request;
|
|
100
|
-
/**
|
|
101
|
-
* Tells the crawler processing this request to skip the navigation and process the request directly.
|
|
102
|
-
*
|
|
103
|
-
* When this is set to `true`, the crawling context will not contain the results of the navigation
|
|
104
|
-
* (e.g. `response`, `body`, `contentType`, `$` or `request.loadedUrl`).
|
|
105
|
-
* Accessing these properties will throw a {@link NavigationSkippedError} at runtime.
|
|
106
|
-
*/
|
|
107
|
-
get skipNavigation(): boolean;
|
|
108
|
-
/**
|
|
109
|
-
* Tells the crawler processing this request to skip the navigation and process the request directly.
|
|
110
|
-
*
|
|
111
|
-
* When this is set to `true`, the crawling context will not contain the results of the navigation
|
|
112
|
-
* (e.g. `response`, `body`, `contentType`, `$` or `request.loadedUrl`).
|
|
113
|
-
* Accessing these properties will throw a {@link NavigationSkippedError} at runtime.
|
|
114
|
-
*/
|
|
115
|
-
set skipNavigation(value: boolean);
|
|
116
|
-
/**
|
|
117
|
-
* Depth of the request in the current crawl tree.
|
|
118
|
-
* Note that this is dependent on the crawler setup and might produce unexpected results when used with multiple crawlers.
|
|
119
|
-
*/
|
|
120
|
-
get crawlDepth(): number;
|
|
121
|
-
/**
|
|
122
|
-
* Depth of the request in the current crawl tree.
|
|
123
|
-
* Note that this is dependent on the crawler setup and might produce unexpected results when used with multiple crawlers.
|
|
124
|
-
*/
|
|
125
|
-
set crawlDepth(value: number);
|
|
126
|
-
/** ID of a session to use for this request. When set, the crawler will fetch this session from the session pool instead of creating a new one. */
|
|
127
|
-
get sessionId(): string | undefined;
|
|
128
|
-
set sessionId(value: string | undefined);
|
|
129
93
|
/** shortcut for getting `request.userData.label` */
|
|
130
94
|
get label(): string | undefined;
|
|
131
95
|
/** shortcut for setting `request.userData.label` */
|
|
132
96
|
set label(value: string | undefined);
|
|
133
|
-
/** Maximum number of retries for this request. Allows to override the global `maxRequestRetries` option of `BasicCrawler`. */
|
|
134
|
-
get maxRetries(): number | undefined;
|
|
135
|
-
/** Maximum number of retries for this request. Allows to override the global `maxRequestRetries` option of `BasicCrawler`. */
|
|
136
|
-
set maxRetries(value: number | undefined);
|
|
137
|
-
/** Describes the request's current lifecycle state. */
|
|
138
|
-
get state(): RequestState;
|
|
139
|
-
/** Describes the request's current lifecycle state. */
|
|
140
|
-
set state(value: RequestState);
|
|
141
|
-
/**
|
|
142
|
-
* Reason for skipping this request.
|
|
143
|
-
*/
|
|
144
|
-
get skippedReason(): SkippedRequestReason | undefined;
|
|
145
|
-
/**
|
|
146
|
-
* Reason for skipping this request.
|
|
147
|
-
*/
|
|
148
|
-
set skippedReason(value: SkippedRequestReason | undefined);
|
|
149
|
-
private get enqueueStrategy();
|
|
150
|
-
private set enqueueStrategy(value);
|
|
151
|
-
/**
|
|
152
|
-
* Stores information about an error that occurred during processing of this request.
|
|
153
|
-
*
|
|
154
|
-
* You should always use Error instances when throwing errors in JavaScript.
|
|
155
|
-
*
|
|
156
|
-
* Nevertheless, to improve the debugging experience when using third party libraries
|
|
157
|
-
* that may not always throw an Error instance, the function performs a type
|
|
158
|
-
* inspection of the passed argument and attempts to extract as much information
|
|
159
|
-
* as possible, since just throwing a bad type error makes any debugging rather difficult.
|
|
160
|
-
*
|
|
161
|
-
* @param errorOrMessage Error object or error message to be stored in the request.
|
|
162
|
-
* @param [options]
|
|
163
|
-
*/
|
|
164
|
-
pushErrorMessage(errorOrMessage: unknown, options?: PushErrorMessageOptions): void;
|
|
165
97
|
/** @internal */
|
|
166
98
|
static computeUniqueKey({ url, method, payload, keepUrlFragment, useExtendedUniqueKey, alwaysEnqueue, }: ComputeUniqueKeyOptions): string;
|
|
167
99
|
/** @internal */
|
|
@@ -265,31 +197,12 @@ export interface RequestOptions<UserData extends Dictionary = Dictionary> {
|
|
|
265
197
|
* @default 0
|
|
266
198
|
*/
|
|
267
199
|
crawlDepth?: number;
|
|
268
|
-
/**
|
|
269
|
-
* Reason for skipping this request.
|
|
270
|
-
* This is used to provide more information about why the request was skipped.
|
|
271
|
-
* @internal
|
|
272
|
-
*/
|
|
273
|
-
skippedReason?: SkippedRequestReason;
|
|
274
200
|
/**
|
|
275
201
|
* Maximum number of retries for this request. Allows to override the global `maxRequestRetries` option of `BasicCrawler`.
|
|
276
202
|
*/
|
|
277
203
|
maxRetries?: number;
|
|
278
204
|
/** @internal */
|
|
279
|
-
|
|
280
|
-
/** @internal */
|
|
281
|
-
handledAt?: string;
|
|
282
|
-
/** @internal */
|
|
283
|
-
lockExpiresAt?: Date;
|
|
284
|
-
/** @internal */
|
|
285
|
-
enqueueStrategy?: EnqueueLinksOptions['strategy'];
|
|
286
|
-
}
|
|
287
|
-
export interface PushErrorMessageOptions {
|
|
288
|
-
/**
|
|
289
|
-
* Only push the error message without stack trace when true.
|
|
290
|
-
* @default false
|
|
291
|
-
*/
|
|
292
|
-
omitStack?: boolean;
|
|
205
|
+
enqueueStrategy?: EnqueueStrategyOption;
|
|
293
206
|
}
|
|
294
207
|
interface ComputeUniqueKeyOptions {
|
|
295
208
|
url: string;
|