@crawlee/core 4.0.0-beta.19 → 4.0.0-beta.190

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 (270) hide show
  1. package/README.md +14 -14
  2. package/byte_utils.d.ts +17 -0
  3. package/byte_utils.js +42 -0
  4. package/configuration.d.ts +90 -226
  5. package/configuration.js +164 -225
  6. package/debug.d.ts +36 -0
  7. package/debug.js +70 -0
  8. package/errors.d.ts +40 -19
  9. package/errors.js +53 -28
  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 -3
  15. package/events/local_event_manager.js +39 -13
  16. package/events/system_info.d.ts +38 -0
  17. package/events/system_info.js +1 -0
  18. package/index.d.ts +7 -11
  19. package/index.js +8 -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 +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 +44 -0
  31. package/memory-storage/memory-storage.js +160 -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 +63 -0
  37. package/memory-storage/resource-clients/key-value-store.js +199 -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 +18 -19
  45. package/proxy_configuration.d.ts +22 -134
  46. package/proxy_configuration.js +34 -146
  47. package/recoverable_state.d.ts +85 -51
  48. package/recoverable_state.js +178 -72
  49. package/request.d.ts +48 -93
  50. package/request.js +116 -217
  51. package/serialization.d.ts +0 -1
  52. package/serialization.js +15 -15
  53. package/service_locator.d.ts +165 -0
  54. package/service_locator.js +254 -0
  55. package/storages/batched_adds.d.ts +37 -0
  56. package/storages/batched_adds.js +73 -0
  57. package/storages/dataset.d.ts +114 -56
  58. package/storages/dataset.js +292 -149
  59. package/storages/index.d.ts +7 -9
  60. package/storages/index.js +5 -9
  61. package/storages/key_value_store.d.ts +187 -50
  62. package/storages/key_value_store.js +453 -172
  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 +54 -129
  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 +109 -0
  72. package/storages/request_manager.js +1 -0
  73. package/storages/request_manager_tandem.d.ts +50 -23
  74. package/storages/request_manager_tandem.js +132 -57
  75. package/storages/request_queue.d.ts +286 -48
  76. package/storages/request_queue.js +756 -218
  77. package/storages/storage_instance_manager.d.ts +87 -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 +260 -0
  82. package/storages/transaction.js +287 -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 -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 -195
  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 -204
  150. package/crawlers/statistics.d.ts.map +0 -1
  151. package/crawlers/statistics.js +0 -346
  152. package/crawlers/statistics.js.map +0 -1
  153. package/enqueue_links/enqueue_links.d.ts +0 -249
  154. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  155. package/enqueue_links/enqueue_links.js +0 -269
  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 -73
  162. package/enqueue_links/shared.d.ts.map +0 -1
  163. package/enqueue_links/shared.js +0 -212
  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.map +0 -1
  168. package/events/event_manager.js.map +0 -1
  169. package/events/index.d.ts.map +0 -1
  170. package/events/index.js.map +0 -1
  171. package/events/local_event_manager.d.ts.map +0 -1
  172. package/events/local_event_manager.js.map +0 -1
  173. package/http_clients/base-http-client.d.ts +0 -91
  174. package/http_clients/base-http-client.d.ts.map +0 -1
  175. package/http_clients/base-http-client.js +0 -44
  176. package/http_clients/base-http-client.js.map +0 -1
  177. package/http_clients/form-data-like.d.ts +0 -67
  178. package/http_clients/form-data-like.d.ts.map +0 -1
  179. package/http_clients/form-data-like.js +0 -5
  180. package/http_clients/form-data-like.js.map +0 -1
  181. package/http_clients/got-scraping-http-client.d.ts +0 -20
  182. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  183. package/http_clients/got-scraping-http-client.js +0 -102
  184. package/http_clients/got-scraping-http-client.js.map +0 -1
  185. package/http_clients/index.d.ts +0 -3
  186. package/http_clients/index.d.ts.map +0 -1
  187. package/http_clients/index.js +0 -3
  188. package/http_clients/index.js.map +0 -1
  189. package/index.d.ts.map +0 -1
  190. package/index.js.map +0 -1
  191. package/log.d.ts.map +0 -1
  192. package/log.js.map +0 -1
  193. package/proxy_configuration.d.ts.map +0 -1
  194. package/proxy_configuration.js.map +0 -1
  195. package/recoverable_state.d.ts.map +0 -1
  196. package/recoverable_state.js.map +0 -1
  197. package/request.d.ts.map +0 -1
  198. package/request.js.map +0 -1
  199. package/router.d.ts +0 -134
  200. package/router.d.ts.map +0 -1
  201. package/router.js +0 -164
  202. package/router.js.map +0 -1
  203. package/serialization.d.ts.map +0 -1
  204. package/serialization.js.map +0 -1
  205. package/session_pool/consts.d.ts +0 -4
  206. package/session_pool/consts.d.ts.map +0 -1
  207. package/session_pool/consts.js +0 -4
  208. package/session_pool/consts.js.map +0 -1
  209. package/session_pool/errors.d.ts +0 -8
  210. package/session_pool/errors.d.ts.map +0 -1
  211. package/session_pool/errors.js +0 -12
  212. package/session_pool/errors.js.map +0 -1
  213. package/session_pool/events.d.ts +0 -3
  214. package/session_pool/events.d.ts.map +0 -1
  215. package/session_pool/events.js +0 -3
  216. package/session_pool/events.js.map +0 -1
  217. package/session_pool/index.d.ts +0 -6
  218. package/session_pool/index.d.ts.map +0 -1
  219. package/session_pool/index.js +0 -6
  220. package/session_pool/index.js.map +0 -1
  221. package/session_pool/session.d.ts +0 -203
  222. package/session_pool/session.d.ts.map +0 -1
  223. package/session_pool/session.js +0 -278
  224. package/session_pool/session.js.map +0 -1
  225. package/session_pool/session_pool.d.ts +0 -258
  226. package/session_pool/session_pool.d.ts.map +0 -1
  227. package/session_pool/session_pool.js +0 -387
  228. package/session_pool/session_pool.js.map +0 -1
  229. package/storages/access_checking.d.ts +0 -13
  230. package/storages/access_checking.d.ts.map +0 -1
  231. package/storages/access_checking.js +0 -14
  232. package/storages/access_checking.js.map +0 -1
  233. package/storages/dataset.d.ts.map +0 -1
  234. package/storages/dataset.js.map +0 -1
  235. package/storages/index.d.ts.map +0 -1
  236. package/storages/index.js.map +0 -1
  237. package/storages/key_value_store.d.ts.map +0 -1
  238. package/storages/key_value_store.js.map +0 -1
  239. package/storages/request_list.d.ts.map +0 -1
  240. package/storages/request_list.js.map +0 -1
  241. package/storages/request_list_adapter.d.ts +0 -58
  242. package/storages/request_list_adapter.d.ts.map +0 -1
  243. package/storages/request_list_adapter.js +0 -81
  244. package/storages/request_list_adapter.js.map +0 -1
  245. package/storages/request_manager_tandem.d.ts.map +0 -1
  246. package/storages/request_manager_tandem.js.map +0 -1
  247. package/storages/request_provider.d.ts +0 -371
  248. package/storages/request_provider.d.ts.map +0 -1
  249. package/storages/request_provider.js +0 -585
  250. package/storages/request_provider.js.map +0 -1
  251. package/storages/request_queue.d.ts.map +0 -1
  252. package/storages/request_queue.js.map +0 -1
  253. package/storages/request_queue_v2.d.ts +0 -87
  254. package/storages/request_queue_v2.d.ts.map +0 -1
  255. package/storages/request_queue_v2.js +0 -438
  256. package/storages/request_queue_v2.js.map +0 -1
  257. package/storages/sitemap_request_list.d.ts +0 -245
  258. package/storages/sitemap_request_list.d.ts.map +0 -1
  259. package/storages/sitemap_request_list.js +0 -430
  260. package/storages/sitemap_request_list.js.map +0 -1
  261. package/storages/storage_manager.d.ts +0 -58
  262. package/storages/storage_manager.d.ts.map +0 -1
  263. package/storages/storage_manager.js +0 -105
  264. package/storages/storage_manager.js.map +0 -1
  265. package/storages/utils.d.ts.map +0 -1
  266. package/storages/utils.js.map +0 -1
  267. package/typedefs.d.ts.map +0 -1
  268. package/typedefs.js.map +0 -1
  269. package/validators.d.ts.map +0 -1
  270. 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,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B;gBAC3C,CAAC,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC,WAAW,EAAE;gBACtD,CAAC,CAAC,IAAI;YACV,gBAAgB,EAAE,IAAI,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,IAAI;YAC1G,qBAAqB,EAAE,IAAI,CAAC,qBAAqB;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,249 +0,0 @@
1
- import type { BatchAddRequestsResult, Dictionary } from '@crawlee/types';
2
- import { type RobotsTxtFile } from '@crawlee/utils';
3
- import type { SetRequired } from 'type-fest';
4
- import type { Request } from '../request.js';
5
- import type { AddRequestsBatchedOptions, AddRequestsBatchedResult, RequestProvider, RequestQueueOperationOptions } from '../storages/request_provider.js';
6
- import type { GlobInput, PseudoUrlInput, RegExpInput, RequestTransform, SkippedRequestCallback } from './shared.js';
7
- export interface EnqueueLinksOptions extends RequestQueueOperationOptions {
8
- /** Limit the amount of actually enqueued URLs to this number. Useful for testing across the entire crawling scope. */
9
- limit?: number;
10
- /** An array of URLs to enqueue. */
11
- urls?: readonly string[];
12
- /** A request queue to which the URLs will be enqueued. */
13
- requestQueue?: RequestProvider;
14
- /** A CSS selector matching links to be enqueued. */
15
- selector?: string;
16
- /** Sets {@link Request.userData} for newly enqueued requests. */
17
- userData?: Dictionary;
18
- /**
19
- * Sets {@link Request.label} for newly enqueued requests.
20
- *
21
- * Note that the request options specified in `globs`, `regexps`, or `pseudoUrls` objects
22
- * have priority over this option.
23
- */
24
- label?: string;
25
- /**
26
- * If set to `true`, tells the crawler to skip navigation and process the request directly.
27
- * @default false
28
- */
29
- skipNavigation?: boolean;
30
- /**
31
- * A base URL that will be used to resolve relative URLs when using Cheerio. Ignored when using Puppeteer,
32
- * since the relative URL resolution is done inside the browser automatically.
33
- */
34
- baseUrl?: string;
35
- /**
36
- * An array of glob pattern strings or plain objects
37
- * containing glob pattern strings matching the URLs to be enqueued.
38
- *
39
- * The plain objects must include at least the `glob` property, which holds the glob pattern string.
40
- * All remaining keys will be used as request options for the corresponding enqueued {@link Request} objects.
41
- *
42
- * The matching is always case-insensitive.
43
- * If you need case-sensitive matching, use `regexps` property directly.
44
- *
45
- * If `globs` is an empty array or `undefined`, and `regexps` are also not defined, then the function
46
- * enqueues the links with the same subdomain.
47
- */
48
- globs?: readonly GlobInput[];
49
- /**
50
- * An array of glob pattern strings, regexp patterns or plain objects
51
- * containing patterns matching URLs that will **never** be enqueued.
52
- *
53
- * The plain objects must include either the `glob` property or the `regexp` property.
54
- *
55
- * Glob matching is always case-insensitive.
56
- * If you need case-sensitive matching, provide a regexp.
57
- */
58
- exclude?: readonly (GlobInput | RegExpInput)[];
59
- /**
60
- * An array of regular expressions or plain objects
61
- * containing regular expressions matching the URLs to be enqueued.
62
- *
63
- * The plain objects must include at least the `regexp` property, which holds the regular expression.
64
- * All remaining keys will be used as request options for the corresponding enqueued {@link Request} objects.
65
- *
66
- * If `regexps` is an empty array or `undefined`, and `globs` are also not defined, then the function
67
- * enqueues the links with the same subdomain.
68
- */
69
- regexps?: readonly RegExpInput[];
70
- /**
71
- * *NOTE:* In future versions of SDK the options will be removed.
72
- * Please use `globs` or `regexps` instead.
73
- *
74
- * An array of {@link PseudoUrl} strings or plain objects
75
- * containing {@link PseudoUrl} strings matching the URLs to be enqueued.
76
- *
77
- * The plain objects must include at least the `purl` property, which holds the pseudo-URL string.
78
- * All remaining keys will be used as request options for the corresponding enqueued {@link Request} objects.
79
- *
80
- * With a pseudo-URL string, the matching is always case-insensitive.
81
- * If you need case-sensitive matching, use `regexps` property directly.
82
- *
83
- * If `pseudoUrls` is an empty array or `undefined`, then the function
84
- * enqueues the links with the same subdomain.
85
- *
86
- * @deprecated prefer using `globs` or `regexps` instead
87
- */
88
- pseudoUrls?: readonly PseudoUrlInput[];
89
- /**
90
- * Just before a new {@link Request} is constructed and enqueued to the {@link RequestQueue}, this function can be used
91
- * to remove it or modify its contents such as `userData`, `payload` or, most importantly `uniqueKey`. This is useful
92
- * when you need to enqueue multiple `Requests` to the queue that share the same URL, but differ in methods or payloads,
93
- * or to dynamically update or create `userData`.
94
- *
95
- * For example: by adding `keepUrlFragment: true` to the `request` object, URL fragments will not be removed
96
- * when `uniqueKey` is computed.
97
- *
98
- * **Example:**
99
- * ```javascript
100
- * {
101
- * transformRequestFunction: (request) => {
102
- * request.userData.foo = 'bar';
103
- * request.keepUrlFragment = true;
104
- * return request;
105
- * }
106
- * }
107
- * ```
108
- *
109
- * Note that the request options specified in `globs`, `regexps`, or `pseudoUrls` objects
110
- * have priority over this function. Some request options returned by `transformRequestFunction` may be overwritten by pattern-based options from `globs`, `regexps`, or `pseudoUrls`.
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?: Pick<RobotsTxtFile, 'isAllowed'>;
142
- /**
143
- * When a request is skipped for some reason, you can use this callback to act on it.
144
- * This is currently fired for requests skipped
145
- * 1. based on robots.txt file,
146
- * 2. because they don't match enqueueLinks filters,
147
- * 3. or because the maxRequestsPerCrawl limit has been reached
148
- */
149
- onSkippedRequest?: SkippedRequestCallback;
150
- }
151
- /**
152
- * The different enqueueing strategies available.
153
- *
154
- * 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:
155
- *
156
- * ```md
157
- * Protocol Domain
158
- * ┌────┐ ┌─────────┐
159
- * https://example.crawlee.dev/...
160
- * │ └─────────────────┤
161
- * │ Hostname │
162
- * │ │
163
- * └─────────────────────────┘
164
- * Origin
165
- *```
166
- *
167
- * - The `Protocol` is usually `http` or `https`
168
- * - The `Domain` represents the path without any possible subdomains to a website. For example, `crawlee.dev` is the domain of `https://example.crawlee.dev/`
169
- * - 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/`
170
- * - The `Origin` is the combination of the `Protocol` and `Hostname`. For example, `https://example.crawlee.dev` is the origin of `https://example.crawlee.dev/`
171
- */
172
- export declare enum EnqueueStrategy {
173
- /**
174
- * Matches any URLs found
175
- */
176
- All = "all",
177
- /**
178
- * Matches any URLs that have the same hostname.
179
- * For example, `https://wow.example.com/hello` will be matched for a base url of `https://wow.example.com/`, but
180
- * `https://example.com/hello` will not be matched.
181
- *
182
- * > This strategy will match both `http` and `https` protocols regardless of the base URL protocol.
183
- */
184
- SameHostname = "same-hostname",
185
- /**
186
- * Matches any URLs that have the same domain as the base URL.
187
- * For example, `https://wow.an.example.com` and `https://example.com` will both be matched for a base url of
188
- * `https://example.com`.
189
- *
190
- * > This strategy will match both `http` and `https` protocols regardless of the base URL protocol.
191
- */
192
- SameDomain = "same-domain",
193
- /**
194
- * Matches any URLs that have the same hostname and protocol.
195
- * For example, `https://wow.example.com/hello` will be matched for a base url of `https://wow.example.com/`, but
196
- * `http://wow.example.com/hello` will not be matched.
197
- *
198
- * > This strategy will ensure the protocol of the base URL is the same as the protocol of the URL to be enqueued.
199
- */
200
- SameOrigin = "same-origin"
201
- }
202
- /**
203
- * This function enqueues the urls provided to the {@link RequestQueue} provided. If you want to automatically find and enqueue links,
204
- * you should use the context-aware `enqueueLinks` function provided on the crawler contexts.
205
- *
206
- * Optionally, the function allows you to filter the target links' URLs using an array of globs or regular expressions
207
- * and override settings of the enqueued {@link Request} objects.
208
- *
209
- * **Example usage**
210
- *
211
- * ```javascript
212
- * await enqueueLinks({
213
- * urls: aListOfFoundUrls,
214
- * requestQueue,
215
- * selector: 'a.product-detail',
216
- * globs: [
217
- * 'https://www.example.com/handbags/*',
218
- * 'https://www.example.com/purses/*'
219
- * ],
220
- * });
221
- * ```
222
- *
223
- * @param options All `enqueueLinks()` parameters are passed via an options object.
224
- * @returns Promise that resolves to {@link BatchAddRequestsResult} object.
225
- */
226
- export declare function enqueueLinks(options: SetRequired<Omit<EnqueueLinksOptions, 'requestQueue'>, 'urls'> & {
227
- requestQueue: {
228
- addRequestsBatched: (requests: Request<Dictionary>[], options: AddRequestsBatchedOptions) => Promise<AddRequestsBatchedResult>;
229
- };
230
- }): Promise<BatchAddRequestsResult>;
231
- /**
232
- * @internal
233
- * This method helps resolve the baseUrl that will be used for filtering in {@link enqueueLinks}.
234
- * - If a user provides a base url, we always return it
235
- * - If a user specifies {@link EnqueueStrategy.All} strategy, they do not care if the newly found urls are on the original
236
- * request domain, or a redirected one
237
- * - In all other cases, we return the domain of the original request as that's the one we need to use for filtering
238
- */
239
- export declare function resolveBaseUrlForEnqueueLinksFiltering({ enqueueStrategy, finalRequestUrl, originalRequestUrl, userProvidedBaseUrl, }: ResolveBaseUrl): string | undefined;
240
- /**
241
- * @internal
242
- */
243
- export interface ResolveBaseUrl {
244
- userProvidedBaseUrl?: string;
245
- enqueueStrategy?: EnqueueLinksOptions['strategy'];
246
- originalRequestUrl: string;
247
- finalRequestUrl?: string;
248
- }
249
- //# 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,OAAO,KAAK,EAAE,sBAAsB,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AACzE,OAAO,EAAE,KAAK,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAGpD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAI7C,OAAO,KAAK,EAAE,OAAO,EAAkB,MAAM,eAAe,CAAC;AAC7D,OAAO,KAAK,EACR,yBAAyB,EACzB,wBAAwB,EACxB,eAAe,EACf,4BAA4B,EAC/B,MAAM,iCAAiC,CAAC;AACzC,OAAO,KAAK,EACR,SAAS,EACT,cAAc,EACd,WAAW,EACX,gBAAgB,EAChB,sBAAsB,EAGzB,MAAM,aAAa,CAAC;AAUrB,MAAM,WAAW,mBAAoB,SAAQ,4BAA4B;IACrE,sHAAsH;IACtH,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf,mCAAmC;IACnC,IAAI,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAEzB,0DAA0D;IAC1D,YAAY,CAAC,EAAE,eAAe,CAAC;IAE/B,oDAAoD;IACpD,QA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