@crawlee/core 4.0.0-beta.17 → 4.0.0-beta.170
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 +70 -92
- 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 +128 -124
- package/crawlers/crawler_commons.js +1 -108
- package/crawlers/error_snapshotter.d.ts +2 -5
- package/crawlers/error_snapshotter.js +5 -6
- 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 +194 -79
- package/crawlers/statistics.js +382 -201
- 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 +82 -4
- package/errors.js +101 -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 +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 +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 +414 -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 +17 -16
- package/proxy_configuration.d.ts +22 -128
- package/proxy_configuration.js +32 -144
- package/recoverable_state.d.ts +84 -51
- package/recoverable_state.js +175 -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 +40 -90
- package/session_pool/session.js +103 -160
- package/session_pool/session_pool.d.ts +85 -101
- package/session_pool/session_pool.js +254 -210
- package/storages/batched_adds.d.ts +37 -0
- package/storages/batched_adds.js +73 -0
- package/storages/dataset.d.ts +114 -56
- package/storages/dataset.js +292 -149
- package/storages/index.d.ts +9 -9
- package/storages/index.js +7 -9
- package/storages/key_value_store.d.ts +186 -48
- package/storages/key_value_store.js +452 -170
- 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 +54 -129
- package/storages/request_list.js +272 -245
- 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 +223 -0
- package/storages/throttling_request_manager.js +835 -0
- package/storages/transaction.d.ts +260 -0
- package/storages/transaction.js +287 -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 +23 -18
- package/validators.js +14 -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
package/recoverable_state.d.ts
CHANGED
|
@@ -1,5 +1,31 @@
|
|
|
1
|
-
import { Configuration } from '@crawlee/core';
|
|
2
|
-
import
|
|
1
|
+
import type { Configuration, CrawleeLogger } from '@crawlee/core';
|
|
2
|
+
import { KeyValueStore } from '@crawlee/core';
|
|
3
|
+
import type { Awaitable } from '@crawlee/types';
|
|
4
|
+
import type { StandardSchemaV1 } from '@standard-schema/spec';
|
|
5
|
+
/**
|
|
6
|
+
* One direction of the conversion between the state model and its persisted form - either a plain function, or a
|
|
7
|
+
* [Standard Schema](https://standardschema.dev) whose validated output is the result.
|
|
8
|
+
*
|
|
9
|
+
* A schema that fails to validate makes {@link RecoverableState} throw a {@link StateValidationError}. Zod
|
|
10
|
+
* codecs work directly, as their validation *is* the decode direction; use `(state) => codec.encode(state)` for the
|
|
11
|
+
* other one.
|
|
12
|
+
*/
|
|
13
|
+
export type StateConversion<TFrom, TTo> = ((value: TFrom) => Awaitable<TTo>) | StandardSchemaV1<TFrom, TTo>;
|
|
14
|
+
/**
|
|
15
|
+
* A {@link StateConversion} for a caller that cannot await one - {@link Statistics}, whose `toJSON()` is
|
|
16
|
+
* synchronous, being the reason this exists.
|
|
17
|
+
*
|
|
18
|
+
* Only the function arm can be narrowed here: a Standard Schema is free to validate asynchronously, so a schema
|
|
19
|
+
* that does is rejected when it runs rather than when it is passed.
|
|
20
|
+
*/
|
|
21
|
+
export type SyncStateConversion<TFrom, TTo> = ((value: TFrom) => TTo) | StandardSchemaV1<TFrom, TTo>;
|
|
22
|
+
/**
|
|
23
|
+
* Applies a {@link SyncStateConversion}, throwing a {@link StateValidationError} for a schema that rejects
|
|
24
|
+
* the value.
|
|
25
|
+
*
|
|
26
|
+
* @internal
|
|
27
|
+
*/
|
|
28
|
+
export declare function convertStateSync<TFrom, TTo>(conversion: SyncStateConversion<TFrom, TTo>, value: TFrom, persistStateKey: string): TTo;
|
|
3
29
|
export interface RecoverableStatePersistenceOptions {
|
|
4
30
|
/**
|
|
5
31
|
* The key under which the state is stored in the KeyValueStore
|
|
@@ -10,44 +36,45 @@ export interface RecoverableStatePersistenceOptions {
|
|
|
10
36
|
*/
|
|
11
37
|
persistenceEnabled?: boolean;
|
|
12
38
|
/**
|
|
13
|
-
* The
|
|
14
|
-
*
|
|
39
|
+
* The KeyValueStore to persist into, defaulting to the default store. Accepts a pending
|
|
40
|
+
* {@link KeyValueStore.open} so that callers do not have to be async to point at a specific store.
|
|
15
41
|
*/
|
|
16
|
-
|
|
42
|
+
keyValueStore?: KeyValueStore | PromiseLike<KeyValueStore>;
|
|
17
43
|
/**
|
|
18
|
-
*
|
|
19
|
-
*
|
|
44
|
+
* Time limit for a single load or save of the state, in milliseconds.
|
|
45
|
+
* @default 60_000
|
|
20
46
|
*/
|
|
21
|
-
|
|
47
|
+
persistenceTimeoutMillis?: number;
|
|
22
48
|
}
|
|
23
49
|
/**
|
|
24
50
|
* Options for configuring the RecoverableState
|
|
25
51
|
*/
|
|
26
|
-
export interface RecoverableStateOptions<TStateModel = Record<string, unknown
|
|
52
|
+
export interface RecoverableStateOptions<TStateModel = Record<string, unknown>, TPersistedState = TStateModel> extends RecoverableStatePersistenceOptions {
|
|
27
53
|
/**
|
|
28
|
-
* The
|
|
29
|
-
*
|
|
54
|
+
* The state used when no persisted state is found, and the state {@link RecoverableState.reset} restores.
|
|
55
|
+
*
|
|
56
|
+
* A plain value is deep-copied with `structuredClone` each time it is used, so pass a factory for a state
|
|
57
|
+
* that `structuredClone` cannot rebuild - one holding class instances, say, or one derived from a schema.
|
|
30
58
|
*/
|
|
31
|
-
defaultState: TStateModel;
|
|
59
|
+
defaultState: TStateModel | (() => TStateModel);
|
|
32
60
|
/**
|
|
33
61
|
* A logger instance for logging operations related to state persistence
|
|
34
62
|
*/
|
|
35
|
-
logger?:
|
|
63
|
+
logger?: CrawleeLogger;
|
|
36
64
|
/**
|
|
37
|
-
* Configuration instance to use
|
|
65
|
+
* Configuration instance to use when opening the KeyValueStore
|
|
38
66
|
*/
|
|
39
|
-
|
|
67
|
+
configuration?: Configuration;
|
|
40
68
|
/**
|
|
41
|
-
* Optional
|
|
42
|
-
* If not provided,
|
|
69
|
+
* Optional conversion of the state to a plain JSON-serializable value before it is persisted.
|
|
70
|
+
* If not provided, the state is persisted as is.
|
|
43
71
|
*/
|
|
44
|
-
serialize?:
|
|
72
|
+
serialize?: StateConversion<TStateModel, TPersistedState>;
|
|
45
73
|
/**
|
|
46
|
-
* Optional
|
|
47
|
-
* If not provided,
|
|
48
|
-
* It is advisable to perform validation in this function and to throw an exception if it fails.
|
|
74
|
+
* Optional conversion of a persisted value back to the state model, and the place to validate a record before
|
|
75
|
+
* trusting it. If not provided, the persisted value is used as is.
|
|
49
76
|
*/
|
|
50
|
-
deserialize?:
|
|
77
|
+
deserialize?: StateConversion<TPersistedState, TStateModel>;
|
|
51
78
|
}
|
|
52
79
|
/**
|
|
53
80
|
* A class for managing persistent recoverable state using a plain JavaScript object.
|
|
@@ -59,29 +86,24 @@ export interface RecoverableStateOptions<TStateModel = Record<string, unknown>>
|
|
|
59
86
|
* The state is represented by a plain JavaScript object that can be serialized to and deserialized from JSON.
|
|
60
87
|
* The class automatically hooks into the event system to persist state when needed.
|
|
61
88
|
*/
|
|
62
|
-
export declare class RecoverableState<TStateModel = Record<string, unknown
|
|
63
|
-
private
|
|
64
|
-
private state;
|
|
65
|
-
private readonly persistenceEnabled;
|
|
66
|
-
private readonly persistStateKey;
|
|
67
|
-
private readonly persistStateKvsName?;
|
|
68
|
-
private readonly persistStateKvsId?;
|
|
69
|
-
private keyValueStore;
|
|
70
|
-
private readonly log;
|
|
71
|
-
private readonly config;
|
|
72
|
-
private readonly serialize;
|
|
73
|
-
private readonly deserialize;
|
|
89
|
+
export declare class RecoverableState<TStateModel = Record<string, unknown>, TPersistedState = TStateModel> {
|
|
90
|
+
#private;
|
|
74
91
|
/**
|
|
75
92
|
* Initialize a new recoverable state object.
|
|
76
93
|
*
|
|
77
94
|
* @param options Configuration options for the recoverable state
|
|
78
95
|
*/
|
|
79
|
-
constructor(options: RecoverableStateOptions<TStateModel>);
|
|
96
|
+
constructor(options: RecoverableStateOptions<TStateModel, TPersistedState>);
|
|
80
97
|
/**
|
|
81
98
|
* Initialize the recoverable state.
|
|
82
99
|
*
|
|
83
|
-
*
|
|
84
|
-
*
|
|
100
|
+
* If persistence is enabled, this method loads the saved state and registers the object to listen for
|
|
101
|
+
* PERSIST_STATE events. A state established beforehand by {@link RecoverableState.reset} survives if there
|
|
102
|
+
* is no record to restore.
|
|
103
|
+
*
|
|
104
|
+
* Calling this again after a {@link RecoverableState.teardown} starts a new persistence window - the
|
|
105
|
+
* listener is registered again. The record is not reloaded: the in-memory state is what the teardown wrote, and
|
|
106
|
+
* reloading it would only drop whatever the deserialization leaves out.
|
|
85
107
|
*
|
|
86
108
|
* @returns The loaded state object
|
|
87
109
|
*/
|
|
@@ -90,34 +112,45 @@ export declare class RecoverableState<TStateModel = Record<string, unknown>> {
|
|
|
90
112
|
* Clean up resources used by the recoverable state.
|
|
91
113
|
*
|
|
92
114
|
* If persistence is enabled, this method deregisters the object from PERSIST_STATE events
|
|
93
|
-
* and persists the current state one last time
|
|
115
|
+
* and persists the current state one last time, warning rather than throwing if that write fails - cleanup
|
|
116
|
+
* runs when the work is already done, and failing it would bury whatever the caller was doing. The in-memory
|
|
117
|
+
* state is left alone, and {@link RecoverableState.initialize} can be called again to open a new
|
|
118
|
+
* persistence window.
|
|
94
119
|
*/
|
|
95
120
|
teardown(): Promise<void>;
|
|
96
121
|
/**
|
|
97
122
|
* Get the current state.
|
|
123
|
+
*
|
|
124
|
+
* Throws until the state has been established, by either {@link RecoverableState.initialize} or the
|
|
125
|
+
* synchronous {@link RecoverableState.reset} - the latter being how a caller that cannot await in its
|
|
126
|
+
* constructor gets a usable state right away.
|
|
98
127
|
*/
|
|
99
128
|
get currentValue(): TStateModel;
|
|
100
129
|
/**
|
|
101
|
-
* Reset the state to the default values
|
|
130
|
+
* Reset the in-memory state to the default values, leaving any persisted record alone.
|
|
102
131
|
*
|
|
103
|
-
*
|
|
104
|
-
* clears the persisted state from the KeyValueStore.
|
|
132
|
+
* Use {@link RecoverableState.resetStore} to clear the persisted record as well.
|
|
105
133
|
*/
|
|
106
|
-
reset():
|
|
134
|
+
reset(): void;
|
|
135
|
+
/**
|
|
136
|
+
* Clear the persisted state record, leaving the in-memory state alone.
|
|
137
|
+
*
|
|
138
|
+
* This is a between-lifecycles operation - its point is to stop the next {@link RecoverableState.initialize}
|
|
139
|
+
* from restoring the record, so it throws while PERSIST_STATE events are still being handled, where the next
|
|
140
|
+
* one would write the record straight back. Use {@link RecoverableState.reset} to reset the state itself,
|
|
141
|
+
* or {@link RecoverableState.teardown} before clearing the record.
|
|
142
|
+
*
|
|
143
|
+
* A no-op if persistence is disabled.
|
|
144
|
+
*/
|
|
145
|
+
resetStore(): Promise<void>;
|
|
107
146
|
/**
|
|
108
147
|
* Persist the current state to the KeyValueStore.
|
|
109
148
|
*
|
|
110
149
|
* This method is typically called in response to a PERSIST_STATE event, but can also be called
|
|
111
|
-
* directly when needed.
|
|
150
|
+
* directly when needed. It is a no-op if persistence is disabled, if no KeyValueStore is available yet, or if
|
|
151
|
+
* there is no state to write. A failed write only rejects here - the periodic and teardown ones warn instead.
|
|
112
152
|
*
|
|
113
153
|
* @param eventData Optional data associated with a PERSIST_STATE event
|
|
114
154
|
*/
|
|
115
|
-
persistState(eventData?:
|
|
116
|
-
isMigrating: boolean;
|
|
117
|
-
}): Promise<void>;
|
|
118
|
-
/**
|
|
119
|
-
* Load the saved state from the KeyValueStore
|
|
120
|
-
*/
|
|
121
|
-
private loadSavedState;
|
|
155
|
+
persistState(eventData?: Record<string, unknown>): Promise<void>;
|
|
122
156
|
}
|
|
123
|
-
//# sourceMappingURL=recoverable_state.d.ts.map
|
package/recoverable_state.js
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
1
|
+
import { addTimeoutToPromise, storage as timeoutStorage } from '@apify/timeout';
|
|
2
|
+
import { EventType, KeyValueStore, serviceLocator, StateValidationError } from '@crawlee/core';
|
|
3
|
+
const DEFAULT_PERSISTENCE_TIMEOUT_MILLIS = 60_000;
|
|
4
|
+
/**
|
|
5
|
+
* Applies a {@link SyncStateConversion}, throwing a {@link StateValidationError} for a schema that rejects
|
|
6
|
+
* the value.
|
|
7
|
+
*
|
|
8
|
+
* @internal
|
|
9
|
+
*/
|
|
10
|
+
export function convertStateSync(conversion, value, persistStateKey) {
|
|
11
|
+
if (typeof conversion === 'function') {
|
|
12
|
+
return conversion(value);
|
|
13
|
+
}
|
|
14
|
+
const result = conversion['~standard'].validate(value);
|
|
15
|
+
if ('then' in result) {
|
|
16
|
+
throw new Error(`The state conversion for '${persistStateKey}' validated asynchronously, which this caller cannot await.`);
|
|
17
|
+
}
|
|
18
|
+
if (result.issues) {
|
|
19
|
+
throw new StateValidationError(persistStateKey, result.issues);
|
|
20
|
+
}
|
|
21
|
+
return result.value;
|
|
22
|
+
}
|
|
3
23
|
/**
|
|
4
24
|
* A class for managing persistent recoverable state using a plain JavaScript object.
|
|
5
25
|
*
|
|
@@ -11,130 +31,213 @@ import log from '@apify/log';
|
|
|
11
31
|
* The class automatically hooks into the event system to persist state when needed.
|
|
12
32
|
*/
|
|
13
33
|
export class RecoverableState {
|
|
14
|
-
defaultState;
|
|
15
|
-
state = null;
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
34
|
+
#defaultState;
|
|
35
|
+
#state = null;
|
|
36
|
+
#initialized = false;
|
|
37
|
+
#recordLoaded = false;
|
|
38
|
+
#listening = false;
|
|
39
|
+
#persistenceEnabled;
|
|
40
|
+
#persistStateKey;
|
|
41
|
+
#persistenceTimeoutMillis;
|
|
42
|
+
#configuration;
|
|
43
|
+
#keyValueStore;
|
|
44
|
+
#log;
|
|
45
|
+
#serialize;
|
|
46
|
+
#deserialize;
|
|
47
|
+
#persistStateQuietly;
|
|
25
48
|
/**
|
|
26
49
|
* Initialize a new recoverable state object.
|
|
27
50
|
*
|
|
28
51
|
* @param options Configuration options for the recoverable state
|
|
29
52
|
*/
|
|
30
53
|
constructor(options) {
|
|
31
|
-
|
|
32
|
-
this
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
this
|
|
37
|
-
this
|
|
38
|
-
this
|
|
39
|
-
this
|
|
40
|
-
this
|
|
54
|
+
const { defaultState } = options;
|
|
55
|
+
this.#defaultState =
|
|
56
|
+
typeof defaultState === 'function'
|
|
57
|
+
? defaultState
|
|
58
|
+
: () => structuredClone(defaultState);
|
|
59
|
+
this.#persistStateKey = options.persistStateKey;
|
|
60
|
+
this.#persistenceEnabled = options.persistenceEnabled ?? false;
|
|
61
|
+
this.#persistenceTimeoutMillis = options.persistenceTimeoutMillis ?? DEFAULT_PERSISTENCE_TIMEOUT_MILLIS;
|
|
62
|
+
this.#configuration = options.configuration;
|
|
63
|
+
this.#keyValueStore = options.keyValueStore ?? null;
|
|
64
|
+
this.#log = options.logger ?? serviceLocator.getLogger().child({ prefix: 'RecoverableState' });
|
|
65
|
+
this.#serialize = this.#toConversion(options.serialize);
|
|
66
|
+
this.#deserialize = this.#toConversion(options.deserialize);
|
|
67
|
+
// A pending open() may reject before anything here awaits it. Observe the rejection so it surfaces on
|
|
68
|
+
// first use rather than as an unhandled rejection - most immediately when persistence is disabled and
|
|
69
|
+
// nothing ever awaits the store.
|
|
70
|
+
if (this.#keyValueStore !== null) {
|
|
71
|
+
Promise.resolve(this.#keyValueStore).then(undefined, () => { });
|
|
72
|
+
}
|
|
73
|
+
// The automatic persists, where a rejection has nowhere useful to go - the event manager does not catch
|
|
74
|
+
// listener errors, and throwing from teardown would bury the outcome of the work it cleans up after.
|
|
75
|
+
this.#persistStateQuietly = async (eventData) => this.persistState(eventData).catch((error) => this.#log.warning(`Failed to persist the state under key '${this.#persistStateKey}'.`, { error }));
|
|
76
|
+
}
|
|
77
|
+
/** Normalizes a conversion option into a function. Absent conversions pass the value through unchanged. */
|
|
78
|
+
#toConversion(conversion) {
|
|
79
|
+
if (conversion === undefined) {
|
|
80
|
+
return async (value) => value;
|
|
81
|
+
}
|
|
82
|
+
if (typeof conversion === 'function') {
|
|
83
|
+
return async (value) => conversion(value);
|
|
84
|
+
}
|
|
85
|
+
return async (value) => {
|
|
86
|
+
const result = await conversion['~standard'].validate(value);
|
|
87
|
+
if (result.issues) {
|
|
88
|
+
throw new StateValidationError(this.#persistStateKey, result.issues);
|
|
89
|
+
}
|
|
90
|
+
return result.value;
|
|
91
|
+
};
|
|
41
92
|
}
|
|
42
93
|
/**
|
|
43
94
|
* Initialize the recoverable state.
|
|
44
95
|
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
96
|
+
* If persistence is enabled, this method loads the saved state and registers the object to listen for
|
|
97
|
+
* PERSIST_STATE events. A state established beforehand by {@link RecoverableState.reset} survives if there
|
|
98
|
+
* is no record to restore.
|
|
99
|
+
*
|
|
100
|
+
* Calling this again after a {@link RecoverableState.teardown} starts a new persistence window - the
|
|
101
|
+
* listener is registered again. The record is not reloaded: the in-memory state is what the teardown wrote, and
|
|
102
|
+
* reloading it would only drop whatever the deserialization leaves out.
|
|
47
103
|
*
|
|
48
104
|
* @returns The loaded state object
|
|
49
105
|
*/
|
|
50
106
|
async initialize() {
|
|
51
|
-
if (this
|
|
107
|
+
if (this.#initialized) {
|
|
52
108
|
return this.currentValue;
|
|
53
109
|
}
|
|
54
|
-
if (
|
|
55
|
-
|
|
56
|
-
|
|
110
|
+
if (this.#persistenceEnabled) {
|
|
111
|
+
await this.#openKeyValueStore();
|
|
112
|
+
serviceLocator.getEventManager().on(EventType.PERSIST_STATE, this.#persistStateQuietly);
|
|
113
|
+
this.#listening = true;
|
|
114
|
+
}
|
|
115
|
+
// Flipped before the record is loaded, so that a caller catching a `StateValidationError` is left with a
|
|
116
|
+
// fully wired object running on the default state rather than a half-initialized one.
|
|
117
|
+
this.#initialized = true;
|
|
118
|
+
this.#state ??= this.#defaultState();
|
|
119
|
+
if (!this.#recordLoaded) {
|
|
120
|
+
this.#recordLoaded = true;
|
|
121
|
+
await this.#loadSavedState();
|
|
57
122
|
}
|
|
58
|
-
this.keyValueStore = await KeyValueStore.open(this.persistStateKvsName ?? this.persistStateKvsId, {
|
|
59
|
-
config: this.config,
|
|
60
|
-
});
|
|
61
|
-
await this.loadSavedState();
|
|
62
|
-
// Register for persist state events
|
|
63
|
-
const eventManager = this.config.getEventManager();
|
|
64
|
-
eventManager.on("persistState" /* EventType.PERSIST_STATE */, this.persistState);
|
|
65
123
|
return this.currentValue;
|
|
66
124
|
}
|
|
67
125
|
/**
|
|
68
126
|
* Clean up resources used by the recoverable state.
|
|
69
127
|
*
|
|
70
128
|
* If persistence is enabled, this method deregisters the object from PERSIST_STATE events
|
|
71
|
-
* and persists the current state one last time
|
|
129
|
+
* and persists the current state one last time, warning rather than throwing if that write fails - cleanup
|
|
130
|
+
* runs when the work is already done, and failing it would bury whatever the caller was doing. The in-memory
|
|
131
|
+
* state is left alone, and {@link RecoverableState.initialize} can be called again to open a new
|
|
132
|
+
* persistence window.
|
|
72
133
|
*/
|
|
73
134
|
async teardown() {
|
|
74
|
-
|
|
135
|
+
this.#initialized = false;
|
|
136
|
+
if (!this.#persistenceEnabled) {
|
|
75
137
|
return;
|
|
76
138
|
}
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
await this
|
|
139
|
+
serviceLocator.getEventManager().off(EventType.PERSIST_STATE, this.#persistStateQuietly);
|
|
140
|
+
this.#listening = false;
|
|
141
|
+
await this.#persistStateQuietly();
|
|
80
142
|
}
|
|
81
143
|
/**
|
|
82
144
|
* Get the current state.
|
|
145
|
+
*
|
|
146
|
+
* Throws until the state has been established, by either {@link RecoverableState.initialize} or the
|
|
147
|
+
* synchronous {@link RecoverableState.reset} - the latter being how a caller that cannot await in its
|
|
148
|
+
* constructor gets a usable state right away.
|
|
83
149
|
*/
|
|
84
150
|
get currentValue() {
|
|
85
|
-
if (this
|
|
86
|
-
throw new Error('Recoverable state has not yet been loaded');
|
|
151
|
+
if (this.#state === null) {
|
|
152
|
+
throw new Error('Recoverable state has not yet been loaded - call initialize() or reset() first');
|
|
87
153
|
}
|
|
88
|
-
return this
|
|
154
|
+
return this.#state;
|
|
89
155
|
}
|
|
90
156
|
/**
|
|
91
|
-
* Reset the state to the default values
|
|
157
|
+
* Reset the in-memory state to the default values, leaving any persisted record alone.
|
|
92
158
|
*
|
|
93
|
-
*
|
|
94
|
-
* clears the persisted state from the KeyValueStore.
|
|
159
|
+
* Use {@link RecoverableState.resetStore} to clear the persisted record as well.
|
|
95
160
|
*/
|
|
96
|
-
|
|
97
|
-
this
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
161
|
+
reset() {
|
|
162
|
+
this.#state = this.#defaultState();
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Clear the persisted state record, leaving the in-memory state alone.
|
|
166
|
+
*
|
|
167
|
+
* This is a between-lifecycles operation - its point is to stop the next {@link RecoverableState.initialize}
|
|
168
|
+
* from restoring the record, so it throws while PERSIST_STATE events are still being handled, where the next
|
|
169
|
+
* one would write the record straight back. Use {@link RecoverableState.reset} to reset the state itself,
|
|
170
|
+
* or {@link RecoverableState.teardown} before clearing the record.
|
|
171
|
+
*
|
|
172
|
+
* A no-op if persistence is disabled.
|
|
173
|
+
*/
|
|
174
|
+
async resetStore() {
|
|
175
|
+
if (this.#listening) {
|
|
176
|
+
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.`);
|
|
103
177
|
}
|
|
178
|
+
if (!this.#persistenceEnabled) {
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
const keyValueStore = await this.#openKeyValueStore();
|
|
182
|
+
await this.#withTimeout(async () => keyValueStore.setValue(this.#persistStateKey, null), 'Clearing the persisted state');
|
|
104
183
|
}
|
|
105
184
|
/**
|
|
106
185
|
* Persist the current state to the KeyValueStore.
|
|
107
186
|
*
|
|
108
187
|
* This method is typically called in response to a PERSIST_STATE event, but can also be called
|
|
109
|
-
* directly when needed.
|
|
188
|
+
* directly when needed. It is a no-op if persistence is disabled, if no KeyValueStore is available yet, or if
|
|
189
|
+
* there is no state to write. A failed write only rejects here - the periodic and teardown ones warn instead.
|
|
110
190
|
*
|
|
111
191
|
* @param eventData Optional data associated with a PERSIST_STATE event
|
|
112
192
|
*/
|
|
113
193
|
async persistState(eventData) {
|
|
114
|
-
this
|
|
115
|
-
|
|
116
|
-
|
|
194
|
+
if (!this.#persistenceEnabled || this.#state === null) {
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
const keyValueStore = await this.#resolveKeyValueStore();
|
|
198
|
+
if (keyValueStore === null) {
|
|
199
|
+
return;
|
|
117
200
|
}
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
201
|
+
this.#log.debug(`Persisting state of the RecoverableState (eventData=${JSON.stringify(eventData)}).`);
|
|
202
|
+
const serializedState = await this.#serialize(this.currentValue);
|
|
203
|
+
await this.#withTimeout(async () => keyValueStore.setValue(this.#persistStateKey, serializedState), 'Persisting the state');
|
|
204
|
+
}
|
|
205
|
+
/** Falls back to the default store when none was supplied - persistence has to write somewhere. */
|
|
206
|
+
async #openKeyValueStore() {
|
|
207
|
+
this.#keyValueStore ??= KeyValueStore.open(null, {
|
|
208
|
+
configuration: this.#configuration ?? serviceLocator.getConfiguration(),
|
|
209
|
+
});
|
|
210
|
+
return (await this.#resolveKeyValueStore());
|
|
211
|
+
}
|
|
212
|
+
/** Awaits a store handed over as a pending `open()`, keeping the resolved instance for later calls. */
|
|
213
|
+
async #resolveKeyValueStore() {
|
|
214
|
+
if (this.#keyValueStore === null) {
|
|
215
|
+
return null;
|
|
122
216
|
}
|
|
217
|
+
this.#keyValueStore = await this.#keyValueStore;
|
|
218
|
+
return this.#keyValueStore;
|
|
123
219
|
}
|
|
124
220
|
/**
|
|
125
|
-
* Load the saved state from the KeyValueStore
|
|
221
|
+
* Load the saved state from the KeyValueStore. Leaves the current state alone if there is no record to load.
|
|
126
222
|
*/
|
|
127
|
-
async loadSavedState() {
|
|
128
|
-
if (this
|
|
129
|
-
|
|
223
|
+
async #loadSavedState() {
|
|
224
|
+
if (!this.#persistenceEnabled) {
|
|
225
|
+
return;
|
|
130
226
|
}
|
|
131
|
-
const
|
|
132
|
-
if (
|
|
133
|
-
|
|
227
|
+
const keyValueStore = await this.#resolveKeyValueStore();
|
|
228
|
+
if (keyValueStore === null) {
|
|
229
|
+
return;
|
|
134
230
|
}
|
|
135
|
-
|
|
136
|
-
|
|
231
|
+
const storedState = await this.#withTimeout(async () => keyValueStore.getValue(this.#persistStateKey), 'Loading the persisted state');
|
|
232
|
+
if (storedState === null || storedState === undefined) {
|
|
233
|
+
return;
|
|
137
234
|
}
|
|
235
|
+
this.#state = await this.#deserialize(storedState);
|
|
236
|
+
}
|
|
237
|
+
async #withTimeout(operation, description) {
|
|
238
|
+
// `@apify/timeout` shares one `AbortController` across nested frames and `KeyValueStore` checks it on
|
|
239
|
+
// every operation, so a teardown-time persist running inside an already-expired request handler timeout
|
|
240
|
+
// would be aborted before it started. Hence a fresh timeout context.
|
|
241
|
+
return timeoutStorage.exit(async () => addTimeoutToPromise(operation, this.#persistenceTimeoutMillis, `${description} under key '${this.#persistStateKey}' timed out after ${this.#persistenceTimeoutMillis / 1000} seconds.`));
|
|
138
242
|
}
|
|
139
243
|
}
|
|
140
|
-
//# sourceMappingURL=recoverable_state.js.map
|