@crawlee/core 4.0.0-beta.14 → 4.0.0-beta.140

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 (287) hide show
  1. package/README.md +14 -14
  2. package/autoscaling/autoscaled_pool.d.ts +67 -172
  3. package/autoscaling/autoscaled_pool.js +182 -329
  4. package/autoscaling/concurrency_system.d.ts +269 -0
  5. package/autoscaling/concurrency_system.js +365 -0
  6. package/autoscaling/cpu_load_signal.d.ts +43 -0
  7. package/autoscaling/cpu_load_signal.js +47 -0
  8. package/autoscaling/event_loop_load_signal.d.ts +51 -0
  9. package/autoscaling/event_loop_load_signal.js +60 -0
  10. package/autoscaling/index.d.ts +6 -1
  11. package/autoscaling/index.js +6 -1
  12. package/autoscaling/load_signal.d.ts +100 -0
  13. package/autoscaling/load_signal.js +105 -0
  14. package/autoscaling/memory_load_signal.d.ts +47 -0
  15. package/autoscaling/memory_load_signal.js +106 -0
  16. package/autoscaling/snapshotter.d.ts +58 -163
  17. package/autoscaling/snapshotter.js +45 -263
  18. package/autoscaling/storage_backend_load_signal.d.ts +56 -0
  19. package/autoscaling/storage_backend_load_signal.js +73 -0
  20. package/autoscaling/system_status.d.ts +67 -89
  21. package/autoscaling/system_status.js +92 -122
  22. package/autoscaling/weighted_avg.d.ts +5 -0
  23. package/autoscaling/weighted_avg.js +14 -0
  24. package/byte_utils.d.ts +17 -0
  25. package/byte_utils.js +42 -0
  26. package/configuration.d.ts +96 -223
  27. package/configuration.js +170 -222
  28. package/cookie_utils.d.ts +3 -2
  29. package/cookie_utils.js +18 -7
  30. package/crawlers/context_pipeline.d.ts +10 -1
  31. package/crawlers/context_pipeline.js +31 -8
  32. package/crawlers/crawler_commons.d.ts +90 -126
  33. package/crawlers/crawler_commons.js +1 -108
  34. package/crawlers/error_snapshotter.d.ts +2 -5
  35. package/crawlers/error_snapshotter.js +7 -8
  36. package/crawlers/error_tracker.d.ts +0 -1
  37. package/crawlers/error_tracker.js +0 -1
  38. package/crawlers/index.d.ts +1 -3
  39. package/crawlers/index.js +0 -3
  40. package/crawlers/internals/types.d.ts +0 -1
  41. package/crawlers/internals/types.js +0 -1
  42. package/crawlers/statistics.d.ts +187 -63
  43. package/crawlers/statistics.js +354 -164
  44. package/debug.d.ts +36 -0
  45. package/debug.js +70 -0
  46. package/enqueue_links/enqueue_links.d.ts +60 -153
  47. package/enqueue_links/enqueue_links.js +38 -229
  48. package/enqueue_links/index.d.ts +0 -1
  49. package/enqueue_links/index.js +0 -1
  50. package/enqueue_links/shared.d.ts +49 -30
  51. package/enqueue_links/shared.js +94 -68
  52. package/errors.d.ts +72 -4
  53. package/errors.js +89 -5
  54. package/events/event_manager.d.ts +35 -9
  55. package/events/event_manager.js +12 -13
  56. package/events/index.d.ts +0 -1
  57. package/events/index.js +0 -1
  58. package/events/local_event_manager.d.ts +15 -3
  59. package/events/local_event_manager.js +39 -13
  60. package/http.d.ts +9 -0
  61. package/http.js +28 -0
  62. package/index.d.ts +7 -5
  63. package/index.js +8 -4
  64. package/iterables.d.ts +79 -0
  65. package/iterables.js +134 -0
  66. package/log.d.ts +78 -1
  67. package/log.js +106 -1
  68. package/memory-storage/consts.d.ts +4 -0
  69. package/memory-storage/consts.js +4 -0
  70. package/memory-storage/index.d.ts +1 -0
  71. package/memory-storage/index.js +1 -0
  72. package/memory-storage/memory-storage.d.ts +44 -0
  73. package/memory-storage/memory-storage.js +160 -0
  74. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  75. package/memory-storage/resource-clients/common/base-client.js +6 -0
  76. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  77. package/memory-storage/resource-clients/dataset.js +106 -0
  78. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  79. package/memory-storage/resource-clients/key-value-store.js +199 -0
  80. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  81. package/memory-storage/resource-clients/request-queue.js +407 -0
  82. package/memory-storage/utils.d.ts +16 -0
  83. package/memory-storage/utils.js +41 -0
  84. package/owned_or_injected.d.ts +58 -0
  85. package/owned_or_injected.js +98 -0
  86. package/package.json +13 -12
  87. package/proxy_configuration.d.ts +22 -128
  88. package/proxy_configuration.js +32 -144
  89. package/recoverable_state.d.ts +83 -51
  90. package/recoverable_state.js +163 -72
  91. package/request.d.ts +57 -16
  92. package/request.js +130 -69
  93. package/router.d.ts +193 -21
  94. package/router.js +188 -43
  95. package/serialization.d.ts +0 -1
  96. package/serialization.js +15 -15
  97. package/service_locator.d.ts +165 -0
  98. package/service_locator.js +253 -0
  99. package/session_pool/consts.d.ts +1 -2
  100. package/session_pool/consts.js +1 -2
  101. package/session_pool/errors.d.ts +0 -1
  102. package/session_pool/errors.js +0 -1
  103. package/session_pool/fingerprint.d.ts +9 -0
  104. package/session_pool/fingerprint.js +30 -0
  105. package/session_pool/index.d.ts +0 -2
  106. package/session_pool/index.js +0 -2
  107. package/session_pool/session.d.ts +35 -88
  108. package/session_pool/session.js +101 -159
  109. package/session_pool/session_pool.d.ts +74 -91
  110. package/session_pool/session_pool.js +175 -165
  111. package/storages/batched_adds.d.ts +37 -0
  112. package/storages/batched_adds.js +73 -0
  113. package/storages/dataset.d.ts +109 -56
  114. package/storages/dataset.js +283 -149
  115. package/storages/index.d.ts +9 -9
  116. package/storages/index.js +7 -9
  117. package/storages/key_value_store.d.ts +183 -48
  118. package/storages/key_value_store.js +445 -171
  119. package/storages/key_value_store_codec.d.ts +32 -0
  120. package/storages/key_value_store_codec.js +113 -0
  121. package/storages/request_dedup_cache.d.ts +22 -0
  122. package/storages/request_dedup_cache.js +48 -0
  123. package/storages/request_list.d.ts +52 -109
  124. package/storages/request_list.js +183 -152
  125. package/storages/request_loader.d.ts +101 -0
  126. package/storages/request_loader.js +1 -0
  127. package/storages/request_manager.d.ts +33 -0
  128. package/storages/request_manager.js +1 -0
  129. package/storages/request_manager_tandem.d.ts +48 -19
  130. package/storages/request_manager_tandem.js +118 -45
  131. package/storages/request_queue.d.ts +290 -47
  132. package/storages/request_queue.js +762 -216
  133. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +45 -89
  134. package/storages/sitemap_request_loader.js +438 -0
  135. package/storages/storage_instance_manager.d.ts +87 -0
  136. package/storages/storage_instance_manager.js +256 -0
  137. package/storages/storage_stats.d.ts +48 -0
  138. package/storages/storage_stats.js +29 -0
  139. package/storages/throttling_request_manager.d.ts +239 -0
  140. package/storages/throttling_request_manager.js +646 -0
  141. package/storages/transaction.d.ts +252 -0
  142. package/storages/transaction.js +251 -0
  143. package/storages/utils.d.ts +59 -11
  144. package/storages/utils.js +75 -15
  145. package/system-info/cpu-info.d.ts +67 -0
  146. package/system-info/cpu-info.js +216 -0
  147. package/system-info/memory-info.d.ts +31 -0
  148. package/system-info/memory-info.js +115 -0
  149. package/system-info/ps-tree.d.ts +17 -0
  150. package/system-info/ps-tree.js +144 -0
  151. package/system-info/runtime.d.ts +14 -0
  152. package/system-info/runtime.js +80 -0
  153. package/typedefs.d.ts +0 -6
  154. package/typedefs.js +0 -1
  155. package/url.d.ts +9 -0
  156. package/url.js +11 -0
  157. package/validators.d.ts +22 -18
  158. package/validators.js +13 -18
  159. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  160. package/autoscaling/autoscaled_pool.js.map +0 -1
  161. package/autoscaling/index.d.ts.map +0 -1
  162. package/autoscaling/index.js.map +0 -1
  163. package/autoscaling/snapshotter.d.ts.map +0 -1
  164. package/autoscaling/snapshotter.js.map +0 -1
  165. package/autoscaling/system_status.d.ts.map +0 -1
  166. package/autoscaling/system_status.js.map +0 -1
  167. package/configuration.d.ts.map +0 -1
  168. package/configuration.js.map +0 -1
  169. package/cookie_utils.d.ts.map +0 -1
  170. package/cookie_utils.js.map +0 -1
  171. package/crawlers/context_pipeline.d.ts.map +0 -1
  172. package/crawlers/context_pipeline.js.map +0 -1
  173. package/crawlers/crawler_commons.d.ts.map +0 -1
  174. package/crawlers/crawler_commons.js.map +0 -1
  175. package/crawlers/crawler_utils.d.ts +0 -10
  176. package/crawlers/crawler_utils.d.ts.map +0 -1
  177. package/crawlers/crawler_utils.js +0 -12
  178. package/crawlers/crawler_utils.js.map +0 -1
  179. package/crawlers/error_snapshotter.d.ts.map +0 -1
  180. package/crawlers/error_snapshotter.js.map +0 -1
  181. package/crawlers/error_tracker.d.ts.map +0 -1
  182. package/crawlers/error_tracker.js.map +0 -1
  183. package/crawlers/index.d.ts.map +0 -1
  184. package/crawlers/index.js.map +0 -1
  185. package/crawlers/internals/types.d.ts.map +0 -1
  186. package/crawlers/internals/types.js.map +0 -1
  187. package/crawlers/statistics.d.ts.map +0 -1
  188. package/crawlers/statistics.js.map +0 -1
  189. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  190. package/enqueue_links/enqueue_links.js.map +0 -1
  191. package/enqueue_links/index.d.ts.map +0 -1
  192. package/enqueue_links/index.js.map +0 -1
  193. package/enqueue_links/shared.d.ts.map +0 -1
  194. package/enqueue_links/shared.js.map +0 -1
  195. package/errors.d.ts.map +0 -1
  196. package/errors.js.map +0 -1
  197. package/events/event_manager.d.ts.map +0 -1
  198. package/events/event_manager.js.map +0 -1
  199. package/events/index.d.ts.map +0 -1
  200. package/events/index.js.map +0 -1
  201. package/events/local_event_manager.d.ts.map +0 -1
  202. package/events/local_event_manager.js.map +0 -1
  203. package/http_clients/base-http-client.d.ts +0 -140
  204. package/http_clients/base-http-client.d.ts.map +0 -1
  205. package/http_clients/base-http-client.js +0 -40
  206. package/http_clients/base-http-client.js.map +0 -1
  207. package/http_clients/form-data-like.d.ts +0 -67
  208. package/http_clients/form-data-like.d.ts.map +0 -1
  209. package/http_clients/form-data-like.js +0 -5
  210. package/http_clients/form-data-like.js.map +0 -1
  211. package/http_clients/got-scraping-http-client.d.ts +0 -20
  212. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  213. package/http_clients/got-scraping-http-client.js +0 -85
  214. package/http_clients/got-scraping-http-client.js.map +0 -1
  215. package/http_clients/index.d.ts +0 -3
  216. package/http_clients/index.d.ts.map +0 -1
  217. package/http_clients/index.js +0 -3
  218. package/http_clients/index.js.map +0 -1
  219. package/index.d.ts.map +0 -1
  220. package/index.js.map +0 -1
  221. package/log.d.ts.map +0 -1
  222. package/log.js.map +0 -1
  223. package/proxy_configuration.d.ts.map +0 -1
  224. package/proxy_configuration.js.map +0 -1
  225. package/recoverable_state.d.ts.map +0 -1
  226. package/recoverable_state.js.map +0 -1
  227. package/request.d.ts.map +0 -1
  228. package/request.js.map +0 -1
  229. package/router.d.ts.map +0 -1
  230. package/router.js.map +0 -1
  231. package/serialization.d.ts.map +0 -1
  232. package/serialization.js.map +0 -1
  233. package/session_pool/consts.d.ts.map +0 -1
  234. package/session_pool/consts.js.map +0 -1
  235. package/session_pool/errors.d.ts.map +0 -1
  236. package/session_pool/errors.js.map +0 -1
  237. package/session_pool/events.d.ts +0 -3
  238. package/session_pool/events.d.ts.map +0 -1
  239. package/session_pool/events.js +0 -3
  240. package/session_pool/events.js.map +0 -1
  241. package/session_pool/index.d.ts.map +0 -1
  242. package/session_pool/index.js.map +0 -1
  243. package/session_pool/session.d.ts.map +0 -1
  244. package/session_pool/session.js.map +0 -1
  245. package/session_pool/session_pool.d.ts.map +0 -1
  246. package/session_pool/session_pool.js.map +0 -1
  247. package/storages/access_checking.d.ts +0 -13
  248. package/storages/access_checking.d.ts.map +0 -1
  249. package/storages/access_checking.js +0 -14
  250. package/storages/access_checking.js.map +0 -1
  251. package/storages/dataset.d.ts.map +0 -1
  252. package/storages/dataset.js.map +0 -1
  253. package/storages/index.d.ts.map +0 -1
  254. package/storages/index.js.map +0 -1
  255. package/storages/key_value_store.d.ts.map +0 -1
  256. package/storages/key_value_store.js.map +0 -1
  257. package/storages/request_list.d.ts.map +0 -1
  258. package/storages/request_list.js.map +0 -1
  259. package/storages/request_list_adapter.d.ts +0 -58
  260. package/storages/request_list_adapter.d.ts.map +0 -1
  261. package/storages/request_list_adapter.js +0 -81
  262. package/storages/request_list_adapter.js.map +0 -1
  263. package/storages/request_manager_tandem.d.ts.map +0 -1
  264. package/storages/request_manager_tandem.js.map +0 -1
  265. package/storages/request_provider.d.ts +0 -371
  266. package/storages/request_provider.d.ts.map +0 -1
  267. package/storages/request_provider.js +0 -585
  268. package/storages/request_provider.js.map +0 -1
  269. package/storages/request_queue.d.ts.map +0 -1
  270. package/storages/request_queue.js.map +0 -1
  271. package/storages/request_queue_v2.d.ts +0 -87
  272. package/storages/request_queue_v2.d.ts.map +0 -1
  273. package/storages/request_queue_v2.js +0 -438
  274. package/storages/request_queue_v2.js.map +0 -1
  275. package/storages/sitemap_request_list.d.ts.map +0 -1
  276. package/storages/sitemap_request_list.js +0 -430
  277. package/storages/sitemap_request_list.js.map +0 -1
  278. package/storages/storage_manager.d.ts +0 -58
  279. package/storages/storage_manager.d.ts.map +0 -1
  280. package/storages/storage_manager.js +0 -105
  281. package/storages/storage_manager.js.map +0 -1
  282. package/storages/utils.d.ts.map +0 -1
  283. package/storages/utils.js.map +0 -1
  284. package/typedefs.d.ts.map +0 -1
  285. package/typedefs.js.map +0 -1
  286. package/validators.d.ts.map +0 -1
  287. package/validators.js.map +0 -1
@@ -1,5 +1,25 @@
1
- import { Configuration, KeyValueStore } from '@crawlee/core';
2
- import log from '@apify/log';
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,201 @@ 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
- persistenceEnabled;
17
- persistStateKey;
18
- persistStateKvsName;
19
- persistStateKvsId;
20
- keyValueStore = null;
21
- log;
22
- config;
23
- serialize;
24
- 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;
25
47
  /**
26
48
  * Initialize a new recoverable state object.
27
49
  *
28
50
  * @param options Configuration options for the recoverable state
29
51
  */
30
52
  constructor(options) {
31
- this.defaultState = options.defaultState;
32
- this.persistStateKey = options.persistStateKey;
33
- this.persistenceEnabled = options.persistenceEnabled ?? false;
34
- this.persistStateKvsName = options.persistStateKvsName;
35
- this.persistStateKvsId = options.persistStateKvsId;
36
- this.log = options.logger ?? log.child({ prefix: 'RecoverableState' });
37
- this.config = options.config ?? Configuration.getGlobalConfig();
38
- this.serialize = options.serialize ?? JSON.stringify;
39
- this.deserialize = options.deserialize ?? JSON.parse;
40
- 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
+ };
41
85
  }
42
86
  /**
43
87
  * Initialize the recoverable state.
44
88
  *
45
- * This method must be called before using the recoverable state. It loads the saved state
46
- * 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.
47
95
  *
48
96
  * @returns The loaded state object
49
97
  */
50
98
  async initialize() {
51
- if (this.state !== null && this.state !== undefined) {
99
+ if (this.#initialized) {
52
100
  return this.currentValue;
53
101
  }
54
- if (!this.persistenceEnabled) {
55
- this.state = this.deserialize(this.serialize(this.defaultState));
56
- return this.currentValue;
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;
57
109
  }
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);
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();
65
115
  return this.currentValue;
66
116
  }
67
117
  /**
68
118
  * Clean up resources used by the recoverable state.
69
119
  *
70
120
  * If persistence is enabled, this method deregisters the object from PERSIST_STATE events
71
- * 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.
72
125
  */
73
126
  async teardown() {
74
- if (!this.persistenceEnabled || !this.persistState) {
127
+ this.#initialized = false;
128
+ if (!this.#persistenceEnabled) {
75
129
  return;
76
130
  }
77
- const eventManager = this.config.getEventManager();
78
- eventManager.off("persistState" /* EventType.PERSIST_STATE */, this.persistState);
79
- await this.persistState();
131
+ serviceLocator.getEventManager().off(EventType.PERSIST_STATE, this.#persistStateQuietly);
132
+ this.#listening = false;
133
+ await this.#persistStateQuietly();
80
134
  }
81
135
  /**
82
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.
83
141
  */
84
142
  get currentValue() {
85
- if (this.state === null) {
86
- 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');
87
145
  }
88
- return this.state;
146
+ return this.#state;
89
147
  }
90
148
  /**
91
- * 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.
92
150
  *
93
- * Resets the current state to the default state and, if persistence is enabled,
94
- * clears the persisted state from the KeyValueStore.
151
+ * Use {@link RecoverableState.resetStore} to clear the persisted record as well.
95
152
  */
96
- async reset() {
97
- this.state = this.deserialize(this.serialize(this.defaultState));
98
- if (this.persistenceEnabled) {
99
- if (this.keyValueStore === null) {
100
- throw new Error('Recoverable state has not yet been initialized');
101
- }
102
- 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;
103
172
  }
173
+ const keyValueStore = await this.#resolveKeyValueStore();
174
+ if (keyValueStore === null) {
175
+ return;
176
+ }
177
+ await this.#withTimeout(async () => keyValueStore.setValue(this.#persistStateKey, null), 'Clearing the persisted state');
104
178
  }
105
179
  /**
106
180
  * Persist the current state to the KeyValueStore.
107
181
  *
108
182
  * This method is typically called in response to a PERSIST_STATE event, but can also be called
109
- * 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.
110
185
  *
111
186
  * @param eventData Optional data associated with a PERSIST_STATE event
112
187
  */
113
188
  async persistState(eventData) {
114
- this.log.debug(`Persisting state of the RecoverableState (eventData=${JSON.stringify(eventData)}).`);
115
- if (this.keyValueStore === null || this.state === null) {
116
- throw new Error('Recoverable state has not yet been initialized');
189
+ if (!this.#persistenceEnabled || this.#state === null) {
190
+ return;
117
191
  }
118
- if (this.persistenceEnabled) {
119
- await this.keyValueStore.setValue(this.persistStateKey, this.serialize(this.state), {
120
- contentType: 'text/plain', // HACK - the result is expected to be JSON, but we do this to avoid the implicit JSON.parse in `KeyValueStore.getValue`
121
- });
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;
122
204
  }
205
+ this.#keyValueStore = await this.#keyValueStore;
206
+ return this.#keyValueStore;
123
207
  }
124
208
  /**
125
- * 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.
126
210
  */
127
- async loadSavedState() {
128
- if (this.keyValueStore === null) {
129
- throw new Error('Recoverable state has not yet been initialized');
211
+ async #loadSavedState() {
212
+ if (!this.#persistenceEnabled) {
213
+ return;
130
214
  }
131
- const storedState = await this.keyValueStore.getValue(this.persistStateKey);
132
- if (storedState === null || storedState === undefined) {
133
- this.state = this.deserialize(this.serialize(this.defaultState));
215
+ const keyValueStore = await this.#resolveKeyValueStore();
216
+ if (keyValueStore === null) {
217
+ return;
134
218
  }
135
- else {
136
- 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;
137
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.`));
138
230
  }
139
231
  }
140
- //# sourceMappingURL=recoverable_state.js.map
package/request.d.ts CHANGED
@@ -1,8 +1,7 @@
1
1
  import type { BinaryLike } from 'node:crypto';
2
- import type { Dictionary } from '@crawlee/types';
3
- import type { EnqueueLinksOptions } from './enqueue_links/enqueue_links.js';
2
+ import type { AllowedHttpMethods, Dictionary } from '@crawlee/types';
3
+ import type { EnqueueStrategyOption } from './enqueue_links/enqueue_links.js';
4
4
  import type { SkippedRequestReason } from './enqueue_links/shared.js';
5
- import type { AllowedHttpMethods } from './typedefs.js';
6
5
  export declare enum RequestState {
7
6
  UNPROCESSED = 0,
8
7
  BEFORE_NAV = 1,
@@ -45,6 +44,7 @@ export declare enum RequestState {
45
44
  * @category Sources
46
45
  */
47
46
  declare class CrawleeRequest<UserData extends Dictionary = Dictionary> {
47
+ #private;
48
48
  /** Request ID */
49
49
  id?: string;
50
50
  /** URL of the web page to crawl. */
@@ -75,9 +75,12 @@ declare class CrawleeRequest<UserData extends Dictionary = Dictionary> {
75
75
  errorMessages: string[];
76
76
  /** Object with HTTP headers. Key is header name, value is the value. */
77
77
  headers?: Record<string, string>;
78
- /** Private store for the custom user data assigned to the request. */
79
- private _userData;
80
- /** Custom user data assigned to the request. */
78
+ /**
79
+ * Custom user data assigned to the request.
80
+ *
81
+ * All data stored in `userData` must be JSON-serializable.
82
+ * Storing non-serializable values (e.g. functions, symbols) may result in unexpected results.
83
+ */
81
84
  userData: UserData;
82
85
  /**
83
86
  * ISO datetime string that indicates the time when the request has been processed.
@@ -93,9 +96,21 @@ declare class CrawleeRequest<UserData extends Dictionary = Dictionary> {
93
96
  * @returns The native `fetch` API Request object.
94
97
  */
95
98
  intoFetchAPIRequest(): Request;
96
- /** Tells the crawler processing this request to skip the navigation and process the request directly. */
99
+ /**
100
+ * Tells the crawler processing this request to skip the navigation and process the request directly.
101
+ *
102
+ * When this is set to `true`, the crawling context will not contain the results of the navigation
103
+ * (e.g. `response`, `body`, `contentType`, `$` or `request.loadedUrl`).
104
+ * Accessing these properties will throw a {@link NavigationSkippedError} at runtime.
105
+ */
97
106
  get skipNavigation(): boolean;
98
- /** Tells the crawler processing this request to skip the navigation and process the request directly. */
107
+ /**
108
+ * Tells the crawler processing this request to skip the navigation and process the request directly.
109
+ *
110
+ * When this is set to `true`, the crawling context will not contain the results of the navigation
111
+ * (e.g. `response`, `body`, `contentType`, `$` or `request.loadedUrl`).
112
+ * Accessing these properties will throw a {@link NavigationSkippedError} at runtime.
113
+ */
99
114
  set skipNavigation(value: boolean);
100
115
  /**
101
116
  * Depth of the request in the current crawl tree.
@@ -107,10 +122,9 @@ declare class CrawleeRequest<UserData extends Dictionary = Dictionary> {
107
122
  * Note that this is dependent on the crawler setup and might produce unexpected results when used with multiple crawlers.
108
123
  */
109
124
  set crawlDepth(value: number);
110
- /** Indicates the number of times the crawling of the request has rotated the session due to a session or a proxy error. */
111
- get sessionRotationCount(): number;
112
- /** Indicates the number of times the crawling of the request has rotated the session due to a session or a proxy error. */
113
- set sessionRotationCount(value: number);
125
+ /** 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. */
126
+ get sessionId(): string | undefined;
127
+ set sessionId(value: string | undefined);
114
128
  /** shortcut for getting `request.userData.label` */
115
129
  get label(): string | undefined;
116
130
  /** shortcut for setting `request.userData.label` */
@@ -123,6 +137,14 @@ declare class CrawleeRequest<UserData extends Dictionary = Dictionary> {
123
137
  get state(): RequestState;
124
138
  /** Describes the request's current lifecycle state. */
125
139
  set state(value: RequestState);
140
+ /**
141
+ * Reason for skipping this request.
142
+ */
143
+ get skippedReason(): SkippedRequestReason | undefined;
144
+ /**
145
+ * Reason for skipping this request.
146
+ */
147
+ set skippedReason(value: SkippedRequestReason | undefined);
126
148
  private get enqueueStrategy();
127
149
  private set enqueueStrategy(value);
128
150
  /**
@@ -140,7 +162,7 @@ declare class CrawleeRequest<UserData extends Dictionary = Dictionary> {
140
162
  */
141
163
  pushErrorMessage(errorOrMessage: unknown, options?: PushErrorMessageOptions): void;
142
164
  /** @internal */
143
- static computeUniqueKey({ url, method, payload, keepUrlFragment, useExtendedUniqueKey, }: ComputeUniqueKeyOptions): string;
165
+ static computeUniqueKey({ url, method, payload, keepUrlFragment, useExtendedUniqueKey, alwaysEnqueue, }: ComputeUniqueKeyOptions): string;
144
166
  /** @internal */
145
167
  static hashPayload(payload: BinaryLike): string;
146
168
  }
@@ -161,7 +183,7 @@ export interface RequestOptions<UserData extends Dictionary = Dictionary> {
161
183
  * The `keepUrlFragment` option determines whether URL hash fragment is included in the `uniqueKey` or not.
162
184
  *
163
185
  * The `useExtendedUniqueKey` options determines whether method and payload are included in the `uniqueKey`,
164
- * producing a `uniqueKey` in the following format: `METHOD(payloadHash):normalizedUrl`. This is useful
186
+ * producing a `uniqueKey` in the following format: `METHOD|payloadHash|normalizedUrl`. This is useful
165
187
  * when requests point to the same URL, but with different methods and payloads. For example: form submits.
166
188
  *
167
189
  * Pass an arbitrary non-empty text value to the `uniqueKey` property
@@ -185,6 +207,9 @@ export interface RequestOptions<UserData extends Dictionary = Dictionary> {
185
207
  /**
186
208
  * Custom user data assigned to the request. Use this to save any request related data to the
187
209
  * request's scope, keeping them accessible on retries, failures etc.
210
+ *
211
+ * All data stored in `userData` must be JSON-serializable.
212
+ * Storing non-serializable values (e.g. functions, symbols) may result in unexpected results.
188
213
  */
189
214
  userData?: UserData;
190
215
  /**
@@ -206,14 +231,30 @@ export interface RequestOptions<UserData extends Dictionary = Dictionary> {
206
231
  * @default false
207
232
  */
208
233
  useExtendedUniqueKey?: boolean;
234
+ /**
235
+ * If `true` then a random value is included in the `uniqueKey` computation, ensuring the request
236
+ * is always enqueued even if a request with the same URL (and method/payload) is already present
237
+ * in the queue. Cannot be used together with a custom `uniqueKey`.
238
+ * @default false
239
+ */
240
+ alwaysEnqueue?: boolean;
209
241
  /**
210
242
  * The `true` value indicates that the request will not be automatically retried on error.
211
243
  * @default false
212
244
  */
213
245
  noRetry?: boolean;
246
+ /**
247
+ * ID of a session from the crawler's `SessionPool` to use for this request.
248
+ * When set, the crawler will fetch this session from the pool instead of creating a new one.
249
+ */
250
+ sessionId?: string;
214
251
  /**
215
252
  * If set to `true` then the crawler processing this request evaluates
216
253
  * the `requestHandler` immediately without prior browser navigation.
254
+ *
255
+ * When enabled, the crawling context will not contain the results of the navigation
256
+ * (e.g. `response`, `body`, `contentType`, `$` or `request.loadedUrl`).
257
+ * Accessing these properties will throw a {@link NavigationSkippedError} at runtime.
217
258
  * @default false
218
259
  */
219
260
  skipNavigation?: boolean;
@@ -240,7 +281,7 @@ export interface RequestOptions<UserData extends Dictionary = Dictionary> {
240
281
  /** @internal */
241
282
  lockExpiresAt?: Date;
242
283
  /** @internal */
243
- enqueueStrategy?: EnqueueLinksOptions['strategy'];
284
+ enqueueStrategy?: EnqueueStrategyOption;
244
285
  }
245
286
  export interface PushErrorMessageOptions {
246
287
  /**
@@ -255,6 +296,7 @@ interface ComputeUniqueKeyOptions {
255
296
  payload?: string | Buffer;
256
297
  keepUrlFragment?: boolean;
257
298
  useExtendedUniqueKey?: boolean;
299
+ alwaysEnqueue?: boolean;
258
300
  }
259
301
  export type Source = (Partial<RequestOptions> & {
260
302
  requestsFromUrl?: string;
@@ -266,4 +308,3 @@ export interface InternalSource {
266
308
  regex?: RegExp;
267
309
  }
268
310
  export { CrawleeRequest as Request };
269
- //# sourceMappingURL=request.d.ts.map