@crawlee/core 4.0.0-beta.99 → 4.0.0-rc.0

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.
Files changed (109) hide show
  1. package/autoscaling/autoscaled_pool.d.ts +3 -21
  2. package/autoscaling/autoscaled_pool.js +105 -97
  3. package/autoscaling/concurrency_system.d.ts +7 -22
  4. package/autoscaling/concurrency_system.js +112 -100
  5. package/autoscaling/cpu_load_signal.d.ts +1 -2
  6. package/autoscaling/cpu_load_signal.js +11 -10
  7. package/autoscaling/event_loop_load_signal.d.ts +1 -4
  8. package/autoscaling/event_loop_load_signal.js +18 -18
  9. package/autoscaling/index.d.ts +1 -1
  10. package/autoscaling/index.js +1 -1
  11. package/autoscaling/load_signal.d.ts +8 -7
  12. package/autoscaling/load_signal.js +14 -12
  13. package/autoscaling/memory_load_signal.d.ts +3 -12
  14. package/autoscaling/memory_load_signal.js +41 -41
  15. package/autoscaling/snapshotter.d.ts +7 -10
  16. package/autoscaling/snapshotter.js +18 -18
  17. package/autoscaling/{client_load_signal.d.ts → storage_backend_load_signal.d.ts} +14 -17
  18. package/autoscaling/{client_load_signal.js → storage_backend_load_signal.js} +27 -27
  19. package/autoscaling/system_status.d.ts +9 -11
  20. package/autoscaling/system_status.js +13 -13
  21. package/configuration.d.ts +16 -16
  22. package/configuration.js +6 -6
  23. package/crawlers/context_pipeline.js +6 -6
  24. package/crawlers/crawler_commons.d.ts +14 -112
  25. package/crawlers/crawler_commons.js +1 -107
  26. package/crawlers/error_snapshotter.d.ts +2 -4
  27. package/crawlers/error_snapshotter.js +5 -5
  28. package/crawlers/index.d.ts +1 -1
  29. package/crawlers/index.js +0 -1
  30. package/crawlers/statistics.d.ts +164 -45
  31. package/crawlers/statistics.js +339 -153
  32. package/debug.js +4 -4
  33. package/enqueue_links/enqueue_links.d.ts +51 -159
  34. package/enqueue_links/enqueue_links.js +38 -231
  35. package/enqueue_links/shared.d.ts +34 -24
  36. package/enqueue_links/shared.js +54 -36
  37. package/errors.d.ts +43 -12
  38. package/errors.js +48 -9
  39. package/events/event_manager.d.ts +2 -2
  40. package/events/event_manager.js +7 -6
  41. package/events/local_event_manager.d.ts +1 -1
  42. package/events/local_event_manager.js +5 -5
  43. package/http.d.ts +9 -0
  44. package/http.js +28 -0
  45. package/index.d.ts +1 -1
  46. package/index.js +1 -1
  47. package/log.js +5 -1
  48. package/memory-storage/memory-storage.d.ts +3 -11
  49. package/memory-storage/memory-storage.js +42 -48
  50. package/memory-storage/resource-clients/dataset.d.ts +1 -1
  51. package/memory-storage/resource-clients/dataset.js +8 -13
  52. package/memory-storage/resource-clients/key-value-store.d.ts +1 -1
  53. package/memory-storage/resource-clients/key-value-store.js +36 -38
  54. package/memory-storage/resource-clients/request-queue.d.ts +4 -23
  55. package/memory-storage/resource-clients/request-queue.js +68 -80
  56. package/owned_or_injected.d.ts +1 -3
  57. package/owned_or_injected.js +17 -17
  58. package/package.json +8 -9
  59. package/proxy_configuration.d.ts +1 -3
  60. package/proxy_configuration.js +18 -14
  61. package/recoverable_state.d.ts +80 -45
  62. package/recoverable_state.js +163 -75
  63. package/request.d.ts +3 -4
  64. package/request.js +57 -44
  65. package/router.d.ts +6 -9
  66. package/router.js +23 -23
  67. package/serialization.js +14 -13
  68. package/service_locator.d.ts +19 -10
  69. package/service_locator.js +57 -48
  70. package/session_pool/session.d.ts +3 -14
  71. package/session_pool/session.js +76 -74
  72. package/session_pool/session_pool.d.ts +6 -12
  73. package/session_pool/session_pool.js +85 -77
  74. package/storages/batched_adds.d.ts +37 -0
  75. package/storages/batched_adds.js +73 -0
  76. package/storages/dataset.d.ts +12 -1
  77. package/storages/dataset.js +133 -32
  78. package/storages/index.d.ts +2 -1
  79. package/storages/index.js +2 -1
  80. package/storages/key_value_store.d.ts +19 -4
  81. package/storages/key_value_store.js +204 -75
  82. package/storages/request_dedup_cache.d.ts +1 -2
  83. package/storages/request_dedup_cache.js +9 -9
  84. package/storages/request_list.d.ts +4 -23
  85. package/storages/request_list.js +103 -96
  86. package/storages/request_loader.d.ts +5 -0
  87. package/storages/request_manager_tandem.d.ts +1 -10
  88. package/storages/request_manager_tandem.js +27 -27
  89. package/storages/request_queue.d.ts +21 -18
  90. package/storages/request_queue.js +318 -177
  91. package/storages/sitemap_request_loader.d.ts +22 -70
  92. package/storages/sitemap_request_loader.js +122 -116
  93. package/storages/storage_instance_manager.d.ts +1 -2
  94. package/storages/storage_instance_manager.js +17 -17
  95. package/storages/storage_stats.d.ts +1 -1
  96. package/storages/storage_stats.js +4 -4
  97. package/storages/throttling_request_manager.d.ts +239 -0
  98. package/storages/throttling_request_manager.js +646 -0
  99. package/storages/transaction.d.ts +252 -0
  100. package/storages/transaction.js +251 -0
  101. package/storages/utils.d.ts +6 -3
  102. package/storages/utils.js +11 -2
  103. package/system-info/runtime.js +7 -7
  104. package/url.d.ts +9 -0
  105. package/url.js +11 -0
  106. package/validators.d.ts +22 -25
  107. package/validators.js +13 -25
  108. package/storages/access_checking.d.ts +0 -12
  109. package/storages/access_checking.js +0 -17
@@ -1,4 +1,31 @@
1
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;
2
29
  export interface RecoverableStatePersistenceOptions {
3
30
  /**
4
31
  * The key under which the state is stored in the KeyValueStore
@@ -9,44 +36,45 @@ export interface RecoverableStatePersistenceOptions {
9
36
  */
10
37
  persistenceEnabled?: boolean;
11
38
  /**
12
- * The name of the KeyValueStore to use for persistence.
13
- * If neither a name nor an id are supplied, the default store will be used.
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.
14
41
  */
15
- persistStateKvsName?: string;
42
+ keyValueStore?: KeyValueStore | PromiseLike<KeyValueStore>;
16
43
  /**
17
- * The identifier of the KeyValueStore to use for persistence.
18
- * If neither a name nor an id are supplied, the default store will be used.
44
+ * Time limit for a single load or save of the state, in milliseconds.
45
+ * @default 60_000
19
46
  */
20
- persistStateKvsId?: string;
47
+ persistenceTimeoutMillis?: number;
21
48
  }
22
49
  /**
23
50
  * Options for configuring the RecoverableState
24
51
  */
25
- export interface RecoverableStateOptions<TStateModel = Record<string, unknown>> extends RecoverableStatePersistenceOptions {
52
+ export interface RecoverableStateOptions<TStateModel = Record<string, unknown>, TPersistedState = TStateModel> extends RecoverableStatePersistenceOptions {
26
53
  /**
27
- * The default state used if no persisted state is found.
28
- * A deep copy is made each time the state is used.
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.
29
58
  */
30
- defaultState: TStateModel;
59
+ defaultState: TStateModel | (() => TStateModel);
31
60
  /**
32
61
  * A logger instance for logging operations related to state persistence
33
62
  */
34
63
  logger?: CrawleeLogger;
35
64
  /**
36
- * Configuration instance to use
65
+ * Configuration instance to use when opening the KeyValueStore
37
66
  */
38
67
  configuration?: Configuration;
39
68
  /**
40
- * Optional function to transform the state to a JSON string before persistence.
41
- * If not provided, JSON.stringify will be used.
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.
42
71
  */
43
- serialize?: (state: TStateModel) => string;
72
+ serialize?: StateConversion<TStateModel, TPersistedState>;
44
73
  /**
45
- * Optional function to transform a JSON-serialized object back to the state model.
46
- * If not provided, JSON.parse is used.
47
- * 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.
48
76
  */
49
- deserialize?: (serializedState: string) => TStateModel;
77
+ deserialize?: StateConversion<TPersistedState, TStateModel>;
50
78
  }
51
79
  /**
52
80
  * A class for managing persistent recoverable state using a plain JavaScript object.
@@ -58,28 +86,23 @@ export interface RecoverableStateOptions<TStateModel = Record<string, unknown>>
58
86
  * The state is represented by a plain JavaScript object that can be serialized to and deserialized from JSON.
59
87
  * The class automatically hooks into the event system to persist state when needed.
60
88
  */
61
- export declare class RecoverableState<TStateModel = Record<string, unknown>> {
62
- private readonly defaultState;
63
- private state;
64
- private readonly persistenceEnabled;
65
- private readonly persistStateKey;
66
- private readonly persistStateKvsName?;
67
- private readonly persistStateKvsId?;
68
- private keyValueStore;
69
- private readonly log;
70
- private readonly serialize;
71
- private readonly deserialize;
89
+ export declare class RecoverableState<TStateModel = Record<string, unknown>, TPersistedState = TStateModel> {
90
+ #private;
72
91
  /**
73
92
  * Initialize a new recoverable state object.
74
93
  *
75
94
  * @param options Configuration options for the recoverable state
76
95
  */
77
- constructor(options: RecoverableStateOptions<TStateModel>);
96
+ constructor(options: RecoverableStateOptions<TStateModel, TPersistedState>);
78
97
  /**
79
98
  * Initialize the recoverable state.
80
99
  *
81
- * This method must be called before using the recoverable state. It loads the saved state
82
- * if persistence is enabled and registers the object to listen for PERSIST_STATE events.
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 and the record reloaded.
83
106
  *
84
107
  * @returns The loaded state object
85
108
  */
@@ -88,33 +111,45 @@ export declare class RecoverableState<TStateModel = Record<string, unknown>> {
88
111
  * Clean up resources used by the recoverable state.
89
112
  *
90
113
  * If persistence is enabled, this method deregisters the object from PERSIST_STATE events
91
- * and persists the current state one last time.
114
+ * and persists the current state one last time, warning rather than throwing if that write fails - cleanup
115
+ * runs when the work is already done, and failing it would bury whatever the caller was doing. The in-memory
116
+ * state is left alone, and {@link RecoverableState.initialize} can be called again to open a new
117
+ * persistence window.
92
118
  */
93
119
  teardown(): Promise<void>;
94
120
  /**
95
121
  * Get the current state.
122
+ *
123
+ * Throws until the state has been established, by either {@link RecoverableState.initialize} or the
124
+ * synchronous {@link RecoverableState.reset} - the latter being how a caller that cannot await in its
125
+ * constructor gets a usable state right away.
96
126
  */
97
127
  get currentValue(): TStateModel;
98
128
  /**
99
- * Reset the state to the default values and clear any persisted state.
129
+ * Reset the in-memory state to the default values, leaving any persisted record alone.
100
130
  *
101
- * Resets the current state to the default state and, if persistence is enabled,
102
- * clears the persisted state from the KeyValueStore.
131
+ * Use {@link RecoverableState.resetStore} to clear the persisted record as well.
103
132
  */
104
- reset(): Promise<void>;
133
+ reset(): void;
134
+ /**
135
+ * Clear the persisted state record, leaving the in-memory state alone.
136
+ *
137
+ * This is a between-lifecycles operation - its point is to stop the next {@link RecoverableState.initialize}
138
+ * from restoring the record, so it throws while PERSIST_STATE events are still being handled, where the next
139
+ * one would write the record straight back. Use {@link RecoverableState.reset} to reset the state itself,
140
+ * or {@link RecoverableState.teardown} before clearing the record.
141
+ *
142
+ * A no-op if persistence is disabled or no KeyValueStore is available yet.
143
+ */
144
+ resetStore(): Promise<void>;
105
145
  /**
106
146
  * Persist the current state to the KeyValueStore.
107
147
  *
108
148
  * This method is typically called in response to a PERSIST_STATE event, but can also be called
109
- * directly when needed.
149
+ * directly when needed. It is a no-op if persistence is disabled, if no KeyValueStore is available yet, or if
150
+ * there is no state to write. A failed write only rejects here - the periodic and teardown ones warn instead.
110
151
  *
111
152
  * @param eventData Optional data associated with a PERSIST_STATE event
112
153
  */
113
- persistState(eventData?: {
114
- isMigrating: boolean;
115
- }): Promise<void>;
116
- /**
117
- * Load the saved state from the KeyValueStore
118
- */
119
- private loadSavedState;
154
+ persistState(eventData?: Record<string, unknown>): Promise<void>;
120
155
  }
@@ -1,4 +1,25 @@
1
- import { KeyValueStore, serviceLocator } from '@crawlee/core';
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
+ }
2
23
  /**
3
24
  * A class for managing persistent recoverable state using a plain JavaScript object.
4
25
  *
@@ -10,134 +31,201 @@ import { KeyValueStore, serviceLocator } from '@crawlee/core';
10
31
  * The class automatically hooks into the event system to persist state when needed.
11
32
  */
12
33
  export class RecoverableState {
13
- defaultState;
14
- state = null;
15
- persistenceEnabled;
16
- persistStateKey;
17
- persistStateKvsName;
18
- persistStateKvsId;
19
- keyValueStore = null;
20
- log;
21
- serialize;
22
- deserialize;
34
+ #defaultState;
35
+ #state = null;
36
+ #initialized = false;
37
+ #listening = false;
38
+ #persistenceEnabled;
39
+ #persistStateKey;
40
+ #persistenceTimeoutMillis;
41
+ #configuration;
42
+ #keyValueStore;
43
+ #log;
44
+ #serialize;
45
+ #deserialize;
46
+ #persistStateQuietly;
23
47
  /**
24
48
  * Initialize a new recoverable state object.
25
49
  *
26
50
  * @param options Configuration options for the recoverable state
27
51
  */
28
52
  constructor(options) {
29
- this.defaultState = options.defaultState;
30
- this.persistStateKey = options.persistStateKey;
31
- this.persistenceEnabled = options.persistenceEnabled ?? false;
32
- this.persistStateKvsName = options.persistStateKvsName;
33
- this.persistStateKvsId = options.persistStateKvsId;
34
- this.log = options.logger ?? serviceLocator.getLogger().child({ prefix: 'RecoverableState' });
35
- this.serialize = options.serialize ?? JSON.stringify;
36
- this.deserialize = options.deserialize ?? JSON.parse;
37
- this.persistState = this.persistState.bind(this);
53
+ const { defaultState } = options;
54
+ this.#defaultState =
55
+ typeof defaultState === 'function'
56
+ ? defaultState
57
+ : () => structuredClone(defaultState);
58
+ this.#persistStateKey = options.persistStateKey;
59
+ this.#persistenceEnabled = options.persistenceEnabled ?? false;
60
+ this.#persistenceTimeoutMillis = options.persistenceTimeoutMillis ?? DEFAULT_PERSISTENCE_TIMEOUT_MILLIS;
61
+ this.#configuration = options.configuration;
62
+ this.#keyValueStore = options.keyValueStore ?? null;
63
+ this.#log = options.logger ?? serviceLocator.getLogger().child({ prefix: 'RecoverableState' });
64
+ this.#serialize = this.#toConversion(options.serialize);
65
+ this.#deserialize = this.#toConversion(options.deserialize);
66
+ // The automatic persists, where a rejection has nowhere useful to go - the event manager does not catch
67
+ // listener errors, and throwing from teardown would bury the outcome of the work it cleans up after.
68
+ this.#persistStateQuietly = async (eventData) => this.persistState(eventData).catch((error) => this.#log.warning(`Failed to persist the state under key '${this.#persistStateKey}'.`, { error }));
69
+ }
70
+ /** Normalizes a conversion option into a function. Absent conversions pass the value through unchanged. */
71
+ #toConversion(conversion) {
72
+ if (conversion === undefined) {
73
+ return async (value) => value;
74
+ }
75
+ if (typeof conversion === 'function') {
76
+ return async (value) => conversion(value);
77
+ }
78
+ return async (value) => {
79
+ const result = await conversion['~standard'].validate(value);
80
+ if (result.issues) {
81
+ throw new StateValidationError(this.#persistStateKey, result.issues);
82
+ }
83
+ return result.value;
84
+ };
38
85
  }
39
86
  /**
40
87
  * Initialize the recoverable state.
41
88
  *
42
- * This method must be called before using the recoverable state. It loads the saved state
43
- * if persistence is enabled and registers the object to listen for PERSIST_STATE events.
89
+ * If persistence is enabled, this method loads the saved state and registers the object to listen for
90
+ * PERSIST_STATE events. A state established beforehand by {@link RecoverableState.reset} survives if there
91
+ * is no record to restore.
92
+ *
93
+ * Calling this again after a {@link RecoverableState.teardown} starts a new persistence window - the
94
+ * listener is registered again and the record reloaded.
44
95
  *
45
96
  * @returns The loaded state object
46
97
  */
47
98
  async initialize() {
48
- if (this.state !== null && this.state !== undefined) {
99
+ if (this.#initialized) {
49
100
  return this.currentValue;
50
101
  }
51
- if (!this.persistenceEnabled) {
52
- this.state = this.deserialize(this.serialize(this.defaultState));
53
- return this.currentValue;
54
- }
55
- let kvsIdentifier = null;
56
- if (this.persistStateKvsName) {
57
- kvsIdentifier = { name: this.persistStateKvsName };
58
- }
59
- else if (this.persistStateKvsId) {
60
- kvsIdentifier = { id: this.persistStateKvsId };
102
+ if (this.#persistenceEnabled) {
103
+ this.#keyValueStore ??= KeyValueStore.open(null, {
104
+ configuration: this.#configuration ?? serviceLocator.getConfiguration(),
105
+ });
106
+ await this.#resolveKeyValueStore();
107
+ serviceLocator.getEventManager().on(EventType.PERSIST_STATE, this.#persistStateQuietly);
108
+ this.#listening = true;
61
109
  }
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);
110
+ // Flipped before the record is loaded, so that a caller catching a `StateValidationError` is left with a
111
+ // fully wired object running on the default state rather than a half-initialized one.
112
+ this.#initialized = true;
113
+ this.#state ??= this.#defaultState();
114
+ await this.#loadSavedState();
69
115
  return this.currentValue;
70
116
  }
71
117
  /**
72
118
  * Clean up resources used by the recoverable state.
73
119
  *
74
120
  * If persistence is enabled, this method deregisters the object from PERSIST_STATE events
75
- * and persists the current state one last time.
121
+ * and persists the current state one last time, warning rather than throwing if that write fails - cleanup
122
+ * runs when the work is already done, and failing it would bury whatever the caller was doing. The in-memory
123
+ * state is left alone, and {@link RecoverableState.initialize} can be called again to open a new
124
+ * persistence window.
76
125
  */
77
126
  async teardown() {
78
- if (!this.persistenceEnabled || !this.persistState) {
127
+ this.#initialized = false;
128
+ if (!this.#persistenceEnabled) {
79
129
  return;
80
130
  }
81
- const eventManager = serviceLocator.getEventManager();
82
- eventManager.off("persistState" /* EventType.PERSIST_STATE */, this.persistState);
83
- await this.persistState();
131
+ serviceLocator.getEventManager().off(EventType.PERSIST_STATE, this.#persistStateQuietly);
132
+ this.#listening = false;
133
+ await this.#persistStateQuietly();
84
134
  }
85
135
  /**
86
136
  * Get the current state.
137
+ *
138
+ * Throws until the state has been established, by either {@link RecoverableState.initialize} or the
139
+ * synchronous {@link RecoverableState.reset} - the latter being how a caller that cannot await in its
140
+ * constructor gets a usable state right away.
87
141
  */
88
142
  get currentValue() {
89
- if (this.state === null) {
90
- throw new Error('Recoverable state has not yet been loaded');
143
+ if (this.#state === null) {
144
+ throw new Error('Recoverable state has not yet been loaded - call initialize() or reset() first');
91
145
  }
92
- return this.state;
146
+ return this.#state;
93
147
  }
94
148
  /**
95
- * Reset the state to the default values and clear any persisted state.
149
+ * Reset the in-memory state to the default values, leaving any persisted record alone.
96
150
  *
97
- * Resets the current state to the default state and, if persistence is enabled,
98
- * clears the persisted state from the KeyValueStore.
151
+ * Use {@link RecoverableState.resetStore} to clear the persisted record as well.
99
152
  */
100
- async reset() {
101
- this.state = this.deserialize(this.serialize(this.defaultState));
102
- if (this.persistenceEnabled) {
103
- if (this.keyValueStore === null) {
104
- throw new Error('Recoverable state has not yet been initialized');
105
- }
106
- await this.keyValueStore.setValue(this.persistStateKey, null);
153
+ reset() {
154
+ this.#state = this.#defaultState();
155
+ }
156
+ /**
157
+ * Clear the persisted state record, leaving the in-memory state alone.
158
+ *
159
+ * This is a between-lifecycles operation - its point is to stop the next {@link RecoverableState.initialize}
160
+ * from restoring the record, so it throws while PERSIST_STATE events are still being handled, where the next
161
+ * one would write the record straight back. Use {@link RecoverableState.reset} to reset the state itself,
162
+ * or {@link RecoverableState.teardown} before clearing the record.
163
+ *
164
+ * A no-op if persistence is disabled or no KeyValueStore is available yet.
165
+ */
166
+ async resetStore() {
167
+ if (this.#listening) {
168
+ 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.`);
169
+ }
170
+ if (!this.#persistenceEnabled) {
171
+ return;
172
+ }
173
+ const keyValueStore = await this.#resolveKeyValueStore();
174
+ if (keyValueStore === null) {
175
+ return;
107
176
  }
177
+ await this.#withTimeout(async () => keyValueStore.setValue(this.#persistStateKey, null), 'Clearing the persisted state');
108
178
  }
109
179
  /**
110
180
  * Persist the current state to the KeyValueStore.
111
181
  *
112
182
  * This method is typically called in response to a PERSIST_STATE event, but can also be called
113
- * directly when needed.
183
+ * directly when needed. It is a no-op if persistence is disabled, if no KeyValueStore is available yet, or if
184
+ * there is no state to write. A failed write only rejects here - the periodic and teardown ones warn instead.
114
185
  *
115
186
  * @param eventData Optional data associated with a PERSIST_STATE event
116
187
  */
117
188
  async persistState(eventData) {
118
- this.log.debug(`Persisting state of the RecoverableState (eventData=${JSON.stringify(eventData)}).`);
119
- if (this.keyValueStore === null || this.state === null) {
120
- throw new Error('Recoverable state has not yet been initialized');
189
+ if (!this.#persistenceEnabled || this.#state === null) {
190
+ return;
121
191
  }
122
- if (this.persistenceEnabled) {
123
- await this.keyValueStore.setValue(this.persistStateKey, this.serialize(this.state), {
124
- contentType: 'text/plain', // HACK - the result is expected to be JSON, but we do this to avoid the implicit JSON.parse in `KeyValueStore.getValue`
125
- });
192
+ const keyValueStore = await this.#resolveKeyValueStore();
193
+ if (keyValueStore === null) {
194
+ return;
195
+ }
196
+ this.#log.debug(`Persisting state of the RecoverableState (eventData=${JSON.stringify(eventData)}).`);
197
+ const serializedState = await this.#serialize(this.currentValue);
198
+ await this.#withTimeout(async () => keyValueStore.setValue(this.#persistStateKey, serializedState), 'Persisting the state');
199
+ }
200
+ /** Awaits a store handed over as a pending `open()`, keeping the resolved instance for later calls. */
201
+ async #resolveKeyValueStore() {
202
+ if (this.#keyValueStore === null) {
203
+ return null;
126
204
  }
205
+ this.#keyValueStore = await this.#keyValueStore;
206
+ return this.#keyValueStore;
127
207
  }
128
208
  /**
129
- * Load the saved state from the KeyValueStore
209
+ * Load the saved state from the KeyValueStore. Leaves the current state alone if there is no record to load.
130
210
  */
131
- async loadSavedState() {
132
- if (this.keyValueStore === null) {
133
- throw new Error('Recoverable state has not yet been initialized');
211
+ async #loadSavedState() {
212
+ if (!this.#persistenceEnabled) {
213
+ return;
134
214
  }
135
- const storedState = await this.keyValueStore.getValue(this.persistStateKey);
136
- if (storedState === null || storedState === undefined) {
137
- this.state = this.deserialize(this.serialize(this.defaultState));
215
+ const keyValueStore = await this.#resolveKeyValueStore();
216
+ if (keyValueStore === null) {
217
+ return;
138
218
  }
139
- else {
140
- this.state = this.deserialize(storedState);
219
+ const storedState = await this.#withTimeout(async () => keyValueStore.getValue(this.#persistStateKey), 'Loading the persisted state');
220
+ if (storedState === null || storedState === undefined) {
221
+ return;
141
222
  }
223
+ this.#state = await this.#deserialize(storedState);
224
+ }
225
+ async #withTimeout(operation, description) {
226
+ // `@apify/timeout` shares one `AbortController` across nested frames and `KeyValueStore` checks it on
227
+ // every operation, so a teardown-time persist running inside an already-expired request handler timeout
228
+ // would be aborted before it started. Hence a fresh timeout context.
229
+ return timeoutStorage.exit(async () => addTimeoutToPromise(operation, this.#persistenceTimeoutMillis, `${description} under key '${this.#persistStateKey}' timed out after ${this.#persistenceTimeoutMillis / 1000} seconds.`));
142
230
  }
143
231
  }
package/request.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { BinaryLike } from 'node:crypto';
2
2
  import type { AllowedHttpMethods, Dictionary } from '@crawlee/types';
3
- import type { EnqueueLinksOptions } from './enqueue_links/enqueue_links.js';
3
+ import type { EnqueueStrategyOption } from './enqueue_links/enqueue_links.js';
4
4
  import type { SkippedRequestReason } from './enqueue_links/shared.js';
5
5
  export declare enum RequestState {
6
6
  UNPROCESSED = 0,
@@ -44,6 +44,7 @@ export declare enum RequestState {
44
44
  * @category Sources
45
45
  */
46
46
  declare class CrawleeRequest<UserData extends Dictionary = Dictionary> {
47
+ #private;
47
48
  /** Request ID */
48
49
  id?: string;
49
50
  /** URL of the web page to crawl. */
@@ -74,8 +75,6 @@ declare class CrawleeRequest<UserData extends Dictionary = Dictionary> {
74
75
  errorMessages: string[];
75
76
  /** Object with HTTP headers. Key is header name, value is the value. */
76
77
  headers?: Record<string, string>;
77
- /** Private store for the custom user data assigned to the request. */
78
- private _userData;
79
78
  /**
80
79
  * Custom user data assigned to the request.
81
80
  *
@@ -282,7 +281,7 @@ export interface RequestOptions<UserData extends Dictionary = Dictionary> {
282
281
  /** @internal */
283
282
  lockExpiresAt?: Date;
284
283
  /** @internal */
285
- enqueueStrategy?: EnqueueLinksOptions['strategy'];
284
+ enqueueStrategy?: EnqueueStrategyOption;
286
285
  }
287
286
  export interface PushErrorMessageOptions {
288
287
  /**