@crawlee/core 4.0.0-beta.2 → 4.0.0-beta.200

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 (259) hide show
  1. package/README.md +17 -13
  2. package/byte_utils.d.ts +17 -0
  3. package/byte_utils.js +42 -0
  4. package/configuration.d.ts +88 -234
  5. package/configuration.js +162 -230
  6. package/debug.d.ts +36 -0
  7. package/debug.js +70 -0
  8. package/errors.d.ts +43 -10
  9. package/errors.js +57 -12
  10. package/events/event_manager.d.ts +35 -9
  11. package/events/event_manager.js +12 -13
  12. package/events/index.d.ts +1 -1
  13. package/events/index.js +0 -1
  14. package/events/local_event_manager.d.ts +15 -5
  15. package/events/local_event_manager.js +39 -42
  16. package/events/system_info.d.ts +38 -0
  17. package/events/system_info.js +1 -0
  18. package/index.d.ts +8 -11
  19. package/index.js +9 -10
  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 +81 -3
  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 +40 -0
  35. package/memory-storage/resource-clients/dataset.js +106 -0
  36. package/memory-storage/resource-clients/key-value-store.d.ts +56 -0
  37. package/memory-storage/resource-clients/key-value-store.js +180 -0
  38. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  39. package/memory-storage/resource-clients/request-queue.js +414 -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 +19 -20
  45. package/proxy_configuration.d.ts +29 -155
  46. package/proxy_configuration.js +38 -183
  47. package/recoverable_state.d.ts +177 -0
  48. package/recoverable_state.js +268 -0
  49. package/request.d.ts +62 -81
  50. package/request.js +125 -220
  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 +37 -0
  56. package/storages/batched_adds.js +73 -0
  57. package/storages/dataset.d.ts +120 -56
  58. package/storages/dataset.js +299 -148
  59. package/storages/index.d.ts +9 -8
  60. package/storages/index.js +5 -8
  61. package/storages/key_value_store.d.ts +192 -65
  62. package/storages/key_value_store.js +453 -193
  63. package/storages/key_value_store_codec.d.ts +32 -0
  64. package/storages/key_value_store_codec.js +113 -0
  65. package/storages/request_dedup_cache.d.ts +22 -0
  66. package/storages/request_dedup_cache.js +48 -0
  67. package/storages/request_list.d.ts +55 -137
  68. package/storages/request_list.js +272 -245
  69. package/storages/request_loader.d.ts +127 -0
  70. package/storages/request_loader.js +36 -0
  71. package/storages/request_manager.d.ts +119 -0
  72. package/storages/request_manager.js +1 -0
  73. package/storages/request_manager_tandem.d.ts +94 -0
  74. package/storages/request_manager_tandem.js +200 -0
  75. package/storages/request_queue.d.ts +293 -48
  76. package/storages/request_queue.js +766 -216
  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 +271 -0
  82. package/storages/transaction.js +296 -0
  83. package/storages/utils.d.ts +59 -11
  84. package/storages/utils.js +75 -15
  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 -292
  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 -113
  120. package/cookie_utils.js.map +0 -1
  121. package/crawlers/crawler_commons.d.ts +0 -199
  122. package/crawlers/crawler_commons.d.ts.map +0 -1
  123. package/crawlers/crawler_commons.js +0 -116
  124. package/crawlers/crawler_commons.js.map +0 -1
  125. package/crawlers/crawler_extension.d.ts +0 -12
  126. package/crawlers/crawler_extension.d.ts.map +0 -1
  127. package/crawlers/crawler_extension.js +0 -14
  128. package/crawlers/crawler_extension.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 -59
  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 -54
  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/statistics.d.ts +0 -204
  146. package/crawlers/statistics.d.ts.map +0 -1
  147. package/crawlers/statistics.js +0 -346
  148. package/crawlers/statistics.js.map +0 -1
  149. package/enqueue_links/enqueue_links.d.ts +0 -242
  150. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  151. package/enqueue_links/enqueue_links.js +0 -250
  152. package/enqueue_links/enqueue_links.js.map +0 -1
  153. package/enqueue_links/index.d.ts +0 -3
  154. package/enqueue_links/index.d.ts.map +0 -1
  155. package/enqueue_links/index.js +0 -3
  156. package/enqueue_links/index.js.map +0 -1
  157. package/enqueue_links/shared.d.ts +0 -67
  158. package/enqueue_links/shared.d.ts.map +0 -1
  159. package/enqueue_links/shared.js +0 -190
  160. package/enqueue_links/shared.js.map +0 -1
  161. package/errors.d.ts.map +0 -1
  162. package/errors.js.map +0 -1
  163. package/events/event_manager.d.ts.map +0 -1
  164. package/events/event_manager.js.map +0 -1
  165. package/events/index.d.ts.map +0 -1
  166. package/events/index.js.map +0 -1
  167. package/events/local_event_manager.d.ts.map +0 -1
  168. package/events/local_event_manager.js.map +0 -1
  169. package/http_clients/base-http-client.d.ts +0 -134
  170. package/http_clients/base-http-client.d.ts.map +0 -1
  171. package/http_clients/base-http-client.js +0 -33
  172. package/http_clients/base-http-client.js.map +0 -1
  173. package/http_clients/form-data-like.d.ts +0 -67
  174. package/http_clients/form-data-like.d.ts.map +0 -1
  175. package/http_clients/form-data-like.js +0 -5
  176. package/http_clients/form-data-like.js.map +0 -1
  177. package/http_clients/got-scraping-http-client.d.ts +0 -15
  178. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  179. package/http_clients/got-scraping-http-client.js +0 -69
  180. package/http_clients/got-scraping-http-client.js.map +0 -1
  181. package/http_clients/index.d.ts +0 -3
  182. package/http_clients/index.d.ts.map +0 -1
  183. package/http_clients/index.js +0 -3
  184. package/http_clients/index.js.map +0 -1
  185. package/index.d.ts.map +0 -1
  186. package/index.js.map +0 -1
  187. package/log.d.ts.map +0 -1
  188. package/log.js.map +0 -1
  189. package/proxy_configuration.d.ts.map +0 -1
  190. package/proxy_configuration.js.map +0 -1
  191. package/request.d.ts.map +0 -1
  192. package/request.js.map +0 -1
  193. package/router.d.ts +0 -134
  194. package/router.d.ts.map +0 -1
  195. package/router.js +0 -164
  196. package/router.js.map +0 -1
  197. package/serialization.d.ts.map +0 -1
  198. package/serialization.js.map +0 -1
  199. package/session_pool/consts.d.ts +0 -4
  200. package/session_pool/consts.d.ts.map +0 -1
  201. package/session_pool/consts.js +0 -4
  202. package/session_pool/consts.js.map +0 -1
  203. package/session_pool/errors.d.ts +0 -8
  204. package/session_pool/errors.d.ts.map +0 -1
  205. package/session_pool/errors.js +0 -12
  206. package/session_pool/errors.js.map +0 -1
  207. package/session_pool/events.d.ts +0 -3
  208. package/session_pool/events.d.ts.map +0 -1
  209. package/session_pool/events.js +0 -3
  210. package/session_pool/events.js.map +0 -1
  211. package/session_pool/index.d.ts +0 -6
  212. package/session_pool/index.d.ts.map +0 -1
  213. package/session_pool/index.js +0 -6
  214. package/session_pool/index.js.map +0 -1
  215. package/session_pool/session.d.ts +0 -199
  216. package/session_pool/session.d.ts.map +0 -1
  217. package/session_pool/session.js +0 -271
  218. package/session_pool/session.js.map +0 -1
  219. package/session_pool/session_pool.d.ts +0 -251
  220. package/session_pool/session_pool.d.ts.map +0 -1
  221. package/session_pool/session_pool.js +0 -375
  222. package/session_pool/session_pool.js.map +0 -1
  223. package/storages/access_checking.d.ts +0 -13
  224. package/storages/access_checking.d.ts.map +0 -1
  225. package/storages/access_checking.js +0 -14
  226. package/storages/access_checking.js.map +0 -1
  227. package/storages/dataset.d.ts.map +0 -1
  228. package/storages/dataset.js.map +0 -1
  229. package/storages/index.d.ts.map +0 -1
  230. package/storages/index.js.map +0 -1
  231. package/storages/key_value_store.d.ts.map +0 -1
  232. package/storages/key_value_store.js.map +0 -1
  233. package/storages/request_list.d.ts.map +0 -1
  234. package/storages/request_list.js.map +0 -1
  235. package/storages/request_provider.d.ts +0 -307
  236. package/storages/request_provider.d.ts.map +0 -1
  237. package/storages/request_provider.js +0 -555
  238. package/storages/request_provider.js.map +0 -1
  239. package/storages/request_queue.d.ts.map +0 -1
  240. package/storages/request_queue.js.map +0 -1
  241. package/storages/request_queue_v2.d.ts +0 -87
  242. package/storages/request_queue_v2.d.ts.map +0 -1
  243. package/storages/request_queue_v2.js +0 -438
  244. package/storages/request_queue_v2.js.map +0 -1
  245. package/storages/sitemap_request_list.d.ts +0 -245
  246. package/storages/sitemap_request_list.d.ts.map +0 -1
  247. package/storages/sitemap_request_list.js +0 -430
  248. package/storages/sitemap_request_list.js.map +0 -1
  249. package/storages/storage_manager.d.ts +0 -58
  250. package/storages/storage_manager.d.ts.map +0 -1
  251. package/storages/storage_manager.js +0 -105
  252. package/storages/storage_manager.js.map +0 -1
  253. package/storages/utils.d.ts.map +0 -1
  254. package/storages/utils.js.map +0 -1
  255. package/tsconfig.build.tsbuildinfo +0 -1
  256. package/typedefs.d.ts.map +0 -1
  257. package/typedefs.js.map +0 -1
  258. package/validators.d.ts.map +0 -1
  259. package/validators.js.map +0 -1
@@ -1,346 +0,0 @@
1
- import ow from 'ow';
2
- import { Configuration } from '../configuration.js';
3
- import { log as defaultLog } from '../log.js';
4
- import { KeyValueStore } from '../storages/key_value_store.js';
5
- import { ErrorTracker } from './error_tracker.js';
6
- /**
7
- * @ignore
8
- */
9
- class Job {
10
- lastRunAt = null;
11
- durationMillis;
12
- run() {
13
- this.lastRunAt = Date.now();
14
- }
15
- finish() {
16
- this.durationMillis = Date.now() - this.lastRunAt;
17
- return this.durationMillis;
18
- }
19
- }
20
- const errorTrackerConfig = {
21
- showErrorCode: true,
22
- showErrorName: true,
23
- showStackTrace: true,
24
- showFullStack: false,
25
- showErrorMessage: true,
26
- showFullMessage: false,
27
- };
28
- /**
29
- * The statistics class provides an interface to collecting and logging run
30
- * statistics for requests.
31
- *
32
- * All statistic information is saved on key value store
33
- * under the key `SDK_CRAWLER_STATISTICS_*`, persists between
34
- * migrations and abort/resurrect
35
- *
36
- * @category Crawlers
37
- */
38
- export class Statistics {
39
- static id = 0;
40
- /**
41
- * An error tracker for final retry errors.
42
- */
43
- errorTracker;
44
- /**
45
- * An error tracker for retry errors prior to the final retry.
46
- */
47
- errorTrackerRetry;
48
- /**
49
- * Statistic instance id.
50
- */
51
- id = Statistics.id++; // assign an id while incrementing so it can be saved/restored from KV
52
- /**
53
- * Current statistic state used for doing calculations on {@link Statistics.calculate} calls
54
- */
55
- state;
56
- /**
57
- * Contains the current retries histogram. Index 0 means 0 retries, index 2, 2 retries, and so on
58
- */
59
- requestRetryHistogram = [];
60
- /**
61
- * Contains the associated Configuration instance
62
- */
63
- config;
64
- keyValueStore = undefined;
65
- persistStateKey = `SDK_CRAWLER_STATISTICS_${this.id}`;
66
- logIntervalMillis;
67
- logMessage;
68
- listener;
69
- requestsInProgress = new Map();
70
- log;
71
- instanceStart;
72
- logInterval;
73
- events;
74
- persistenceOptions;
75
- /**
76
- * @internal
77
- */
78
- constructor(options = {}) {
79
- ow(options, ow.object.exactShape({
80
- logIntervalSecs: ow.optional.number,
81
- logMessage: ow.optional.string,
82
- log: ow.optional.object,
83
- keyValueStore: ow.optional.object,
84
- config: ow.optional.object,
85
- persistenceOptions: ow.optional.object,
86
- saveErrorSnapshots: ow.optional.boolean,
87
- }));
88
- const { logIntervalSecs = 60, logMessage = 'Statistics', keyValueStore, config = Configuration.getGlobalConfig(), persistenceOptions = {
89
- enable: true,
90
- }, saveErrorSnapshots = false, } = options;
91
- this.log = (options.log ?? defaultLog).child({ prefix: 'Statistics' });
92
- this.errorTracker = new ErrorTracker({ ...errorTrackerConfig, saveErrorSnapshots });
93
- this.errorTrackerRetry = new ErrorTracker({ ...errorTrackerConfig, saveErrorSnapshots });
94
- this.logIntervalMillis = logIntervalSecs * 1000;
95
- this.logMessage = logMessage;
96
- this.keyValueStore = keyValueStore;
97
- this.listener = this.persistState.bind(this);
98
- this.events = config.getEventManager();
99
- this.config = config;
100
- this.persistenceOptions = persistenceOptions;
101
- // initialize by "resetting"
102
- this.reset();
103
- }
104
- /**
105
- * Set the current statistic instance to pristine values
106
- */
107
- reset() {
108
- this.errorTracker.reset();
109
- this.errorTrackerRetry.reset();
110
- this.state = {
111
- requestsFinished: 0,
112
- requestsFailed: 0,
113
- requestsRetries: 0,
114
- requestsFailedPerMinute: 0,
115
- requestsFinishedPerMinute: 0,
116
- requestMinDurationMillis: Infinity,
117
- requestMaxDurationMillis: 0,
118
- requestTotalFailedDurationMillis: 0,
119
- requestTotalFinishedDurationMillis: 0,
120
- crawlerStartedAt: null,
121
- crawlerFinishedAt: null,
122
- statsPersistedAt: null,
123
- crawlerRuntimeMillis: 0,
124
- requestsWithStatusCode: {},
125
- errors: this.errorTracker.result,
126
- retryErrors: this.errorTrackerRetry.result,
127
- };
128
- this.requestRetryHistogram.length = 0;
129
- this.requestsInProgress.clear();
130
- this.instanceStart = Date.now();
131
- this._teardown();
132
- }
133
- /**
134
- * @param options - Override the persistence options provided in the constructor
135
- */
136
- async resetStore(options) {
137
- if (!this.persistenceOptions.enable && !options?.enable) {
138
- return;
139
- }
140
- if (!this.keyValueStore) {
141
- return;
142
- }
143
- await this.keyValueStore.setValue(this.persistStateKey, null);
144
- }
145
- /**
146
- * Increments the status code counter.
147
- */
148
- registerStatusCode(code) {
149
- const s = String(code);
150
- if (this.state.requestsWithStatusCode[s] === undefined) {
151
- this.state.requestsWithStatusCode[s] = 0;
152
- }
153
- this.state.requestsWithStatusCode[s]++;
154
- }
155
- /**
156
- * Starts a job
157
- * @ignore
158
- */
159
- startJob(id) {
160
- let job = this.requestsInProgress.get(id);
161
- if (!job)
162
- job = new Job();
163
- job.run();
164
- this.requestsInProgress.set(id, job);
165
- }
166
- /**
167
- * Mark job as finished and sets the state
168
- * @ignore
169
- */
170
- finishJob(id, retryCount) {
171
- const job = this.requestsInProgress.get(id);
172
- if (!job)
173
- return;
174
- const jobDurationMillis = job.finish();
175
- this.state.requestsFinished++;
176
- this.state.requestTotalFinishedDurationMillis += jobDurationMillis;
177
- this._saveRetryCountForJob(retryCount);
178
- if (jobDurationMillis < this.state.requestMinDurationMillis)
179
- this.state.requestMinDurationMillis = jobDurationMillis;
180
- if (jobDurationMillis > this.state.requestMaxDurationMillis)
181
- this.state.requestMaxDurationMillis = jobDurationMillis;
182
- this.requestsInProgress.delete(id);
183
- }
184
- /**
185
- * Mark job as failed and sets the state
186
- * @ignore
187
- */
188
- failJob(id, retryCount) {
189
- const job = this.requestsInProgress.get(id);
190
- if (!job)
191
- return;
192
- this.state.requestTotalFailedDurationMillis += job.finish();
193
- this.state.requestsFailed++;
194
- this._saveRetryCountForJob(retryCount);
195
- this.requestsInProgress.delete(id);
196
- }
197
- /**
198
- * Calculate the current statistics
199
- */
200
- calculate() {
201
- const { requestsFailed, requestsFinished, requestTotalFailedDurationMillis, requestTotalFinishedDurationMillis, } = this.state;
202
- const totalMillis = Date.now() - this.instanceStart;
203
- const totalMinutes = totalMillis / 1000 / 60;
204
- return {
205
- requestAvgFailedDurationMillis: Math.round(requestTotalFailedDurationMillis / requestsFailed) || Infinity,
206
- requestAvgFinishedDurationMillis: Math.round(requestTotalFinishedDurationMillis / requestsFinished) || Infinity,
207
- requestsFinishedPerMinute: Math.round(requestsFinished / totalMinutes) || 0,
208
- requestsFailedPerMinute: Math.floor(requestsFailed / totalMinutes) || 0,
209
- requestTotalDurationMillis: requestTotalFinishedDurationMillis + requestTotalFailedDurationMillis,
210
- requestsTotal: requestsFailed + requestsFinished,
211
- crawlerRuntimeMillis: totalMillis,
212
- };
213
- }
214
- /**
215
- * Initializes the key value store for persisting the statistics,
216
- * displaying the current state in predefined intervals
217
- */
218
- async startCapturing() {
219
- this.keyValueStore ??= await KeyValueStore.open(null, { config: this.config });
220
- if (this.state.crawlerStartedAt === null) {
221
- this.state.crawlerStartedAt = new Date();
222
- }
223
- if (this.persistenceOptions.enable) {
224
- await this._maybeLoadStatistics();
225
- this.events.on("persistState" /* EventType.PERSIST_STATE */, this.listener);
226
- }
227
- this.logInterval = setInterval(() => {
228
- this.log.info(this.logMessage, {
229
- ...this.calculate(),
230
- retryHistogram: this.requestRetryHistogram,
231
- });
232
- }, this.logIntervalMillis);
233
- }
234
- /**
235
- * Stops logging and remove event listeners, then persist
236
- */
237
- async stopCapturing() {
238
- this._teardown();
239
- this.state.crawlerFinishedAt = new Date();
240
- await this.persistState();
241
- }
242
- _saveRetryCountForJob(retryCount) {
243
- if (retryCount > 0)
244
- this.state.requestsRetries++;
245
- this.requestRetryHistogram[retryCount] ??= 0;
246
- this.requestRetryHistogram[retryCount]++;
247
- }
248
- /**
249
- * Persist internal state to the key value store
250
- * @param options - Override the persistence options provided in the constructor
251
- */
252
- async persistState(options) {
253
- if (!this.persistenceOptions.enable && !options?.enable) {
254
- return;
255
- }
256
- // this might be called before startCapturing was called without using await, should not crash
257
- if (!this.keyValueStore) {
258
- return;
259
- }
260
- this.log.debug('Persisting state', { persistStateKey: this.persistStateKey });
261
- // use half the interval of `persistState` to avoid race conditions
262
- const persistStateIntervalMillis = this.config.get('persistStateIntervalMillis');
263
- const timeoutSecs = persistStateIntervalMillis / 2_000;
264
- await this.keyValueStore
265
- .setValue(this.persistStateKey, this.toJSON(), {
266
- timeoutSecs,
267
- doNotRetryTimeouts: true,
268
- })
269
- .catch((error) => this.log.warning(`Failed to persist the statistics to ${this.persistStateKey}`, { error }));
270
- }
271
- /**
272
- * Loads the current statistic from the key value store if any
273
- */
274
- async _maybeLoadStatistics() {
275
- // this might be called before startCapturing was called without using await, should not crash
276
- if (!this.keyValueStore) {
277
- return;
278
- }
279
- const savedState = await this.keyValueStore.getValue(this.persistStateKey);
280
- if (!savedState)
281
- return;
282
- // We saw a run where the requestRetryHistogram was not iterable and crashed
283
- // the crawler. Adding some logging to monitor this problem in the future.
284
- if (!Array.isArray(savedState.requestRetryHistogram)) {
285
- this.log.warning('Received invalid state from Key-value store.', {
286
- persistStateKey: this.persistStateKey,
287
- state: savedState,
288
- });
289
- }
290
- this.log.debug('Recreating state from KeyValueStore', { persistStateKey: this.persistStateKey });
291
- // the `requestRetryHistogram` array might be very large, we could end up with
292
- // `RangeError: Maximum call stack size exceeded` if we use `a.push(...b)`
293
- savedState.requestRetryHistogram.forEach((idx) => this.requestRetryHistogram.push(idx));
294
- this.state.requestsFinished = savedState.requestsFinished;
295
- this.state.requestsFailed = savedState.requestsFailed;
296
- this.state.requestsRetries = savedState.requestsRetries;
297
- this.state.requestTotalFailedDurationMillis = savedState.requestTotalFailedDurationMillis;
298
- this.state.requestTotalFinishedDurationMillis = savedState.requestTotalFinishedDurationMillis;
299
- this.state.requestMinDurationMillis = savedState.requestMinDurationMillis;
300
- this.state.requestMaxDurationMillis = savedState.requestMaxDurationMillis;
301
- // persisted state uses ISO date strings
302
- this.state.crawlerFinishedAt = savedState.crawlerFinishedAt ? new Date(savedState.crawlerFinishedAt) : null;
303
- this.state.crawlerStartedAt = savedState.crawlerStartedAt ? new Date(savedState.crawlerStartedAt) : null;
304
- this.state.statsPersistedAt = savedState.statsPersistedAt ? new Date(savedState.statsPersistedAt) : null;
305
- this.state.crawlerRuntimeMillis = savedState.crawlerRuntimeMillis;
306
- this.instanceStart = Date.now() - (+this.state.statsPersistedAt - savedState.crawlerLastStartTimestamp);
307
- this.log.debug('Loaded from KeyValueStore');
308
- }
309
- _teardown() {
310
- // this can be called before a call to startCapturing happens (or in a 'finally' block)
311
- this.events.off("persistState" /* EventType.PERSIST_STATE */, this.listener);
312
- if (this.logInterval) {
313
- clearInterval(this.logInterval);
314
- this.logInterval = null;
315
- }
316
- }
317
- /**
318
- * Make this class serializable when called with `JSON.stringify(statsInstance)` directly
319
- * or through `keyValueStore.setValue('KEY', statsInstance)`
320
- */
321
- toJSON() {
322
- // merge all the current state information that can be used from the outside
323
- // without the need to reconstruct for the sake of stats.calculate()
324
- // omit duplicated information
325
- const result = {
326
- ...this.state,
327
- crawlerLastStartTimestamp: this.instanceStart,
328
- crawlerFinishedAt: this.state.crawlerFinishedAt
329
- ? new Date(this.state.crawlerFinishedAt).toISOString()
330
- : null,
331
- crawlerStartedAt: this.state.crawlerStartedAt ? new Date(this.state.crawlerStartedAt).toISOString() : null,
332
- requestRetryHistogram: this.requestRetryHistogram,
333
- statsId: this.id,
334
- statsPersistedAt: new Date().toISOString(),
335
- ...this.calculate(),
336
- };
337
- Reflect.deleteProperty(result, 'requestsWithStatusCode');
338
- Reflect.deleteProperty(result, 'errors');
339
- Reflect.deleteProperty(result, 'retryErrors');
340
- result.requestsWithStatusCode = this.state.requestsWithStatusCode;
341
- result.errors = this.state.errors;
342
- result.retryErrors = this.state.retryErrors;
343
- return result;
344
- }
345
- }
346
- //# sourceMappingURL=statistics.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"statistics.js","sourceRoot":"","sources":["../../src/crawlers/statistics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AAIpB,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGpD,OAAO,EAAE,GAAG,IAAI,UAAU,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAC/D,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD;;GAEG;AACH,MAAM,GAAG;IACG,SAAS,GAAkB,IAAI,CAAC;IAChC,cAAc,CAAU;IAEhC,GAAG;QACC,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC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AqB;YACjD,OAAO,EAAE,IAAI,CAAC,EAAE;YAChB,gBAAgB,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YAC1C,GAAG,IAAI,CAAC,SAAS,EAAE;SACtB,CAAC;QAEF,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,wBAAwB,CAAC,CAAC;QACzD,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QACzC,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;QAE9C,MAAM,CAAC,sBAAsB,GAAG,IAAI,CAAC,KAAK,CAAC,sBAAsB,CAAC;QAClE,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC;QAClC,MAAM,CAAC,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC;QAE5C,OAAO,MAAM,CAAC;IAClB,CAAC"}
@@ -1,242 +0,0 @@
1
- import type { Awaitable, BatchAddRequestsResult, Dictionary } from '@crawlee/types';
2
- import { type RobotsTxtFile } from '@crawlee/utils';
3
- import type { SetRequired } from 'type-fest';
4
- import type { RequestProvider, RequestQueueOperationOptions } from '../storages/request_provider.js';
5
- import type { GlobInput, PseudoUrlInput, RegExpInput, RequestTransform } from './shared.js';
6
- export type SkippedRequestCallback = (args: {
7
- url: string;
8
- reason: 'robotsTxt';
9
- }) => Awaitable<void>;
10
- export interface EnqueueLinksOptions extends RequestQueueOperationOptions {
11
- /** Limit the amount of actually enqueued URLs to this number. Useful for testing across the entire crawling scope. */
12
- limit?: number;
13
- /** An array of URLs to enqueue. */
14
- urls?: readonly string[];
15
- /** A request queue to which the URLs will be enqueued. */
16
- requestQueue?: RequestProvider;
17
- /** A CSS selector matching links to be enqueued. */
18
- selector?: string;
19
- /** Sets {@link Request.userData} for newly enqueued requests. */
20
- userData?: Dictionary;
21
- /** Sets {@link Request.label} for newly enqueued requests. */
22
- label?: string;
23
- /**
24
- * If set to `true`, tells the crawler to skip navigation and process the request directly.
25
- * @default false
26
- */
27
- skipNavigation?: boolean;
28
- /**
29
- * A base URL that will be used to resolve relative URLs when using Cheerio. Ignored when using Puppeteer,
30
- * since the relative URL resolution is done inside the browser automatically.
31
- */
32
- baseUrl?: string;
33
- /**
34
- * An array of glob pattern strings or plain objects
35
- * containing glob pattern strings matching the URLs to be enqueued.
36
- *
37
- * The plain objects must include at least the `glob` property, which holds the glob pattern string.
38
- * All remaining keys will be used as request options for the corresponding enqueued {@link Request} objects.
39
- *
40
- * The matching is always case-insensitive.
41
- * If you need case-sensitive matching, use `regexps` property directly.
42
- *
43
- * If `globs` is an empty array or `undefined`, and `regexps` are also not defined, then the function
44
- * enqueues the links with the same subdomain.
45
- */
46
- globs?: readonly GlobInput[];
47
- /**
48
- * An array of glob pattern strings, regexp patterns or plain objects
49
- * containing patterns matching URLs that will **never** be enqueued.
50
- *
51
- * The plain objects must include either the `glob` property or the `regexp` property.
52
- * All remaining keys will be used as request options for the corresponding enqueued {@link Request} objects.
53
- *
54
- * Glob matching is always case-insensitive.
55
- * If you need case-sensitive matching, provide a regexp.
56
- */
57
- exclude?: readonly (GlobInput | RegExpInput)[];
58
- /**
59
- * An array of regular expressions or plain objects
60
- * containing regular expressions matching the URLs to be enqueued.
61
- *
62
- * The plain objects must include at least the `regexp` property, which holds the regular expression.
63
- * All remaining keys will be used as request options for the corresponding enqueued {@link Request} objects.
64
- *
65
- * If `regexps` is an empty array or `undefined`, and `globs` are also not defined, then the function
66
- * enqueues the links with the same subdomain.
67
- */
68
- regexps?: readonly RegExpInput[];
69
- /**
70
- * *NOTE:* In future versions of SDK the options will be removed.
71
- * Please use `globs` or `regexps` instead.
72
- *
73
- * An array of {@link PseudoUrl} strings or plain objects
74
- * containing {@link PseudoUrl} strings matching the URLs to be enqueued.
75
- *
76
- * The plain objects must include at least the `purl` property, which holds the pseudo-URL string.
77
- * All remaining keys will be used as request options for the corresponding enqueued {@link Request} objects.
78
- *
79
- * With a pseudo-URL string, the matching is always case-insensitive.
80
- * If you need case-sensitive matching, use `regexps` property directly.
81
- *
82
- * If `pseudoUrls` is an empty array or `undefined`, then the function
83
- * enqueues the links with the same subdomain.
84
- *
85
- * @deprecated prefer using `globs` or `regexps` instead
86
- */
87
- pseudoUrls?: readonly PseudoUrlInput[];
88
- /**
89
- * Just before a new {@link Request} is constructed and enqueued to the {@link RequestQueue}, this function can be used
90
- * to remove it or modify its contents such as `userData`, `payload` or, most importantly `uniqueKey`. This is useful
91
- * when you need to enqueue multiple `Requests` to the queue that share the same URL, but differ in methods or payloads,
92
- * or to dynamically update or create `userData`.
93
- *
94
- * For example: by adding `keepUrlFragment: true` to the `request` object, URL fragments will not be removed
95
- * when `uniqueKey` is computed.
96
- *
97
- * **Example:**
98
- * ```javascript
99
- * {
100
- * transformRequestFunction: (request) => {
101
- * request.userData.foo = 'bar';
102
- * request.keepUrlFragment = true;
103
- * return request;
104
- * }
105
- * }
106
- * ```
107
- *
108
- * Note that `transformRequestFunction` has a priority over request options
109
- * specified in `globs`, `regexps`, or `pseudoUrls` objects,
110
- * and thus some options could be over-written by `transformRequestFunction`.
111
- */
112
- transformRequestFunction?: RequestTransform;
113
- /**
114
- * The strategy to use when enqueueing the urls.
115
- *
116
- * Depending on the strategy you select, we will only check certain parts of the URLs found. Here is a diagram of each URL part and their name:
117
- *
118
- * ```md
119
- * Protocol Domain
120
- * ┌────┐ ┌─────────┐
121
- * https://example.crawlee.dev/...
122
- * │ └─────────────────┤
123
- * │ Hostname │
124
- * │ │
125
- * └─────────────────────────┘
126
- * Origin
127
- *```
128
- *
129
- * @default EnqueueStrategy.SameHostname
130
- */
131
- strategy?: EnqueueStrategy | 'all' | 'same-domain' | 'same-hostname' | 'same-origin';
132
- /**
133
- * By default, only the first batch (1000) of found requests will be added to the queue before resolving the call.
134
- * You can use this option to wait for adding all of them.
135
- */
136
- waitForAllRequestsToBeAdded?: boolean;
137
- /**
138
- * RobotsTxtFile instance for the current request that triggered the `enqueueLinks`.
139
- * If provided, disallowed URLs will be ignored.
140
- */
141
- robotsTxtFile?: RobotsTxtFile;
142
- /**
143
- * When a request is skipped for some reason, you can use this callback to act on it.
144
- * This is currently fired only for requests skipped based on robots.txt file.
145
- */
146
- onSkippedRequest?: SkippedRequestCallback;
147
- }
148
- /**
149
- * The different enqueueing strategies available.
150
- *
151
- * Depending on the strategy you select, we will only check certain parts of the URLs found. Here is a diagram of each URL part and their name:
152
- *
153
- * ```md
154
- * Protocol Domain
155
- * ┌────┐ ┌─────────┐
156
- * https://example.crawlee.dev/...
157
- * │ └─────────────────┤
158
- * │ Hostname │
159
- * │ │
160
- * └─────────────────────────┘
161
- * Origin
162
- *```
163
- *
164
- * - The `Protocol` is usually `http` or `https`
165
- * - The `Domain` represents the path without any possible subdomains to a website. For example, `crawlee.dev` is the domain of `https://example.crawlee.dev/`
166
- * - The `Hostname` is the full path to a website, including any subdomains. For example, `example.crawlee.dev` is the hostname of `https://example.crawlee.dev/`
167
- * - The `Origin` is the combination of the `Protocol` and `Hostname`. For example, `https://example.crawlee.dev` is the origin of `https://example.crawlee.dev/`
168
- */
169
- export declare enum EnqueueStrategy {
170
- /**
171
- * Matches any URLs found
172
- */
173
- All = "all",
174
- /**
175
- * Matches any URLs that have the same hostname.
176
- * For example, `https://wow.example.com/hello` will be matched for a base url of `https://wow.example.com/`, but
177
- * `https://example.com/hello` will not be matched.
178
- *
179
- * > This strategy will match both `http` and `https` protocols regardless of the base URL protocol.
180
- */
181
- SameHostname = "same-hostname",
182
- /**
183
- * Matches any URLs that have the same domain as the base URL.
184
- * For example, `https://wow.an.example.com` and `https://example.com` will both be matched for a base url of
185
- * `https://example.com`.
186
- *
187
- * > This strategy will match both `http` and `https` protocols regardless of the base URL protocol.
188
- */
189
- SameDomain = "same-domain",
190
- /**
191
- * Matches any URLs that have the same hostname and protocol.
192
- * For example, `https://wow.example.com/hello` will be matched for a base url of `https://wow.example.com/`, but
193
- * `http://wow.example.com/hello` will not be matched.
194
- *
195
- * > This strategy will ensure the protocol of the base URL is the same as the protocol of the URL to be enqueued.
196
- */
197
- SameOrigin = "same-origin"
198
- }
199
- /**
200
- * This function enqueues the urls provided to the {@link RequestQueue} provided. If you want to automatically find and enqueue links,
201
- * you should use the context-aware `enqueueLinks` function provided on the crawler contexts.
202
- *
203
- * Optionally, the function allows you to filter the target links' URLs using an array of globs or regular expressions
204
- * and override settings of the enqueued {@link Request} objects.
205
- *
206
- * **Example usage**
207
- *
208
- * ```javascript
209
- * await enqueueLinks({
210
- * urls: aListOfFoundUrls,
211
- * requestQueue,
212
- * selector: 'a.product-detail',
213
- * globs: [
214
- * 'https://www.example.com/handbags/*',
215
- * 'https://www.example.com/purses/*'
216
- * ],
217
- * });
218
- * ```
219
- *
220
- * @param options All `enqueueLinks()` parameters are passed via an options object.
221
- * @returns Promise that resolves to {@link BatchAddRequestsResult} object.
222
- */
223
- export declare function enqueueLinks(options: SetRequired<EnqueueLinksOptions, 'requestQueue' | 'urls'>): Promise<BatchAddRequestsResult>;
224
- /**
225
- * @internal
226
- * This method helps resolve the baseUrl that will be used for filtering in {@link enqueueLinks}.
227
- * - If a user provides a base url, we always return it
228
- * - If a user specifies {@link EnqueueStrategy.All} strategy, they do not care if the newly found urls are on the original
229
- * request domain, or a redirected one
230
- * - In all other cases, we return the domain of the original request as that's the one we need to use for filtering
231
- */
232
- export declare function resolveBaseUrlForEnqueueLinksFiltering({ enqueueStrategy, finalRequestUrl, originalRequestUrl, userProvidedBaseUrl, }: ResolveBaseUrl): string | undefined;
233
- /**
234
- * @internal
235
- */
236
- export interface ResolveBaseUrl {
237
- userProvidedBaseUrl?: string;
238
- enqueueStrategy?: EnqueueLinksOptions['strategy'];
239
- originalRequestUrl: string;
240
- finalRequestUrl?: string;
241
- }
242
- //# sourceMappingURL=enqueue_links.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"enqueue_links.d.ts","sourceRoot":"","sources":["../../src/enqueue_links/enqueue_links.ts"],"names":[],"mappings":"AAAA,OAA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