@crawlee/core 4.0.0-beta.101 → 4.0.0-beta.103

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.
@@ -25,9 +25,7 @@ interface ErrorSnapshot {
25
25
  * ```ts
26
26
  * const crawler = new BasicCrawler({
27
27
  * // ...
28
- * statisticsOptions: {
29
- * saveErrorSnapshots: true,
30
- * },
28
+ * statistics: new Statistics({ saveErrorSnapshots: true }),
31
29
  * });
32
30
  * ```
33
31
  */
@@ -7,9 +7,7 @@ import crypto from 'node:crypto';
7
7
  * ```ts
8
8
  * const crawler = new BasicCrawler({
9
9
  * // ...
10
- * statisticsOptions: {
11
- * saveErrorSnapshots: true,
12
- * },
10
+ * statistics: new Statistics({ saveErrorSnapshots: true }),
13
11
  * });
14
12
  * ```
15
13
  */
@@ -11,6 +11,65 @@ export interface PersistenceOptions {
11
11
  */
12
12
  enable?: boolean;
13
13
  }
14
+ /**
15
+ * The statistics surface a crawler depends on: recording per-request outcomes, tracking errors, and driving the
16
+ * capture lifecycle for a run. Injected via the crawler's `statistics` option, so a custom implementation (or a
17
+ * {@link Statistics} subclass tracking extra fields) can be plugged in without subclassing the crawler.
18
+ *
19
+ * The owned-only mutators the crawler uses to *own* a default it built - `reset()`/`resetStore()` - are deliberately
20
+ * absent: an injected instance is borrowed, and the crawler never wipes it. Those live on the concrete
21
+ * {@link Statistics} only.
22
+ *
23
+ * @category Crawlers
24
+ */
25
+ export interface IStatistics {
26
+ /** Tracker for errors on the final retry of a request. */
27
+ readonly errorTracker: ErrorTracker;
28
+ /** Tracker for errors on retries prior to the final one. */
29
+ readonly errorTrackerRetry: ErrorTracker;
30
+ /** The live statistics state the crawler reads for status messages and the final summary. */
31
+ readonly state: StatisticState;
32
+ /** Retries histogram - index `i` holds the number of requests that finished after `i` retries. */
33
+ readonly requestRetryHistogram: number[];
34
+ /** Marks a request as started, so its duration can be measured on finish/fail. */
35
+ startJob(id: number | string): void;
36
+ /** Marks a started request as finished, updating the finished counters and durations. */
37
+ finishJob(id: number | string, retryCount: number): void;
38
+ /** Marks a started request as failed, updating the failed counters and durations. */
39
+ failJob(id: number | string, retryCount: number): void;
40
+ /** Drops a started request without counting it as finished or failed (e.g. skipped by robots.txt). */
41
+ discardJob(id: number | string): void;
42
+ /** Increments the counter for the given HTTP status code. */
43
+ registerStatusCode(code: number): void;
44
+ /** Computes the derived aggregates (averages, per-minute rates, totals) from the current state. */
45
+ calculate(): CalculatedStatistics;
46
+ /** Begins a capture window: loads any persisted state, subscribes to persistence events, starts periodic logging. */
47
+ startCapturing(): Promise<void>;
48
+ /** Ends the capture window: stops logging, unsubscribes, and persists the final state. */
49
+ stopCapturing(): Promise<void>;
50
+ /**
51
+ * Persists the current state to the key-value store. Optional - the crawler calls it on migration, but a backend
52
+ * with no persistence of its own can omit it.
53
+ */
54
+ persistState?(options?: PersistenceOptions): Promise<void>;
55
+ }
56
+ /** The derived aggregates computed by {@link IStatistics.calculate} from the current {@link StatisticState}. */
57
+ export interface CalculatedStatistics {
58
+ /** Mean duration of a failed request, in milliseconds; `Infinity` when nothing has failed. */
59
+ requestAvgFailedDurationMillis: number;
60
+ /** Mean duration of a finished request, in milliseconds; `Infinity` when nothing has finished. */
61
+ requestAvgFinishedDurationMillis: number;
62
+ /** Requests finished per minute over the run so far. */
63
+ requestsFinishedPerMinute: number;
64
+ /** Requests failed per minute over the run so far. */
65
+ requestsFailedPerMinute: number;
66
+ /** Combined duration of all finished and failed requests, in milliseconds. */
67
+ requestTotalDurationMillis: number;
68
+ /** Total number of settled requests (finished plus failed). */
69
+ requestsTotal: number;
70
+ /** Wall-clock runtime since capturing started, in milliseconds. */
71
+ crawlerRuntimeMillis: number;
72
+ }
14
73
  /**
15
74
  * The statistics class provides an interface to collecting and logging run
16
75
  * statistics for requests.
@@ -21,7 +80,7 @@ export interface PersistenceOptions {
21
80
  *
22
81
  * @category Crawlers
23
82
  */
24
- export declare class Statistics {
83
+ export declare class Statistics implements IStatistics {
25
84
  private static id;
26
85
  /**
27
86
  * An error tracker for final retry errors.
@@ -56,7 +115,8 @@ export declare class Statistics {
56
115
  private persistenceOptions;
57
116
  private get events();
58
117
  /**
59
- * @internal
118
+ * Construct a statistics instance to pass to a crawler via its `statistics` option, e.g. to preconfigure
119
+ * persistence or error snapshots, share it across sequential runs, or subclass it to track extra fields.
60
120
  */
61
121
  constructor(options?: StatisticsOptions);
62
122
  /**
@@ -95,15 +155,7 @@ export declare class Statistics {
95
155
  /**
96
156
  * Calculate the current statistics
97
157
  */
98
- calculate(): {
99
- requestAvgFailedDurationMillis: number;
100
- requestAvgFinishedDurationMillis: number;
101
- requestsFinishedPerMinute: number;
102
- requestsFailedPerMinute: number;
103
- requestTotalDurationMillis: number;
104
- requestsTotal: number;
105
- crawlerRuntimeMillis: number;
106
- };
158
+ calculate(): CalculatedStatistics;
107
159
  /**
108
160
  * Initializes the key value store for persisting the statistics,
109
161
  * displaying the current state in predefined intervals
@@ -74,7 +74,8 @@ export class Statistics {
74
74
  return this._events;
75
75
  }
76
76
  /**
77
- * @internal
77
+ * Construct a statistics instance to pass to a crawler via its `statistics` option, e.g. to preconfigure
78
+ * persistence or error snapshots, share it across sequential runs, or subclass it to track extra fields.
78
79
  */
79
80
  constructor(options = {}) {
80
81
  ow(options, ow.object.exactShape({
@@ -225,6 +226,11 @@ export class Statistics {
225
226
  * displaying the current state in predefined intervals
226
227
  */
227
228
  async startCapturing() {
229
+ // A single instance drives one logging interval and one PERSIST_STATE listener, so a second concurrent
230
+ // capture (e.g. sharing one instance across crawlers running at once) would orphan the first. Fail loudly.
231
+ if (this.logInterval) {
232
+ throw new Error('Statistics.startCapturing() was already called - this instance is already capturing.');
233
+ }
228
234
  this.keyValueStore ??= await KeyValueStore.open(null, { configuration: serviceLocator.getConfiguration() });
229
235
  if (this.state.crawlerStartedAt === null) {
230
236
  this.state.crawlerStartedAt = new Date();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crawlee/core",
3
- "version": "4.0.0-beta.101",
3
+ "version": "4.0.0-beta.103",
4
4
  "description": "The scalable web crawling and scraping library for JavaScript/Node.js. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.",
5
5
  "engines": {
6
6
  "node": ">=22.0.0"
@@ -52,9 +52,9 @@
52
52
  "@apify/log": "^2.5.18",
53
53
  "@apify/timeout": "^0.4.4",
54
54
  "@apify/utilities": "^2.15.5",
55
- "@crawlee/fs-storage": "4.0.0-beta.101",
56
- "@crawlee/types": "4.0.0-beta.101",
57
- "@crawlee/utils": "4.0.0-beta.101",
55
+ "@crawlee/fs-storage": "4.0.0-beta.103",
56
+ "@crawlee/types": "4.0.0-beta.103",
57
+ "@crawlee/utils": "4.0.0-beta.103",
58
58
  "@sapphire/async-queue": "^1.5.5",
59
59
  "@sapphire/shapeshift": "^4.0.0",
60
60
  "@vladfrangu/async_event_emitter": "^2.4.6",
@@ -78,5 +78,5 @@
78
78
  }
79
79
  }
80
80
  },
81
- "gitHead": "1fd886ee601c053d6fa8cada24b751f9cbe0a539"
81
+ "gitHead": "fe5d0ae11067683e27a2d17b4edd226ccf112cf5"
82
82
  }