@crawlee/basic 4.0.0-beta.99 → 4.0.0-rc.1

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 (80) hide show
  1. package/README.md +1 -1
  2. package/index.d.ts +11 -1
  3. package/index.js +11 -0
  4. package/internals/autoscaling/autoscaled_pool.d.ts +178 -0
  5. package/internals/autoscaling/autoscaled_pool.js +387 -0
  6. package/internals/autoscaling/concurrency_system.d.ts +235 -0
  7. package/internals/autoscaling/concurrency_system.js +357 -0
  8. package/internals/autoscaling/cpu_load_signal.d.ts +43 -0
  9. package/internals/autoscaling/cpu_load_signal.js +46 -0
  10. package/internals/autoscaling/event_loop_load_signal.d.ts +51 -0
  11. package/internals/autoscaling/event_loop_load_signal.js +60 -0
  12. package/internals/autoscaling/index.d.ts +9 -0
  13. package/internals/autoscaling/index.js +9 -0
  14. package/internals/autoscaling/load_signal.d.ts +98 -0
  15. package/internals/autoscaling/load_signal.js +103 -0
  16. package/internals/autoscaling/memory_load_signal.d.ts +45 -0
  17. package/internals/autoscaling/memory_load_signal.js +104 -0
  18. package/internals/autoscaling/snapshotter.d.ts +84 -0
  19. package/internals/autoscaling/snapshotter.js +67 -0
  20. package/internals/autoscaling/storage_backend_load_signal.d.ts +56 -0
  21. package/internals/autoscaling/storage_backend_load_signal.js +73 -0
  22. package/internals/autoscaling/system_status.d.ts +112 -0
  23. package/internals/autoscaling/system_status.js +139 -0
  24. package/internals/autoscaling/weighted_avg.d.ts +5 -0
  25. package/internals/autoscaling/weighted_avg.js +14 -0
  26. package/internals/basic-crawler.d.ts +185 -389
  27. package/internals/basic-crawler.js +982 -684
  28. package/internals/cookie_utils.d.ts +40 -0
  29. package/internals/cookie_utils.js +122 -0
  30. package/internals/crawler-run.d.ts +76 -0
  31. package/internals/crawler-run.js +142 -0
  32. package/internals/crawlers/context_pipeline.d.ts +75 -0
  33. package/internals/crawlers/context_pipeline.js +109 -0
  34. package/internals/crawlers/crawler_commons.d.ts +216 -0
  35. package/internals/crawlers/crawler_commons.js +1 -0
  36. package/internals/crawlers/error_snapshotter.d.ts +29 -0
  37. package/internals/crawlers/error_snapshotter.js +116 -0
  38. package/internals/crawlers/error_tracker.d.ts +51 -0
  39. package/internals/crawlers/error_tracker.js +316 -0
  40. package/internals/crawlers/index.d.ts +4 -0
  41. package/internals/crawlers/index.js +3 -0
  42. package/internals/crawlers/internals/types.d.ts +7 -0
  43. package/internals/crawlers/internals/types.js +1 -0
  44. package/internals/crawlers/statistics.d.ts +316 -0
  45. package/internals/crawlers/statistics.js +525 -0
  46. package/internals/crawling_request.d.ts +86 -0
  47. package/internals/crawling_request.js +127 -0
  48. package/internals/enqueue_links/enqueue_links.d.ts +152 -0
  49. package/internals/enqueue_links/enqueue_links.js +76 -0
  50. package/internals/enqueue_links/index.d.ts +3 -0
  51. package/internals/enqueue_links/index.js +3 -0
  52. package/internals/enqueue_links/shared.d.ts +106 -0
  53. package/internals/enqueue_links/shared.js +258 -0
  54. package/internals/errors.d.ts +68 -0
  55. package/internals/errors.js +83 -0
  56. package/internals/http.d.ts +9 -0
  57. package/internals/http.js +28 -0
  58. package/internals/request-timeout.d.ts +6 -0
  59. package/internals/request-timeout.js +27 -2
  60. package/internals/router.d.ts +299 -0
  61. package/internals/router.js +312 -0
  62. package/internals/send-request.d.ts +2 -1
  63. package/internals/send-request.js +1 -0
  64. package/internals/session_pool/consts.d.ts +1 -0
  65. package/internals/session_pool/consts.js +1 -0
  66. package/internals/session_pool/errors.d.ts +7 -0
  67. package/internals/session_pool/errors.js +11 -0
  68. package/internals/session_pool/fingerprint.d.ts +9 -0
  69. package/internals/session_pool/fingerprint.js +30 -0
  70. package/internals/session_pool/index.d.ts +4 -0
  71. package/internals/session_pool/index.js +4 -0
  72. package/internals/session_pool/session.d.ts +151 -0
  73. package/internals/session_pool/session.js +225 -0
  74. package/internals/session_pool/session_pool.d.ts +193 -0
  75. package/internals/session_pool/session_pool.js +453 -0
  76. package/internals/sitemap_request_loader.d.ts +158 -0
  77. package/internals/sitemap_request_loader.js +432 -0
  78. package/internals/throttling_request_manager.d.ts +229 -0
  79. package/internals/throttling_request_manager.js +843 -0
  80. package/package.json +17 -14
@@ -0,0 +1,525 @@
1
+ import { convertStateSync, KeyValueStore, RecoverableState, serviceLocator, validators } from '@crawlee/core';
2
+ import { parseArgument, schemas } from '@crawlee/utils/internal';
3
+ import { z } from 'zod';
4
+ import { ErrorTracker } from './error_tracker.js';
5
+ /**
6
+ * @ignore
7
+ */
8
+ class RequestProcessingRecord {
9
+ #lastRunAt = null;
10
+ run() {
11
+ this.#lastRunAt = Date.now();
12
+ }
13
+ finish() {
14
+ return Date.now() - this.#lastRunAt;
15
+ }
16
+ }
17
+ const statisticsOptionsSchema = z.strictObject({
18
+ logIntervalSecs: schemas.anyNumber.default(60),
19
+ logMessage: z.string().default('Statistics'),
20
+ log: validators.logger.optional(),
21
+ keyValueStore: z.instanceof(KeyValueStore).optional(),
22
+ // `schemas.anyObject` passes values through by reference (object schemas return a pruned plain copy).
23
+ persistenceOptions: schemas.anyObject.default(() => ({ enable: true })),
24
+ saveErrorSnapshots: z.boolean().default(false),
25
+ id: z.union([schemas.anyNumber, z.string()]).optional(),
26
+ stateExtension: schemas.anyObject.default(() => ({})),
27
+ });
28
+ const errorTrackerConfig = {
29
+ showErrorCode: true,
30
+ showErrorName: true,
31
+ showStackTrace: true,
32
+ showFullStack: false,
33
+ showErrorMessage: true,
34
+ showFullMessage: false,
35
+ };
36
+ /**
37
+ * The persisted record, in the order it is written - the schema rebuilds the object on the way out, so the field
38
+ * order here *is* the record's field order (guarded by a test).
39
+ *
40
+ * JSON has no infinity, so the three fields that are `Infinity` until the first request settles are written as
41
+ * `null`. Both {@link Statistics.serializeState} and {@link Statistics.deserializeState} run through this,
42
+ * which is what keeps them describing the same record.
43
+ *
44
+ * Nothing is optional on purpose: the record has always carried every field, so one missing a field is not one of
45
+ * ours and is discarded whole rather than partially trusted - a counter restored as a string would poison every
46
+ * later increment.
47
+ *
48
+ * Custom fields are not this schema's business either way: they are added to the record after the encode and
49
+ * validated by their own conversion on the way back, so the keys it does not know about are simply dropped here.
50
+ */
51
+ const persistedStatisticState = z.object({
52
+ requestsSucceeded: z.number(),
53
+ requestsFailed: z.number(),
54
+ requestsRetries: z.number(),
55
+ requestsFailedPerMinute: z.number().nullable(),
56
+ requestsSucceededPerMinute: z.number().nullable(),
57
+ requestMinDurationMillis: z.number().nullable(),
58
+ requestMaxDurationMillis: z.number(),
59
+ requestTotalFailedDurationMillis: z.number(),
60
+ requestTotalSucceededDurationMillis: z.number(),
61
+ crawlerStartedAt: z.string().nullable(),
62
+ crawlerFinishedAt: z.string().nullable(),
63
+ statsPersistedAt: z.string(),
64
+ crawlerRuntimeMillis: z.number(),
65
+ crawlerLastStartTimestamp: z.number(),
66
+ // A retry count that never occurred leaves a hole in the live histogram, written out as a `null`. We
67
+ // once saw a record whose histogram was not an array at all and crashed the crawler on load.
68
+ requestRetryHistogram: z.array(z.number().nullable()),
69
+ statsId: z.string(),
70
+ requestAvgFailedDurationMillis: z.number().nullable(),
71
+ requestAvgSucceededDurationMillis: z.number().nullable(),
72
+ requestTotalDurationMillis: z.number(),
73
+ requestsTotal: z.number(),
74
+ requestsWithStatusCode: z.record(z.string(), z.number()),
75
+ errors: z.record(z.string(), z.unknown()),
76
+ retryErrors: z.record(z.string(), z.unknown()),
77
+ });
78
+ /** `Infinity` is what the statistics use for "nothing to average yet"; JSON has only `null` for it. */
79
+ function finiteOrNull(value) {
80
+ return Number.isFinite(value) ? value : null;
81
+ }
82
+ /**
83
+ * The conversion between the live state and the record above, in both directions.
84
+ *
85
+ * Built per instance rather than kept as a constant because a record carries three things the state does not: the
86
+ * instance `id`, the derived aggregates of the overridable {@link Statistics.calculate}, and - on the way back -
87
+ * the fields that are rebuilt from the instance's default state rather than restored, the error trackers among them.
88
+ *
89
+ * The model side is deliberately opaque: zod rebuilds what it validates, and `state.errors` has to stay the very
90
+ * object the error trackers write into, not a copy of it.
91
+ */
92
+ function buildStatisticStateCodec(statistics) {
93
+ return z.codec(persistedStatisticState, z.custom(), {
94
+ decode: (record) => ({
95
+ ...statistics.defaultState(),
96
+ requestsSucceeded: record.requestsSucceeded,
97
+ requestsFailed: record.requestsFailed,
98
+ requestsRetries: record.requestsRetries,
99
+ requestTotalFailedDurationMillis: record.requestTotalFailedDurationMillis,
100
+ requestTotalSucceededDurationMillis: record.requestTotalSucceededDurationMillis,
101
+ // Restoring the `null` as-is would make every later `duration < min` comparison fail, leaving the
102
+ // minimum `null` for the rest of the run.
103
+ requestMinDurationMillis: record.requestMinDurationMillis ?? Infinity,
104
+ requestMaxDurationMillis: record.requestMaxDurationMillis,
105
+ crawlerRuntimeMillis: record.crawlerRuntimeMillis,
106
+ // A `null` stands for the zero requests that reached that retry count - restore it as such.
107
+ requestRetryHistogram: record.requestRetryHistogram.map((count) => count ?? 0),
108
+ // The record keeps ISO strings, the live state keeps `Date`s.
109
+ crawlerStartedAt: record.crawlerStartedAt === null ? null : new Date(record.crawlerStartedAt),
110
+ crawlerFinishedAt: record.crawlerFinishedAt === null ? null : new Date(record.crawlerFinishedAt),
111
+ statsPersistedAt: new Date(record.statsPersistedAt),
112
+ // Rebased so that the runtime reported by `calculate()` spans the migration instead of restarting.
113
+ instanceStart: Date.now() - (new Date(record.statsPersistedAt).getTime() - record.crawlerLastStartTimestamp),
114
+ }),
115
+ encode: (state) => {
116
+ // The per-minute rates fall through into `counters` and are overwritten below by `calculate()`'s,
117
+ // which are the ones the record carries.
118
+ const { requestsWithStatusCode, errors, retryErrors, requestRetryHistogram, instanceStart, ...counters } = state;
119
+ // Every rate and average `calculate()` derives is `Infinity` until the run is long enough, or until
120
+ // something has succeeded or failed, to divide by.
121
+ const { requestAvgFailedDurationMillis, requestAvgSucceededDurationMillis, requestsFailedPerMinute, requestsSucceededPerMinute, ...aggregates } = statistics.calculate();
122
+ return {
123
+ ...counters,
124
+ requestMinDurationMillis: finiteOrNull(state.requestMinDurationMillis),
125
+ crawlerStartedAt: state.crawlerStartedAt ? new Date(state.crawlerStartedAt).toISOString() : null,
126
+ crawlerFinishedAt: state.crawlerFinishedAt ? new Date(state.crawlerFinishedAt).toISOString() : null,
127
+ statsPersistedAt: new Date().toISOString(),
128
+ crawlerLastStartTimestamp: instanceStart,
129
+ // `Array.from`, not `map` - a hole left by a retry count no request reached is skipped by `map`
130
+ // and would stay a hole, which is not something the record can carry.
131
+ requestRetryHistogram: Array.from(requestRetryHistogram, (count) => count ?? null),
132
+ statsId: statistics.statsId,
133
+ ...aggregates,
134
+ requestAvgFailedDurationMillis: finiteOrNull(requestAvgFailedDurationMillis),
135
+ requestAvgSucceededDurationMillis: finiteOrNull(requestAvgSucceededDurationMillis),
136
+ requestsFailedPerMinute: finiteOrNull(requestsFailedPerMinute),
137
+ requestsSucceededPerMinute: finiteOrNull(requestsSucceededPerMinute),
138
+ requestsWithStatusCode,
139
+ errors,
140
+ retryErrors,
141
+ };
142
+ },
143
+ });
144
+ }
145
+ /**
146
+ * The statistics class provides an interface to collecting and logging run
147
+ * statistics for requests.
148
+ *
149
+ * All statistic information is saved on key value store
150
+ * under the key `CRAWLEE_CRAWLER_STATISTICS_*`, persists between
151
+ * migrations and abort/resurrect
152
+ *
153
+ * Custom fields are tracked by passing {@link StatisticsOptions.stateExtension|`stateExtension`} - the extra fields are then part
154
+ * of {@link Statistics.state|`state`}, persisted and restored along with the built-in ones.
155
+ *
156
+ * @category Crawlers
157
+ */
158
+ export class Statistics {
159
+ static #id = 0;
160
+ /**
161
+ * An error tracker for final retry errors.
162
+ */
163
+ errorTracker;
164
+ /**
165
+ * An error tracker for retry errors prior to the final retry.
166
+ */
167
+ errorTrackerRetry;
168
+ /**
169
+ * Statistic instance id.
170
+ */
171
+ id;
172
+ #persistStateKey;
173
+ #stateCodec;
174
+ #recoverableState;
175
+ #stateExtension;
176
+ #defaultStateExtension;
177
+ #stateExtensionKeys;
178
+ #logIntervalMillis;
179
+ #logMessage;
180
+ #requestsInProgress = new Map();
181
+ #log;
182
+ #logInterval;
183
+ /**
184
+ * Current statistic state used for doing calculations on {@link Statistics.calculate} calls
185
+ */
186
+ get state() {
187
+ return this.#recoverableState.currentValue;
188
+ }
189
+ /**
190
+ * Contains the current retries histogram. Index 0 means 0 retries, index 2, 2 retries, and so on
191
+ */
192
+ get requestRetryHistogram() {
193
+ return this.state.requestRetryHistogram;
194
+ }
195
+ /**
196
+ * Construct a statistics instance to pass to a crawler via its `statistics` option, e.g. to preconfigure
197
+ * persistence or error snapshots, share it across sequential runs, or track extra fields via `state`.
198
+ */
199
+ constructor(options = {}) {
200
+ const { logIntervalSecs, logMessage, log, keyValueStore, persistenceOptions, saveErrorSnapshots, id, stateExtension, } = parseArgument(options, statisticsOptionsSchema);
201
+ this.id = id ?? String(Statistics.#id++);
202
+ this.#persistStateKey = `CRAWLEE_CRAWLER_STATISTICS_${this.id}`;
203
+ this.#log = (log ?? serviceLocator.getLogger()).child({ prefix: 'Statistics' });
204
+ this.errorTracker = new ErrorTracker({ ...errorTrackerConfig, saveErrorSnapshots });
205
+ this.errorTrackerRetry = new ErrorTracker({ ...errorTrackerConfig, saveErrorSnapshots });
206
+ this.#logIntervalMillis = logIntervalSecs * 1000;
207
+ this.#logMessage = logMessage;
208
+ this.#stateExtension = stateExtension;
209
+ this.#defaultStateExtension = this.#resolveDefaultStateExtension(this.#stateExtension);
210
+ this.#stateExtensionKeys = Object.keys(this.#defaultStateExtension());
211
+ for (const key of this.#stateExtensionKeys) {
212
+ if (key in this.#builtInDefaultState()) {
213
+ throw new Error(`The custom statistics field \`${String(key)}\` collides with a built-in one - it would shadow ` +
214
+ 'the value the crawler tracks. Rename it in `stateExtension`.');
215
+ }
216
+ }
217
+ // `calculate()` is late-bound on purpose - it is an override point, and a subclass's must be the one that runs.
218
+ this.#stateCodec = buildStatisticStateCodec({
219
+ statsId: this.id,
220
+ defaultState: () => this.#defaultState(),
221
+ calculate: () => this.calculate(),
222
+ });
223
+ this.#recoverableState = new RecoverableState({
224
+ persistStateKey: this.#persistStateKey,
225
+ persistenceEnabled: persistenceOptions.enable,
226
+ keyValueStore,
227
+ logger: this.#log,
228
+ defaultState: () => this.#defaultState(),
229
+ serialize: (state) => this.#serializeState(state),
230
+ deserialize: (persistedState) => this.#deserializeState(persistedState),
231
+ });
232
+ // initialize by "resetting"
233
+ this.reset();
234
+ }
235
+ /**
236
+ * Set the current statistic instance to pristine values.
237
+ *
238
+ * The persisted record is left alone - use {@link Statistics.resetStore} to clear that as well.
239
+ */
240
+ reset() {
241
+ this.errorTracker.reset();
242
+ this.errorTrackerRetry.reset();
243
+ this.#recoverableState.reset();
244
+ this.#requestsInProgress.clear();
245
+ }
246
+ /** The pristine state a new instance starts with and {@link Statistics.reset} restores. */
247
+ #defaultState() {
248
+ return {
249
+ ...this.#builtInDefaultState(),
250
+ ...this.#defaultStateExtension(),
251
+ };
252
+ }
253
+ /**
254
+ * The factory behind the custom half of the default state - it has to hand out a fresh object every time, or a
255
+ * `reset()` would write through to the defaults of the next one.
256
+ *
257
+ * With no `defaultState` given, the defaults are what `deserialize` makes of an empty record. That keeps a
258
+ * single declaration of the custom fields - a schema with a `.default()` per field is enough - and the defaults
259
+ * cannot then disagree with the conversion that has to accept them back.
260
+ */
261
+ #resolveDefaultStateExtension(options) {
262
+ const { defaultState, deserialize } = options;
263
+ if (typeof defaultState === 'function') {
264
+ return defaultState;
265
+ }
266
+ if (defaultState !== undefined) {
267
+ return () => structuredClone(defaultState);
268
+ }
269
+ if (deserialize === undefined) {
270
+ return () => ({});
271
+ }
272
+ return () => {
273
+ try {
274
+ return convertStateSync(deserialize, {}, this.#persistStateKey);
275
+ }
276
+ catch (error) {
277
+ throw new Error('Could not derive the default values of the custom statistics fields from `stateExtension.deserialize` - ' +
278
+ 'give every field a default, or declare `stateExtension.defaultState` explicitly.', { cause: error });
279
+ }
280
+ };
281
+ }
282
+ /** The built-in half of {@link Statistics.defaultState}, before any custom fields are merged over it. */
283
+ #builtInDefaultState() {
284
+ return {
285
+ requestsSucceeded: 0,
286
+ requestsFailed: 0,
287
+ requestsRetries: 0,
288
+ requestsFailedPerMinute: 0,
289
+ requestsSucceededPerMinute: 0,
290
+ requestMinDurationMillis: Infinity,
291
+ requestMaxDurationMillis: 0,
292
+ requestTotalFailedDurationMillis: 0,
293
+ requestTotalSucceededDurationMillis: 0,
294
+ crawlerStartedAt: null,
295
+ crawlerFinishedAt: null,
296
+ statsPersistedAt: null,
297
+ crawlerRuntimeMillis: 0,
298
+ requestsWithStatusCode: {},
299
+ // Aliases, not copies - the trackers keep writing into these objects.
300
+ errors: this.errorTracker.result,
301
+ retryErrors: this.errorTrackerRetry.result,
302
+ requestRetryHistogram: [],
303
+ instanceStart: Date.now(),
304
+ };
305
+ }
306
+ /**
307
+ * Clear the persisted statistics record, leaving the in-memory state alone.
308
+ *
309
+ * Throws while capturing - the next PERSIST_STATE event would write the record straight back.
310
+ */
311
+ async resetStore() {
312
+ await this.#recoverableState.resetStore();
313
+ }
314
+ /**
315
+ * Increments the status code counter.
316
+ */
317
+ registerStatusCode(code) {
318
+ const s = String(code);
319
+ if (this.state.requestsWithStatusCode[s] === undefined) {
320
+ this.state.requestsWithStatusCode[s] = 0;
321
+ }
322
+ this.state.requestsWithStatusCode[s]++;
323
+ }
324
+ /** @ignore */
325
+ recordRequestStart(id) {
326
+ let record = this.#requestsInProgress.get(id);
327
+ if (!record)
328
+ record = new RequestProcessingRecord();
329
+ record.run();
330
+ this.#requestsInProgress.set(id, record);
331
+ }
332
+ /** @ignore */
333
+ recordRequestSuccess(id, retryCount) {
334
+ const record = this.#requestsInProgress.get(id);
335
+ if (!record)
336
+ return;
337
+ const durationMillis = record.finish();
338
+ this.state.requestsSucceeded++;
339
+ this.state.requestTotalSucceededDurationMillis += durationMillis;
340
+ this.#saveRetryCountForRequest(retryCount);
341
+ if (durationMillis < this.state.requestMinDurationMillis)
342
+ this.state.requestMinDurationMillis = durationMillis;
343
+ if (durationMillis > this.state.requestMaxDurationMillis)
344
+ this.state.requestMaxDurationMillis = durationMillis;
345
+ this.#requestsInProgress.delete(id);
346
+ }
347
+ /** @ignore */
348
+ recordRequestFailure(id, retryCount) {
349
+ const record = this.#requestsInProgress.get(id);
350
+ if (!record)
351
+ return;
352
+ this.state.requestTotalFailedDurationMillis += record.finish();
353
+ this.state.requestsFailed++;
354
+ this.#saveRetryCountForRequest(retryCount);
355
+ this.#requestsInProgress.delete(id);
356
+ }
357
+ /**
358
+ * Discards a started request without affecting the succeeded/failed counters, e.g. when a request
359
+ * turns out to be skipped (robots.txt, enqueue strategy) after `recordRequestStart` was already
360
+ * called for it.
361
+ * @ignore
362
+ */
363
+ discardRequestRecord(id) {
364
+ this.#requestsInProgress.delete(id);
365
+ }
366
+ /**
367
+ * Calculate the current statistics
368
+ */
369
+ calculate() {
370
+ const { requestsFailed, requestsSucceeded, requestTotalFailedDurationMillis, requestTotalSucceededDurationMillis, } = this.state;
371
+ const totalMillis = Date.now() - this.state.instanceStart;
372
+ const totalMinutes = totalMillis / 1000 / 60;
373
+ return {
374
+ requestAvgFailedDurationMillis: Math.round(requestTotalFailedDurationMillis / requestsFailed) || Infinity,
375
+ requestAvgSucceededDurationMillis: Math.round(requestTotalSucceededDurationMillis / requestsSucceeded) || Infinity,
376
+ requestsSucceededPerMinute: Math.round(requestsSucceeded / totalMinutes) || 0,
377
+ requestsFailedPerMinute: Math.floor(requestsFailed / totalMinutes) || 0,
378
+ requestTotalDurationMillis: requestTotalSucceededDurationMillis + requestTotalFailedDurationMillis,
379
+ requestsTotal: requestsFailed + requestsSucceeded,
380
+ crawlerRuntimeMillis: totalMillis,
381
+ };
382
+ }
383
+ /**
384
+ * Initializes the key value store for persisting the statistics,
385
+ * displaying the current state in predefined intervals
386
+ */
387
+ async startCapturing() {
388
+ // A single instance drives one logging interval and one PERSIST_STATE listener, so a second concurrent
389
+ // capture (e.g. sharing one instance across crawlers running at once) would orphan the first. Fail loudly.
390
+ if (this.#logInterval) {
391
+ throw new Error('Statistics.startCapturing() was already called - this instance is already capturing.');
392
+ }
393
+ await this.#recoverableState.initialize();
394
+ // After the load, so that a restored record keeps the timestamp of the run it belongs to.
395
+ if (this.state.crawlerStartedAt === null) {
396
+ this.state.crawlerStartedAt = new Date();
397
+ }
398
+ this.#logInterval = setInterval(() => {
399
+ this.#log.info(this.#logMessage, {
400
+ ...this.calculate(),
401
+ retryHistogram: this.requestRetryHistogram,
402
+ });
403
+ }, this.#logIntervalMillis);
404
+ }
405
+ /**
406
+ * Stops logging and remove event listeners, then persist
407
+ */
408
+ async stopCapturing() {
409
+ this.#stopLogging();
410
+ this.state.crawlerFinishedAt = new Date();
411
+ await this.#recoverableState.teardown();
412
+ }
413
+ #saveRetryCountForRequest(retryCount) {
414
+ if (retryCount > 0)
415
+ this.state.requestsRetries++;
416
+ this.requestRetryHistogram[retryCount] ??= 0;
417
+ this.requestRetryHistogram[retryCount]++;
418
+ }
419
+ /**
420
+ * Persist internal state to the key value store.
421
+ *
422
+ * Statistics are bookkeeping - a store that refuses the write is worth a warning, not a failed crawl. The
423
+ * crawler calls this from its migration handler, where a rejection would go unhandled.
424
+ */
425
+ async persistState() {
426
+ await this.#recoverableState
427
+ .persistState()
428
+ .catch((error) => this.#log.warning(`Failed to persist the statistics to ${this.#persistStateKey}`, { error }));
429
+ }
430
+ /** Rebuilds the state from a persisted record. */
431
+ #deserializeState(persistedState) {
432
+ // The cast covers the custom fields, whose type is open here - and the record is an unvalidated blob off the
433
+ // key-value store either way, which is what the decode is for. Their keys are not in the schema, so the
434
+ // decode drops them; `#restoreStateExtension` is what brings them back.
435
+ const restored = z.safeDecode(this.#stateCodec, persistedState);
436
+ if (!restored.success) {
437
+ // Statistics are bookkeeping - a record that cannot be made sense of is worth a warning and a fresh
438
+ // start, not a failed crawl.
439
+ this.#log.warning('Received invalid state from Key-value store, starting the statistics from scratch.', {
440
+ persistStateKey: this.#persistStateKey,
441
+ issues: restored.error.issues,
442
+ });
443
+ return this.#defaultState();
444
+ }
445
+ this.#log.debug('Recreating state from KeyValueStore', { persistStateKey: this.#persistStateKey });
446
+ return { ...this.#defaultState(), ...restored.data, ...this.#restoreStateExtension(persistedState) };
447
+ }
448
+ /**
449
+ * The custom {@link StatisticsOptions.stateExtension|`stateExtension`} fields as they were persisted - the codec only rebuilds
450
+ * the built-in ones.
451
+ *
452
+ * Given a `deserialize`, the whole record goes through it, so a field the record does not carry - one declared
453
+ * after the record was written - comes back as whatever default the conversion gives it. Without one, the
454
+ * declared keys are copied over as they were persisted and a missing one keeps the default it already has.
455
+ */
456
+ #restoreStateExtension(persistedState) {
457
+ const { deserialize } = this.#stateExtension;
458
+ if (deserialize === undefined) {
459
+ const restored = {};
460
+ for (const key of this.#stateExtensionKeys) {
461
+ // The record is an unvalidated blob and there is no conversion to check it with, so this is the
462
+ // caller's word for it - the state ends up holding whatever was written. The two halves only line
463
+ // up at all because the fields are persisted as they are without a `serialize`.
464
+ const persistedValue = persistedState[key];
465
+ if (persistedValue !== undefined) {
466
+ restored[key] = persistedValue;
467
+ }
468
+ }
469
+ return restored;
470
+ }
471
+ try {
472
+ return convertStateSync(deserialize, persistedState, this.#persistStateKey);
473
+ }
474
+ catch (error) {
475
+ // Same policy as a built-in field that cannot be made sense of, but scoped to the custom ones - a
476
+ // corrupt counter of your own is no reason to throw away the crawler's.
477
+ this.#log.warning('Received invalid custom statistics fields from Key-value store, starting those from scratch.', { persistStateKey: this.#persistStateKey, error });
478
+ return {};
479
+ }
480
+ }
481
+ #stopLogging() {
482
+ if (this.#logInterval) {
483
+ clearInterval(this.#logInterval);
484
+ this.#logInterval = null;
485
+ }
486
+ }
487
+ /**
488
+ * Builds the record written to the key value store, merging in the derived aggregates so that a consumer
489
+ * reading the record does not have to reconstruct them.
490
+ */
491
+ #serializeState(state) {
492
+ const { builtIn, extension } = this.#splitState(state);
493
+ return {
494
+ ...z.encode(this.#stateCodec, builtIn),
495
+ ...this.#serializeStateExtension(extension),
496
+ };
497
+ }
498
+ /** The custom {@link StatisticsOptions.stateExtension|`stateExtension`} fields as they go into the record. */
499
+ #serializeStateExtension(extension) {
500
+ const { serialize } = this.#stateExtension;
501
+ if (serialize === undefined) {
502
+ return extension;
503
+ }
504
+ // Unlike the way back, a failure here throws: the value is the caller's own, and a record written from a
505
+ // state that does not match its own declaration is not worth having.
506
+ return convertStateSync(serialize, extension, this.#persistStateKey);
507
+ }
508
+ /** Separates the declared custom fields from the built-in ones, so that each half goes through its own conversion. */
509
+ #splitState(state) {
510
+ const builtIn = { ...state };
511
+ const extension = {};
512
+ for (const key of this.#stateExtensionKeys) {
513
+ extension[key] = state[key];
514
+ delete builtIn[key];
515
+ }
516
+ return { builtIn, extension };
517
+ }
518
+ /**
519
+ * Make this class serializable when called with `JSON.stringify(statsInstance)` directly
520
+ * or through `keyValueStore.setValue('KEY', statsInstance)`
521
+ */
522
+ toJSON() {
523
+ return this.#serializeState(this.state);
524
+ }
525
+ }
@@ -0,0 +1,86 @@
1
+ import type { EnqueueStrategyOption } from '@crawlee/core';
2
+ import { Request } from '@crawlee/core';
3
+ import type { Dictionary, RequestSchema } from '@crawlee/types';
4
+ export type SkippedRequestReason = 'robotsTxt' | 'limit' | 'enqueueLimit' | 'filters' | 'transform' | 'redirect' | 'depth' | 'manual';
5
+ export declare enum RequestState {
6
+ UNPROCESSED = 0,
7
+ BEFORE_NAV = 1,
8
+ AFTER_NAV = 2,
9
+ REQUEST_HANDLER = 3,
10
+ DONE = 4,
11
+ ERROR_HANDLER = 5,
12
+ ERROR = 6,
13
+ SKIPPED = 7
14
+ }
15
+ export interface PushErrorMessageOptions {
16
+ /**
17
+ * Only push the error message without stack trace when true.
18
+ * @default false
19
+ */
20
+ omitStack?: boolean;
21
+ }
22
+ /**
23
+ * The crawler's per-request state, persisted inside `userData.__crawlee` so every storage carries it as plain user
24
+ * data. The settings are written by the `Request` constructor from `RequestOptions`; `state` only by a running crawler.
25
+ * @internal
26
+ */
27
+ export interface CrawlingRequestData {
28
+ skipNavigation?: boolean;
29
+ crawlDepth?: number;
30
+ sessionId?: string;
31
+ maxRetries?: number;
32
+ enqueueStrategy?: EnqueueStrategyOption;
33
+ state?: RequestState;
34
+ }
35
+ /**
36
+ * A {@link Request} as seen by a crawler: the same stored record, with the crawler's own per-request state
37
+ * (`userData.__crawlee`) exposed as properties. This is what `request` is in every request handler.
38
+ *
39
+ * Requests fetched from a request manager are plain {@link Request}s; {@link BasicCrawler} rebuilds them
40
+ * as `CrawlingRequest`s before handing them to the pipeline.
41
+ * @category Sources
42
+ */
43
+ export declare class CrawlingRequest<UserData extends Dictionary = Dictionary> extends Request<UserData> {
44
+ #private;
45
+ static fromSchema<UserData extends Dictionary = Dictionary>(schema: RequestSchema): CrawlingRequest<UserData>;
46
+ /**
47
+ * Tells the crawler processing this request to skip the navigation and process the request directly.
48
+ *
49
+ * When this is set to `true`, the crawling context will not contain the results of the navigation
50
+ * (e.g. `response`, `body`, `contentType`, `$` or `request.loadedUrl`).
51
+ * Accessing these properties will throw a {@link NavigationSkippedError} at runtime.
52
+ */
53
+ get skipNavigation(): boolean;
54
+ set skipNavigation(value: boolean);
55
+ /**
56
+ * Depth of the request in the current crawl tree.
57
+ * Note that this is dependent on the crawler setup and might produce unexpected results when used with multiple crawlers.
58
+ */
59
+ get crawlDepth(): number;
60
+ set crawlDepth(value: number);
61
+ /** ID of a session to use for this request. When set, the crawler will fetch this session from the session pool instead of creating a new one. */
62
+ get sessionId(): string | undefined;
63
+ set sessionId(value: string | undefined);
64
+ /** Maximum number of retries for this request. Allows to override the global `maxRequestRetries` option of `BasicCrawler`. */
65
+ get maxRetries(): number | undefined;
66
+ set maxRetries(value: number | undefined);
67
+ /** Describes the request's current lifecycle state. */
68
+ get state(): RequestState;
69
+ set state(value: RequestState);
70
+ /** The strategy the request was enqueued under, if it came from `enqueueLinks`. @internal */
71
+ get enqueueStrategy(): EnqueueStrategyOption | undefined;
72
+ /**
73
+ * Stores information about an error that occurred during processing of this request.
74
+ *
75
+ * You should always use Error instances when throwing errors in JavaScript.
76
+ *
77
+ * Nevertheless, to improve the debugging experience when using third party libraries
78
+ * that may not always throw an Error instance, the function performs a type
79
+ * inspection of the passed argument and attempts to extract as much information
80
+ * as possible, since just throwing a bad type error makes any debugging rather difficult.
81
+ *
82
+ * @param errorOrMessage Error object or error message to be stored in the request.
83
+ * @param [options]
84
+ */
85
+ pushErrorMessage(errorOrMessage: unknown, options?: PushErrorMessageOptions): void;
86
+ }