@crawlee/core 4.0.0-beta.27 → 4.0.0-beta.271

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