@crawlee/basic 4.0.0-beta.170 → 4.0.0-beta.171

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 (73) hide show
  1. package/index.d.ts +10 -0
  2. package/index.js +10 -0
  3. package/internals/autoscaling/autoscaled_pool.d.ts +196 -0
  4. package/internals/autoscaling/autoscaled_pool.js +385 -0
  5. package/internals/autoscaling/concurrency_system.d.ts +267 -0
  6. package/internals/autoscaling/concurrency_system.js +364 -0
  7. package/internals/autoscaling/cpu_load_signal.d.ts +43 -0
  8. package/internals/autoscaling/cpu_load_signal.js +46 -0
  9. package/internals/autoscaling/event_loop_load_signal.d.ts +51 -0
  10. package/internals/autoscaling/event_loop_load_signal.js +60 -0
  11. package/internals/autoscaling/index.d.ts +9 -0
  12. package/internals/autoscaling/index.js +9 -0
  13. package/internals/autoscaling/load_signal.d.ts +98 -0
  14. package/internals/autoscaling/load_signal.js +103 -0
  15. package/internals/autoscaling/memory_load_signal.d.ts +47 -0
  16. package/internals/autoscaling/memory_load_signal.js +104 -0
  17. package/internals/autoscaling/snapshotter.d.ts +84 -0
  18. package/internals/autoscaling/snapshotter.js +67 -0
  19. package/internals/autoscaling/storage_backend_load_signal.d.ts +56 -0
  20. package/internals/autoscaling/storage_backend_load_signal.js +73 -0
  21. package/internals/autoscaling/system_status.d.ts +122 -0
  22. package/internals/autoscaling/system_status.js +139 -0
  23. package/internals/autoscaling/weighted_avg.d.ts +5 -0
  24. package/internals/autoscaling/weighted_avg.js +14 -0
  25. package/internals/basic-crawler.d.ts +11 -2
  26. package/internals/basic-crawler.js +13 -1
  27. package/internals/cookie_utils.d.ts +44 -0
  28. package/internals/cookie_utils.js +122 -0
  29. package/internals/crawler-run.d.ts +3 -1
  30. package/internals/crawler-run.js +1 -1
  31. package/internals/crawlers/context_pipeline.d.ts +70 -0
  32. package/internals/crawlers/context_pipeline.js +122 -0
  33. package/internals/crawlers/crawler_commons.d.ts +193 -0
  34. package/internals/crawlers/crawler_commons.js +1 -0
  35. package/internals/crawlers/error_snapshotter.d.ts +57 -0
  36. package/internals/crawlers/error_snapshotter.js +117 -0
  37. package/internals/crawlers/error_tracker.d.ts +54 -0
  38. package/internals/crawlers/error_tracker.js +308 -0
  39. package/internals/crawlers/index.d.ts +5 -0
  40. package/internals/crawlers/index.js +4 -0
  41. package/internals/crawlers/internals/types.d.ts +7 -0
  42. package/internals/crawlers/internals/types.js +1 -0
  43. package/internals/crawlers/statistics.d.ts +318 -0
  44. package/internals/crawlers/statistics.js +525 -0
  45. package/internals/enqueue_links/enqueue_links.d.ts +152 -0
  46. package/internals/enqueue_links/enqueue_links.js +76 -0
  47. package/internals/enqueue_links/index.d.ts +2 -0
  48. package/internals/enqueue_links/index.js +2 -0
  49. package/internals/enqueue_links/shared.d.ts +98 -0
  50. package/internals/enqueue_links/shared.js +259 -0
  51. package/internals/errors.d.ts +58 -0
  52. package/internals/errors.js +72 -0
  53. package/internals/http.d.ts +9 -0
  54. package/internals/http.js +28 -0
  55. package/internals/router.d.ts +306 -0
  56. package/internals/router.js +310 -0
  57. package/internals/session_pool/consts.d.ts +3 -0
  58. package/internals/session_pool/consts.js +3 -0
  59. package/internals/session_pool/errors.d.ts +7 -0
  60. package/internals/session_pool/errors.js +11 -0
  61. package/internals/session_pool/fingerprint.d.ts +9 -0
  62. package/internals/session_pool/fingerprint.js +30 -0
  63. package/internals/session_pool/index.d.ts +4 -0
  64. package/internals/session_pool/index.js +4 -0
  65. package/internals/session_pool/session.d.ts +153 -0
  66. package/internals/session_pool/session.js +221 -0
  67. package/internals/session_pool/session_pool.d.ts +242 -0
  68. package/internals/session_pool/session_pool.js +429 -0
  69. package/internals/sitemap_request_loader.d.ts +196 -0
  70. package/internals/sitemap_request_loader.js +432 -0
  71. package/internals/throttling_request_manager.d.ts +217 -0
  72. package/internals/throttling_request_manager.js +829 -0
  73. package/package.json +11 -7
@@ -0,0 +1,318 @@
1
+ import type { CrawleeLogger, SyncStateConversion } from '@crawlee/core';
2
+ import { KeyValueStore } from '@crawlee/core';
3
+ import { ErrorTracker } from './error_tracker.js';
4
+ /**
5
+ * Persistence-related options to control how and when crawler's data gets persisted.
6
+ */
7
+ export interface PersistenceOptions {
8
+ /**
9
+ * Use this flag to disable or enable periodic persistence to key value store.
10
+ * @default true
11
+ */
12
+ enable?: boolean;
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 can be
17
+ * plugged in without subclassing the crawler.
18
+ *
19
+ * `StateExtension` describes the custom fields tracked alongside the built-in {@link StatisticState} ones - see
20
+ * {@link StatisticsOptions.stateExtension}.
21
+ *
22
+ * The owned-only mutators the crawler uses to *own* a default it built - `reset()`/`resetStore()` - are deliberately
23
+ * absent: an injected instance is borrowed, and the crawler never wipes it. Those live on the concrete
24
+ * {@link Statistics} only.
25
+ *
26
+ * @category Crawlers
27
+ */
28
+ export interface IStatistics<StateExtension extends object = {}> {
29
+ /** Tracker for errors on the final retry of a request. */
30
+ readonly errorTracker: ErrorTracker;
31
+ /** Tracker for errors on retries prior to the final one. */
32
+ readonly errorTrackerRetry: ErrorTracker;
33
+ /** The live statistics state the crawler reads for status messages and the final summary. */
34
+ readonly state: StatisticState & StateExtension;
35
+ /** Retries histogram - index `i` holds the number of requests that settled after `i` retries. */
36
+ readonly requestRetryHistogram: number[];
37
+ /** Marks a request as started, so its duration can be measured on success/failure. */
38
+ recordRequestStart(id: number | string): void;
39
+ /** Marks a started request as succeeded, updating the succeeded counters and durations. */
40
+ recordRequestSuccess(id: number | string, retryCount: number): void;
41
+ /** Marks a started request as failed, updating the failed counters and durations. */
42
+ recordRequestFailure(id: number | string, retryCount: number): void;
43
+ /** Drops a started request without counting it as succeeded or failed (e.g. skipped by robots.txt). */
44
+ discardRequestRecord(id: number | string): void;
45
+ /** Increments the counter for the given HTTP status code. */
46
+ registerStatusCode(code: number): void;
47
+ /** Computes the derived aggregates (averages, per-minute rates, totals) from the current state. */
48
+ calculate(): CalculatedStatistics;
49
+ /** Begins a capture window: loads any persisted state, subscribes to persistence events, starts periodic logging. */
50
+ startCapturing(): Promise<void>;
51
+ /** Ends the capture window: stops logging, unsubscribes, and persists the final state. */
52
+ stopCapturing(): Promise<void>;
53
+ /**
54
+ * Persists the current state to the key-value store. Optional - the crawler calls it on migration, but a backend
55
+ * with no persistence of its own can omit it.
56
+ */
57
+ persistState?(): Promise<void>;
58
+ }
59
+ /** The derived aggregates computed by {@link IStatistics.calculate} from the current {@link StatisticState}. */
60
+ export interface CalculatedStatistics {
61
+ /** Mean duration of a failed request, in milliseconds; `Infinity` when nothing has failed. */
62
+ requestAvgFailedDurationMillis: number;
63
+ /** Mean duration of a succeeded request, in milliseconds; `Infinity` when nothing has succeeded. */
64
+ requestAvgSucceededDurationMillis: number;
65
+ /** Requests succeeded per minute over the run so far. */
66
+ requestsSucceededPerMinute: number;
67
+ /** Requests failed per minute over the run so far. */
68
+ requestsFailedPerMinute: number;
69
+ /** Combined duration of all succeeded and failed requests, in milliseconds. */
70
+ requestTotalDurationMillis: number;
71
+ /** Total number of settled requests (succeeded plus failed). */
72
+ requestsTotal: number;
73
+ /** Wall-clock runtime since capturing started, in milliseconds. */
74
+ crawlerRuntimeMillis: number;
75
+ }
76
+ /**
77
+ * The statistics class provides an interface to collecting and logging run
78
+ * statistics for requests.
79
+ *
80
+ * All statistic information is saved on key value store
81
+ * under the key `CRAWLEE_CRAWLER_STATISTICS_*`, persists between
82
+ * migrations and abort/resurrect
83
+ *
84
+ * Custom fields are tracked by passing {@link StatisticsOptions.stateExtension|`stateExtension`} - the extra fields are then part
85
+ * of {@link Statistics.state|`state`}, persisted and restored along with the built-in ones.
86
+ *
87
+ * @category Crawlers
88
+ */
89
+ export declare class Statistics<StateExtension extends object = {}, PersistedStateExtension extends object = StateExtension> implements IStatistics<StateExtension> {
90
+ #private;
91
+ /**
92
+ * An error tracker for final retry errors.
93
+ */
94
+ readonly errorTracker: ErrorTracker;
95
+ /**
96
+ * An error tracker for retry errors prior to the final retry.
97
+ */
98
+ readonly errorTrackerRetry: ErrorTracker;
99
+ /**
100
+ * Statistic instance id.
101
+ */
102
+ readonly id: string;
103
+ private readonly log;
104
+ /**
105
+ * Current statistic state used for doing calculations on {@link Statistics.calculate} calls
106
+ */
107
+ get state(): StatisticState & StateExtension;
108
+ /**
109
+ * Contains the current retries histogram. Index 0 means 0 retries, index 2, 2 retries, and so on
110
+ */
111
+ get requestRetryHistogram(): number[];
112
+ /**
113
+ * Construct a statistics instance to pass to a crawler via its `statistics` option, e.g. to preconfigure
114
+ * persistence or error snapshots, share it across sequential runs, or track extra fields via `state`.
115
+ */
116
+ constructor(options?: StatisticsOptions<StateExtension, PersistedStateExtension>);
117
+ /**
118
+ * Set the current statistic instance to pristine values.
119
+ *
120
+ * The persisted record is left alone - use {@link Statistics.resetStore} to clear that as well.
121
+ */
122
+ reset(): void;
123
+ /**
124
+ * Clear the persisted statistics record, leaving the in-memory state alone.
125
+ *
126
+ * Throws while capturing - the next PERSIST_STATE event would write the record straight back.
127
+ */
128
+ resetStore(): Promise<void>;
129
+ /**
130
+ * Increments the status code counter.
131
+ */
132
+ registerStatusCode(code: number): void;
133
+ /** @ignore */
134
+ recordRequestStart(id: number | string): void;
135
+ /** @ignore */
136
+ recordRequestSuccess(id: number | string, retryCount: number): void;
137
+ /** @ignore */
138
+ recordRequestFailure(id: number | string, retryCount: number): void;
139
+ /**
140
+ * Discards a started request without affecting the succeeded/failed counters, e.g. when a request
141
+ * turns out to be skipped (robots.txt, enqueue strategy) after `recordRequestStart` was already
142
+ * called for it.
143
+ * @ignore
144
+ */
145
+ discardRequestRecord(id: number | string): void;
146
+ /**
147
+ * Calculate the current statistics
148
+ */
149
+ calculate(): CalculatedStatistics;
150
+ /**
151
+ * Initializes the key value store for persisting the statistics,
152
+ * displaying the current state in predefined intervals
153
+ */
154
+ startCapturing(): Promise<void>;
155
+ /**
156
+ * Stops logging and remove event listeners, then persist
157
+ */
158
+ stopCapturing(): Promise<void>;
159
+ private saveRetryCountForRequest;
160
+ /**
161
+ * Persist internal state to the key value store.
162
+ *
163
+ * Statistics are bookkeeping - a store that refuses the write is worth a warning, not a failed crawl. The
164
+ * crawler calls this from its migration handler, where a rejection would go unhandled.
165
+ */
166
+ persistState(): Promise<void>;
167
+ /**
168
+ * Make this class serializable when called with `JSON.stringify(statsInstance)` directly
169
+ * or through `keyValueStore.setValue('KEY', statsInstance)`
170
+ */
171
+ toJSON(): StatisticPersistedState & PersistedStateExtension;
172
+ }
173
+ /**
174
+ * Configuration for the {@link Statistics} instance used by the crawler
175
+ */
176
+ export interface StatisticsOptions<StateExtension extends object = {}, PersistedStateExtension extends object = StateExtension> {
177
+ /**
178
+ * Interval in seconds to log the current statistics
179
+ * @default 60
180
+ */
181
+ logIntervalSecs?: number;
182
+ /**
183
+ * Message to log with the current statistics
184
+ * @default 'Statistics'
185
+ */
186
+ logMessage?: string;
187
+ /**
188
+ * Parent logger instance, the statistics will create a child logger from this.
189
+ * @default crawler.log
190
+ */
191
+ log?: CrawleeLogger;
192
+ /**
193
+ * Key value store instance to persist the statistics.
194
+ * If not provided, the default one will be used when capturing starts
195
+ */
196
+ keyValueStore?: KeyValueStore;
197
+ /**
198
+ * Control how and when to persist the statistics.
199
+ */
200
+ persistenceOptions?: PersistenceOptions;
201
+ /**
202
+ * Save HTML snapshot (and a screenshot if possible) when an error occurs.
203
+ * @default false
204
+ */
205
+ saveErrorSnapshots?: boolean;
206
+ /**
207
+ * A unique identifier for this statistics instance. This ID is used for persistence
208
+ * to the key value store, ensuring the same statistics can be loaded after script restarts.
209
+ *
210
+ * If not provided, an auto-incremented ID will be used for backward compatibility.
211
+ * This means statistics may not persist correctly across script restarts
212
+ * if crawler creation order changes.
213
+ */
214
+ id?: string;
215
+ /**
216
+ * Custom fields to track alongside the built-in {@link StatisticState} ones. They become part of
217
+ * {@link Statistics.state|`state`} (typed as such), are persisted with the rest of the state, and are
218
+ * restored on migration or resurrect.
219
+ *
220
+ * ```ts
221
+ * const statistics = new Statistics({ stateExtension: { defaultState: { productsFound: 0 } } });
222
+ * statistics.state.productsFound++;
223
+ * ```
224
+ */
225
+ stateExtension?: StatisticStateExtensionOptions<StateExtension, PersistedStateExtension>;
226
+ }
227
+ /**
228
+ * How the custom fields of {@link StatisticsOptions.stateExtension} are initialized and converted to and from the
229
+ * persisted record - the same three things {@link RecoverableStateOptions} asks for, scoped to the custom half
230
+ * of the statistics state.
231
+ */
232
+ export interface StatisticStateExtensionOptions<StateExtension extends object, PersistedStateExtension extends object = StateExtension> {
233
+ /**
234
+ * The values the fields start with, and the ones {@link Statistics.reset} restores. A plain value is
235
+ * deep-copied with `structuredClone` each time it is used; pass a factory for a state `structuredClone` cannot
236
+ * rebuild.
237
+ *
238
+ * Can be omitted when `deserialize` supplies its own defaults, which is then the single place the fields are
239
+ * declared - see the example on {@link StatisticStateExtensionOptions.deserialize|`deserialize`}.
240
+ */
241
+ defaultState?: StateExtension | (() => StateExtension);
242
+ /**
243
+ * Rebuilds the custom fields from the persisted record, and the place to validate them before trusting them.
244
+ * Receives the whole record, so it has to supply a value for every field - `.default()` in a schema, or
245
+ * {@link StatisticStateExtensionOptions.defaultState|`defaultState`} alongside a conversion that copes with
246
+ * a missing field itself.
247
+ *
248
+ * ```ts
249
+ * const statistics = new Statistics({
250
+ * stateExtension: { deserialize: z.object({ productsFound: z.number().default(0) }) },
251
+ * });
252
+ * ```
253
+ *
254
+ * Without it, the declared fields are restored as they were persisted - which is a record off the key-value
255
+ * store taken at its word, `productsFound` included in whatever type it happens to hold.
256
+ *
257
+ * A conversion that rejects the record costs the custom fields their persisted values (they start from the
258
+ * defaults, with a warning) and nothing else.
259
+ */
260
+ deserialize?: SyncStateConversion<unknown, StateExtension>;
261
+ /**
262
+ * Converts the custom fields to the JSON-serializable form they are persisted in. Not needed for fields that
263
+ * already are one - pair it with `deserialize` for the fields that are not.
264
+ */
265
+ serialize?: SyncStateConversion<StateExtension, PersistedStateExtension>;
266
+ }
267
+ /**
268
+ * Format of the persisted stats.
269
+ *
270
+ * The `null`s are `Infinity` on the way out - JSON has no infinity, so a record written before anything
271
+ * succeeded or failed carries a `null` in its place.
272
+ */
273
+ export interface StatisticPersistedState extends Omit<StatisticState, 'statsPersistedAt' | 'crawlerStartedAt' | 'crawlerFinishedAt' | 'requestMinDurationMillis' | 'requestsFailedPerMinute' | 'requestsSucceededPerMinute' | 'requestRetryHistogram' | 'instanceStart'> {
274
+ statsId: string;
275
+ requestsFailedPerMinute: number | null;
276
+ requestsSucceededPerMinute: number | null;
277
+ /** ISO strings - the live state keeps these as `Date`s. */
278
+ crawlerStartedAt: string | null;
279
+ crawlerFinishedAt: string | null;
280
+ statsPersistedAt: string;
281
+ requestMinDurationMillis: number | null;
282
+ /** A retry count that no request ever reached leaves a `null` here. */
283
+ requestRetryHistogram: (number | null)[];
284
+ requestAvgFailedDurationMillis: number | null;
285
+ requestAvgSucceededDurationMillis: number | null;
286
+ requestTotalDurationMillis: number;
287
+ requestsTotal: number;
288
+ /** {@link StatisticState.instanceStart} of the run that wrote the record. */
289
+ crawlerLastStartTimestamp: number;
290
+ }
291
+ /**
292
+ * Contains the statistics state
293
+ */
294
+ export interface StatisticState {
295
+ requestsSucceeded: number;
296
+ requestsFailed: number;
297
+ requestsRetries: number;
298
+ requestsFailedPerMinute: number;
299
+ requestsSucceededPerMinute: number;
300
+ requestMinDurationMillis: number;
301
+ requestMaxDurationMillis: number;
302
+ requestTotalFailedDurationMillis: number;
303
+ requestTotalSucceededDurationMillis: number;
304
+ crawlerStartedAt: Date | string | null;
305
+ crawlerFinishedAt: Date | string | null;
306
+ crawlerRuntimeMillis: number;
307
+ statsPersistedAt: Date | string | null;
308
+ errors: Record<string, unknown>;
309
+ retryErrors: Record<string, unknown>;
310
+ requestsWithStatusCode: Record<string, number>;
311
+ /** Retries histogram - index `i` holds the number of requests that settled after `i` retries. */
312
+ requestRetryHistogram: number[];
313
+ /**
314
+ * When the current capture window started, as a `Date.now()` timestamp. Rebased on load so that the runtime
315
+ * reported by {@link Statistics.calculate} spans a migration rather than restarting from zero.
316
+ */
317
+ instanceStart: number;
318
+ }