@crawlee/core 4.0.0-beta.99 → 4.0.0-rc.0

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 (109) hide show
  1. package/autoscaling/autoscaled_pool.d.ts +3 -21
  2. package/autoscaling/autoscaled_pool.js +105 -97
  3. package/autoscaling/concurrency_system.d.ts +7 -22
  4. package/autoscaling/concurrency_system.js +112 -100
  5. package/autoscaling/cpu_load_signal.d.ts +1 -2
  6. package/autoscaling/cpu_load_signal.js +11 -10
  7. package/autoscaling/event_loop_load_signal.d.ts +1 -4
  8. package/autoscaling/event_loop_load_signal.js +18 -18
  9. package/autoscaling/index.d.ts +1 -1
  10. package/autoscaling/index.js +1 -1
  11. package/autoscaling/load_signal.d.ts +8 -7
  12. package/autoscaling/load_signal.js +14 -12
  13. package/autoscaling/memory_load_signal.d.ts +3 -12
  14. package/autoscaling/memory_load_signal.js +41 -41
  15. package/autoscaling/snapshotter.d.ts +7 -10
  16. package/autoscaling/snapshotter.js +18 -18
  17. package/autoscaling/{client_load_signal.d.ts → storage_backend_load_signal.d.ts} +14 -17
  18. package/autoscaling/{client_load_signal.js → storage_backend_load_signal.js} +27 -27
  19. package/autoscaling/system_status.d.ts +9 -11
  20. package/autoscaling/system_status.js +13 -13
  21. package/configuration.d.ts +16 -16
  22. package/configuration.js +6 -6
  23. package/crawlers/context_pipeline.js +6 -6
  24. package/crawlers/crawler_commons.d.ts +14 -112
  25. package/crawlers/crawler_commons.js +1 -107
  26. package/crawlers/error_snapshotter.d.ts +2 -4
  27. package/crawlers/error_snapshotter.js +5 -5
  28. package/crawlers/index.d.ts +1 -1
  29. package/crawlers/index.js +0 -1
  30. package/crawlers/statistics.d.ts +164 -45
  31. package/crawlers/statistics.js +339 -153
  32. package/debug.js +4 -4
  33. package/enqueue_links/enqueue_links.d.ts +51 -159
  34. package/enqueue_links/enqueue_links.js +38 -231
  35. package/enqueue_links/shared.d.ts +34 -24
  36. package/enqueue_links/shared.js +54 -36
  37. package/errors.d.ts +43 -12
  38. package/errors.js +48 -9
  39. package/events/event_manager.d.ts +2 -2
  40. package/events/event_manager.js +7 -6
  41. package/events/local_event_manager.d.ts +1 -1
  42. package/events/local_event_manager.js +5 -5
  43. package/http.d.ts +9 -0
  44. package/http.js +28 -0
  45. package/index.d.ts +1 -1
  46. package/index.js +1 -1
  47. package/log.js +5 -1
  48. package/memory-storage/memory-storage.d.ts +3 -11
  49. package/memory-storage/memory-storage.js +42 -48
  50. package/memory-storage/resource-clients/dataset.d.ts +1 -1
  51. package/memory-storage/resource-clients/dataset.js +8 -13
  52. package/memory-storage/resource-clients/key-value-store.d.ts +1 -1
  53. package/memory-storage/resource-clients/key-value-store.js +36 -38
  54. package/memory-storage/resource-clients/request-queue.d.ts +4 -23
  55. package/memory-storage/resource-clients/request-queue.js +68 -80
  56. package/owned_or_injected.d.ts +1 -3
  57. package/owned_or_injected.js +17 -17
  58. package/package.json +8 -9
  59. package/proxy_configuration.d.ts +1 -3
  60. package/proxy_configuration.js +18 -14
  61. package/recoverable_state.d.ts +80 -45
  62. package/recoverable_state.js +163 -75
  63. package/request.d.ts +3 -4
  64. package/request.js +57 -44
  65. package/router.d.ts +6 -9
  66. package/router.js +23 -23
  67. package/serialization.js +14 -13
  68. package/service_locator.d.ts +19 -10
  69. package/service_locator.js +57 -48
  70. package/session_pool/session.d.ts +3 -14
  71. package/session_pool/session.js +76 -74
  72. package/session_pool/session_pool.d.ts +6 -12
  73. package/session_pool/session_pool.js +85 -77
  74. package/storages/batched_adds.d.ts +37 -0
  75. package/storages/batched_adds.js +73 -0
  76. package/storages/dataset.d.ts +12 -1
  77. package/storages/dataset.js +133 -32
  78. package/storages/index.d.ts +2 -1
  79. package/storages/index.js +2 -1
  80. package/storages/key_value_store.d.ts +19 -4
  81. package/storages/key_value_store.js +204 -75
  82. package/storages/request_dedup_cache.d.ts +1 -2
  83. package/storages/request_dedup_cache.js +9 -9
  84. package/storages/request_list.d.ts +4 -23
  85. package/storages/request_list.js +103 -96
  86. package/storages/request_loader.d.ts +5 -0
  87. package/storages/request_manager_tandem.d.ts +1 -10
  88. package/storages/request_manager_tandem.js +27 -27
  89. package/storages/request_queue.d.ts +21 -18
  90. package/storages/request_queue.js +318 -177
  91. package/storages/sitemap_request_loader.d.ts +22 -70
  92. package/storages/sitemap_request_loader.js +122 -116
  93. package/storages/storage_instance_manager.d.ts +1 -2
  94. package/storages/storage_instance_manager.js +17 -17
  95. package/storages/storage_stats.d.ts +1 -1
  96. package/storages/storage_stats.js +4 -4
  97. package/storages/throttling_request_manager.d.ts +239 -0
  98. package/storages/throttling_request_manager.js +646 -0
  99. package/storages/transaction.d.ts +252 -0
  100. package/storages/transaction.js +251 -0
  101. package/storages/utils.d.ts +6 -3
  102. package/storages/utils.js +11 -2
  103. package/system-info/runtime.js +7 -7
  104. package/url.d.ts +9 -0
  105. package/url.js +11 -0
  106. package/validators.d.ts +22 -25
  107. package/validators.js +13 -25
  108. package/storages/access_checking.d.ts +0 -12
  109. package/storages/access_checking.js +0 -17
@@ -1,4 +1,5 @@
1
1
  import type { CrawleeLogger } from '../log.js';
2
+ import type { SyncStateConversion } from '../recoverable_state.js';
2
3
  import { KeyValueStore } from '../storages/key_value_store.js';
3
4
  import { ErrorTracker } from './error_tracker.js';
4
5
  /**
@@ -11,6 +12,68 @@ export interface PersistenceOptions {
11
12
  */
12
13
  enable?: boolean;
13
14
  }
15
+ /**
16
+ * The statistics surface a crawler depends on: recording per-request outcomes, tracking errors, and driving the
17
+ * capture lifecycle for a run. Injected via the crawler's `statistics` option, so a custom implementation can be
18
+ * plugged in without subclassing the crawler.
19
+ *
20
+ * `StateExtension` describes the custom fields tracked alongside the built-in {@link StatisticState} ones - see
21
+ * {@link StatisticsOptions.stateExtension}.
22
+ *
23
+ * The owned-only mutators the crawler uses to *own* a default it built - `reset()`/`resetStore()` - are deliberately
24
+ * absent: an injected instance is borrowed, and the crawler never wipes it. Those live on the concrete
25
+ * {@link Statistics} only.
26
+ *
27
+ * @category Crawlers
28
+ */
29
+ export interface IStatistics<StateExtension extends object = {}> {
30
+ /** Tracker for errors on the final retry of a request. */
31
+ readonly errorTracker: ErrorTracker;
32
+ /** Tracker for errors on retries prior to the final one. */
33
+ readonly errorTrackerRetry: ErrorTracker;
34
+ /** The live statistics state the crawler reads for status messages and the final summary. */
35
+ readonly state: StatisticState & StateExtension;
36
+ /** Retries histogram - index `i` holds the number of requests that finished after `i` retries. */
37
+ readonly requestRetryHistogram: number[];
38
+ /** Marks a request as started, so its duration can be measured on finish/fail. */
39
+ startJob(id: number | string): void;
40
+ /** Marks a started request as finished, updating the finished counters and durations. */
41
+ finishJob(id: number | string, retryCount: number): void;
42
+ /** Marks a started request as failed, updating the failed counters and durations. */
43
+ failJob(id: number | string, retryCount: number): void;
44
+ /** Drops a started request without counting it as finished or failed (e.g. skipped by robots.txt). */
45
+ discardJob(id: number | string): void;
46
+ /** Increments the counter for the given HTTP status code. */
47
+ registerStatusCode(code: number): void;
48
+ /** Computes the derived aggregates (averages, per-minute rates, totals) from the current state. */
49
+ calculate(): CalculatedStatistics;
50
+ /** Begins a capture window: loads any persisted state, subscribes to persistence events, starts periodic logging. */
51
+ startCapturing(): Promise<void>;
52
+ /** Ends the capture window: stops logging, unsubscribes, and persists the final state. */
53
+ stopCapturing(): Promise<void>;
54
+ /**
55
+ * Persists the current state to the key-value store. Optional - the crawler calls it on migration, but a backend
56
+ * with no persistence of its own can omit it.
57
+ */
58
+ persistState?(): Promise<void>;
59
+ }
60
+ /** The derived aggregates computed by {@link IStatistics.calculate} from the current {@link StatisticState}. */
61
+ export interface CalculatedStatistics {
62
+ /** Mean duration of a failed request, in milliseconds; `Infinity` when nothing has failed. */
63
+ requestAvgFailedDurationMillis: number;
64
+ /** Mean duration of a finished request, in milliseconds; `Infinity` when nothing has finished. */
65
+ requestAvgFinishedDurationMillis: number;
66
+ /** Requests finished per minute over the run so far. */
67
+ requestsFinishedPerMinute: number;
68
+ /** Requests failed per minute over the run so far. */
69
+ requestsFailedPerMinute: number;
70
+ /** Combined duration of all finished and failed requests, in milliseconds. */
71
+ requestTotalDurationMillis: number;
72
+ /** Total number of settled requests (finished plus failed). */
73
+ requestsTotal: number;
74
+ /** Wall-clock runtime since capturing started, in milliseconds. */
75
+ crawlerRuntimeMillis: number;
76
+ }
14
77
  /**
15
78
  * The statistics class provides an interface to collecting and logging run
16
79
  * statistics for requests.
@@ -19,9 +82,13 @@ export interface PersistenceOptions {
19
82
  * under the key `CRAWLEE_CRAWLER_STATISTICS_*`, persists between
20
83
  * migrations and abort/resurrect
21
84
  *
85
+ * Custom fields are tracked by passing {@link StatisticsOptions.stateExtension|`stateExtension`} - the extra fields are then part
86
+ * of {@link Statistics.state|`state`}, persisted and restored along with the built-in ones.
87
+ *
22
88
  * @category Crawlers
23
89
  */
24
- export declare class Statistics {
90
+ export declare class Statistics<StateExtension extends object = {}, PersistedStateExtension extends object = StateExtension> implements IStatistics<StateExtension> {
91
+ #private;
25
92
  private static id;
26
93
  /**
27
94
  * An error tracker for final retry errors.
@@ -35,38 +102,32 @@ export declare class Statistics {
35
102
  * Statistic instance id.
36
103
  */
37
104
  readonly id: string;
105
+ private readonly log;
38
106
  /**
39
107
  * Current statistic state used for doing calculations on {@link Statistics.calculate} calls
40
108
  */
41
- state: StatisticState;
109
+ get state(): StatisticState & StateExtension;
42
110
  /**
43
111
  * Contains the current retries histogram. Index 0 means 0 retries, index 2, 2 retries, and so on
44
112
  */
45
- readonly requestRetryHistogram: number[];
46
- protected keyValueStore?: KeyValueStore;
47
- protected readonly persistStateKey: string;
48
- private logIntervalMillis;
49
- private logMessage;
50
- private listener;
51
- private requestsInProgress;
52
- private readonly log;
53
- private instanceStart;
54
- private logInterval;
55
- private _events?;
56
- private persistenceOptions;
57
- private get events();
113
+ get requestRetryHistogram(): number[];
58
114
  /**
59
- * @internal
115
+ * Construct a statistics instance to pass to a crawler via its `statistics` option, e.g. to preconfigure
116
+ * persistence or error snapshots, share it across sequential runs, or track extra fields via `state`.
60
117
  */
61
- constructor(options?: StatisticsOptions);
118
+ constructor(options?: StatisticsOptions<StateExtension, PersistedStateExtension>);
62
119
  /**
63
- * Set the current statistic instance to pristine values
120
+ * Set the current statistic instance to pristine values.
121
+ *
122
+ * The persisted record is left alone - use {@link Statistics.resetStore} to clear that as well.
64
123
  */
65
124
  reset(): void;
66
125
  /**
67
- * @param options - Override the persistence options provided in the constructor
126
+ * Clear the persisted statistics record, leaving the in-memory state alone.
127
+ *
128
+ * Throws while capturing - the next PERSIST_STATE event would write the record straight back.
68
129
  */
69
- resetStore(options?: PersistenceOptions): Promise<void>;
130
+ resetStore(): Promise<void>;
70
131
  /**
71
132
  * Increments the status code counter.
72
133
  */
@@ -95,15 +156,7 @@ export declare class Statistics {
95
156
  /**
96
157
  * Calculate the current statistics
97
158
  */
98
- calculate(): {
99
- requestAvgFailedDurationMillis: number;
100
- requestAvgFinishedDurationMillis: number;
101
- requestsFinishedPerMinute: number;
102
- requestsFailedPerMinute: number;
103
- requestTotalDurationMillis: number;
104
- requestsTotal: number;
105
- crawlerRuntimeMillis: number;
106
- };
159
+ calculate(): CalculatedStatistics;
107
160
  /**
108
161
  * Initializes the key value store for persisting the statistics,
109
162
  * displaying the current state in predefined intervals
@@ -115,25 +168,22 @@ export declare class Statistics {
115
168
  stopCapturing(): Promise<void>;
116
169
  private saveRetryCountForJob;
117
170
  /**
118
- * Persist internal state to the key value store
119
- * @param options - Override the persistence options provided in the constructor
120
- */
121
- persistState(options?: PersistenceOptions): Promise<void>;
122
- /**
123
- * Loads the current statistic from the key value store if any
171
+ * Persist internal state to the key value store.
172
+ *
173
+ * Statistics are bookkeeping - a store that refuses the write is worth a warning, not a failed crawl. The
174
+ * crawler calls this from its migration handler, where a rejection would go unhandled.
124
175
  */
125
- protected maybeLoadStatistics(): Promise<void>;
126
- private teardown;
176
+ persistState(): Promise<void>;
127
177
  /**
128
178
  * Make this class serializable when called with `JSON.stringify(statsInstance)` directly
129
179
  * or through `keyValueStore.setValue('KEY', statsInstance)`
130
180
  */
131
- toJSON(): StatisticPersistedState;
181
+ toJSON(): StatisticPersistedState & PersistedStateExtension;
132
182
  }
133
183
  /**
134
184
  * Configuration for the {@link Statistics} instance used by the crawler
135
185
  */
136
- export interface StatisticsOptions {
186
+ export interface StatisticsOptions<StateExtension extends object = {}, PersistedStateExtension extends object = StateExtension> {
137
187
  /**
138
188
  * Interval in seconds to log the current statistics
139
189
  * @default 60
@@ -172,19 +222,81 @@ export interface StatisticsOptions {
172
222
  * if crawler creation order changes.
173
223
  */
174
224
  id?: string;
225
+ /**
226
+ * Custom fields to track alongside the built-in {@link StatisticState} ones. They become part of
227
+ * {@link Statistics.state|`state`} (typed as such), are persisted with the rest of the state, and are
228
+ * restored on migration or resurrect.
229
+ *
230
+ * ```ts
231
+ * const statistics = new Statistics({ stateExtension: { defaultState: { productsFound: 0 } } });
232
+ * statistics.state.productsFound++;
233
+ * ```
234
+ */
235
+ stateExtension?: StatisticStateExtensionOptions<StateExtension, PersistedStateExtension>;
175
236
  }
176
237
  /**
177
- * Format of the persisted stats
238
+ * How the custom fields of {@link StatisticsOptions.stateExtension} are initialized and converted to and from the
239
+ * persisted record - the same three things {@link RecoverableStateOptions} asks for, scoped to the custom half
240
+ * of the statistics state.
178
241
  */
179
- export interface StatisticPersistedState extends Omit<StatisticState, 'statsPersistedAt'> {
180
- requestRetryHistogram: number[];
242
+ export interface StatisticStateExtensionOptions<StateExtension extends object, PersistedStateExtension extends object = StateExtension> {
243
+ /**
244
+ * The values the fields start with, and the ones {@link Statistics.reset} restores. A plain value is
245
+ * deep-copied with `structuredClone` each time it is used; pass a factory for a state `structuredClone` cannot
246
+ * rebuild.
247
+ *
248
+ * Can be omitted when `deserialize` supplies its own defaults, which is then the single place the fields are
249
+ * declared - see the example on {@link StatisticStateExtensionOptions.deserialize|`deserialize`}.
250
+ */
251
+ defaultState?: StateExtension | (() => StateExtension);
252
+ /**
253
+ * Rebuilds the custom fields from the persisted record, and the place to validate them before trusting them.
254
+ * Receives the whole record, so it has to supply a value for every field - `.default()` in a schema, or
255
+ * {@link StatisticStateExtensionOptions.defaultState|`defaultState`} alongside a conversion that copes with
256
+ * a missing field itself.
257
+ *
258
+ * ```ts
259
+ * const statistics = new Statistics({
260
+ * stateExtension: { deserialize: z.object({ productsFound: z.number().default(0) }) },
261
+ * });
262
+ * ```
263
+ *
264
+ * Without it, the declared fields are restored as they were persisted - which is a record off the key-value
265
+ * store taken at its word, `productsFound` included in whatever type it happens to hold.
266
+ *
267
+ * A conversion that rejects the record costs the custom fields their persisted values (they start from the
268
+ * defaults, with a warning) and nothing else.
269
+ */
270
+ deserialize?: SyncStateConversion<unknown, StateExtension>;
271
+ /**
272
+ * Converts the custom fields to the JSON-serializable form they are persisted in. Not needed for fields that
273
+ * already are one - pair it with `deserialize` for the fields that are not.
274
+ */
275
+ serialize?: SyncStateConversion<StateExtension, PersistedStateExtension>;
276
+ }
277
+ /**
278
+ * Format of the persisted stats.
279
+ *
280
+ * The `null`s are `Infinity` on the way out - JSON has no infinity, so a record written before anything
281
+ * finished or failed carries a `null` in its place.
282
+ */
283
+ export interface StatisticPersistedState extends Omit<StatisticState, 'statsPersistedAt' | 'crawlerStartedAt' | 'crawlerFinishedAt' | 'requestMinDurationMillis' | 'requestsFailedPerMinute' | 'requestsFinishedPerMinute' | 'requestRetryHistogram' | 'instanceStart'> {
181
284
  statsId: string;
182
- requestAvgFailedDurationMillis: number;
183
- requestAvgFinishedDurationMillis: number;
285
+ requestsFailedPerMinute: number | null;
286
+ requestsFinishedPerMinute: number | null;
287
+ /** ISO strings - the live state keeps these as `Date`s. */
288
+ crawlerStartedAt: string | null;
289
+ crawlerFinishedAt: string | null;
290
+ statsPersistedAt: string;
291
+ requestMinDurationMillis: number | null;
292
+ /** A retry count that no request ever reached leaves a `null` here. */
293
+ requestRetryHistogram: (number | null)[];
294
+ requestAvgFailedDurationMillis: number | null;
295
+ requestAvgFinishedDurationMillis: number | null;
184
296
  requestTotalDurationMillis: number;
185
297
  requestsTotal: number;
298
+ /** {@link StatisticState.instanceStart} of the run that wrote the record. */
186
299
  crawlerLastStartTimestamp: number;
187
- statsPersistedAt: string;
188
300
  }
189
301
  /**
190
302
  * Contains the statistics state
@@ -206,4 +318,11 @@ export interface StatisticState {
206
318
  errors: Record<string, unknown>;
207
319
  retryErrors: Record<string, unknown>;
208
320
  requestsWithStatusCode: Record<string, number>;
321
+ /** Retries histogram - index `i` holds the number of requests that finished after `i` retries. */
322
+ requestRetryHistogram: number[];
323
+ /**
324
+ * When the current capture window started, as a `Date.now()` timestamp. Rebased on load so that the runtime
325
+ * reported by {@link Statistics.calculate} spans a migration rather than restarting from zero.
326
+ */
327
+ instanceStart: number;
209
328
  }