@crawlee/core 4.0.0-rc.0 → 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.
- package/README.md +1 -1
- package/configuration.d.ts +15 -46
- package/configuration.js +8 -20
- package/errors.d.ts +12 -53
- package/errors.js +13 -66
- package/events/index.d.ts +1 -0
- package/events/local_event_manager.d.ts +0 -7
- package/events/local_event_manager.js +8 -8
- package/events/system_info.d.ts +38 -0
- package/index.d.ts +2 -8
- package/index.js +4 -8
- package/internal.d.ts +8 -0
- package/internal.js +9 -0
- package/log.d.ts +10 -11
- package/log.js +53 -25
- package/memory-storage/memory-storage.d.ts +12 -7
- package/memory-storage/memory-storage.js +45 -17
- package/memory-storage/resource-clients/dataset.d.ts +0 -5
- package/memory-storage/resource-clients/dataset.js +17 -20
- package/memory-storage/resource-clients/key-value-store.d.ts +0 -9
- package/memory-storage/resource-clients/key-value-store.js +11 -33
- package/memory-storage/resource-clients/request-queue.d.ts +0 -22
- package/memory-storage/resource-clients/request-queue.js +57 -53
- package/package.json +16 -18
- package/proxy_configuration.d.ts +20 -23
- package/proxy_configuration.js +18 -12
- package/recoverable_state.d.ts +28 -6
- package/recoverable_state.js +51 -14
- package/request.d.ts +18 -104
- package/request.js +41 -220
- package/serialization.js +3 -3
- package/service_locator.d.ts +3 -0
- package/service_locator.js +2 -0
- package/storages/dataset.d.ts +9 -15
- package/storages/dataset.js +22 -14
- package/storages/index.d.ts +3 -4
- package/storages/index.js +1 -4
- package/storages/key_value_store.d.ts +12 -46
- package/storages/key_value_store.js +31 -47
- package/storages/key_value_store_codec.js +6 -11
- package/storages/request_dedup_cache.d.ts +0 -2
- package/storages/request_dedup_cache.js +8 -8
- package/storages/request_list.d.ts +6 -82
- package/storages/request_list.js +175 -179
- package/storages/request_loader.d.ts +48 -22
- package/storages/request_loader.js +36 -1
- package/storages/request_manager.d.ts +86 -0
- package/storages/request_manager_tandem.d.ts +13 -28
- package/storages/request_manager_tandem.js +46 -43
- package/storages/request_queue.d.ts +19 -49
- package/storages/request_queue.js +92 -88
- package/storages/storage_instance_manager.d.ts +1 -2
- package/storages/storage_instance_manager.js +4 -4
- package/storages/transaction.d.ts +27 -9
- package/storages/transaction.js +56 -11
- package/storages/utils.d.ts +2 -2
- package/validators.d.ts +3 -2
- package/validators.js +3 -2
- package/autoscaling/autoscaled_pool.d.ts +0 -195
- package/autoscaling/autoscaled_pool.js +0 -386
- package/autoscaling/concurrency_system.d.ts +0 -268
- package/autoscaling/concurrency_system.js +0 -362
- package/autoscaling/cpu_load_signal.d.ts +0 -43
- package/autoscaling/cpu_load_signal.js +0 -47
- package/autoscaling/event_loop_load_signal.d.ts +0 -51
- package/autoscaling/event_loop_load_signal.js +0 -60
- package/autoscaling/index.d.ts +0 -9
- package/autoscaling/index.js +0 -9
- package/autoscaling/load_signal.d.ts +0 -100
- package/autoscaling/load_signal.js +0 -105
- package/autoscaling/memory_load_signal.d.ts +0 -47
- package/autoscaling/memory_load_signal.js +0 -106
- package/autoscaling/snapshotter.d.ts +0 -84
- package/autoscaling/snapshotter.js +0 -67
- package/autoscaling/storage_backend_load_signal.d.ts +0 -56
- package/autoscaling/storage_backend_load_signal.js +0 -73
- package/autoscaling/system_status.d.ts +0 -159
- package/autoscaling/system_status.js +0 -139
- package/autoscaling/weighted_avg.d.ts +0 -5
- package/autoscaling/weighted_avg.js +0 -14
- package/cookie_utils.d.ts +0 -44
- package/cookie_utils.js +0 -122
- package/crawlers/context_pipeline.d.ts +0 -70
- package/crawlers/context_pipeline.js +0 -122
- package/crawlers/crawler_commons.d.ts +0 -159
- package/crawlers/error_snapshotter.d.ts +0 -57
- package/crawlers/error_snapshotter.js +0 -117
- package/crawlers/error_tracker.d.ts +0 -54
- package/crawlers/error_tracker.js +0 -308
- package/crawlers/index.d.ts +0 -5
- package/crawlers/index.js +0 -4
- package/crawlers/internals/types.d.ts +0 -7
- package/crawlers/internals/types.js +0 -1
- package/crawlers/statistics.d.ts +0 -328
- package/crawlers/statistics.js +0 -536
- package/enqueue_links/enqueue_links.d.ts +0 -156
- package/enqueue_links/enqueue_links.js +0 -78
- package/enqueue_links/index.d.ts +0 -2
- package/enqueue_links/index.js +0 -2
- package/enqueue_links/shared.d.ts +0 -93
- package/enqueue_links/shared.js +0 -239
- package/http.d.ts +0 -9
- package/http.js +0 -28
- package/router.d.ts +0 -306
- package/router.js +0 -309
- package/session_pool/consts.d.ts +0 -3
- package/session_pool/consts.js +0 -3
- package/session_pool/errors.d.ts +0 -7
- package/session_pool/errors.js +0 -11
- package/session_pool/fingerprint.d.ts +0 -9
- package/session_pool/fingerprint.js +0 -30
- package/session_pool/index.d.ts +0 -4
- package/session_pool/index.js +0 -4
- package/session_pool/session.d.ts +0 -150
- package/session_pool/session.js +0 -220
- package/session_pool/session_pool.d.ts +0 -240
- package/session_pool/session_pool.js +0 -394
- package/storages/sitemap_request_loader.d.ts +0 -201
- package/storages/sitemap_request_loader.js +0 -438
- package/storages/throttling_request_manager.d.ts +0 -239
- package/storages/throttling_request_manager.js +0 -646
- /package/{crawlers/crawler_commons.js → events/system_info.js} +0 -0
|
@@ -1,308 +0,0 @@
|
|
|
1
|
-
import { inspect } from 'node:util';
|
|
2
|
-
import { ErrorSnapshotter } from './error_snapshotter.js';
|
|
3
|
-
const extractPathFromStackTraceLine = (line) => {
|
|
4
|
-
const lastStartingRoundBracketIndex = line.lastIndexOf('(');
|
|
5
|
-
if (lastStartingRoundBracketIndex !== -1) {
|
|
6
|
-
const closingRoundBracketIndex = line.indexOf(')', lastStartingRoundBracketIndex);
|
|
7
|
-
if (closingRoundBracketIndex !== -1) {
|
|
8
|
-
return line.slice(lastStartingRoundBracketIndex + 1, closingRoundBracketIndex);
|
|
9
|
-
}
|
|
10
|
-
}
|
|
11
|
-
return line;
|
|
12
|
-
};
|
|
13
|
-
// https://v8.dev/docs/stack-trace-api#appendix%3A-stack-trace-format
|
|
14
|
-
const getPathFromStackTrace = (stack) => {
|
|
15
|
-
for (const line of stack) {
|
|
16
|
-
const path = extractPathFromStackTraceLine(line);
|
|
17
|
-
if (path.startsWith('node:') || path.includes('/node_modules/') || path.includes('\\node_modules\\')) {
|
|
18
|
-
continue;
|
|
19
|
-
}
|
|
20
|
-
return path;
|
|
21
|
-
}
|
|
22
|
-
return extractPathFromStackTraceLine(stack[0]);
|
|
23
|
-
};
|
|
24
|
-
const getStackTraceGroup = (error, storage, showFullStack) => {
|
|
25
|
-
const stack = error.stack?.split('\n').map((line) => line.trim());
|
|
26
|
-
let sliceAt = -1;
|
|
27
|
-
if (stack) {
|
|
28
|
-
for (let i = 0; i < stack.length; i++) {
|
|
29
|
-
if (stack[i].startsWith('at ') || stack[i].startsWith('eval at ')) {
|
|
30
|
-
sliceAt = i;
|
|
31
|
-
break;
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
let normalizedStackTrace = null;
|
|
36
|
-
if (sliceAt !== -1) {
|
|
37
|
-
normalizedStackTrace = showFullStack
|
|
38
|
-
? stack
|
|
39
|
-
.slice(sliceAt)
|
|
40
|
-
.map((x) => x.trim())
|
|
41
|
-
.join('\n')
|
|
42
|
-
: getPathFromStackTrace(stack.slice(sliceAt));
|
|
43
|
-
}
|
|
44
|
-
if (!normalizedStackTrace) {
|
|
45
|
-
normalizedStackTrace = 'missing stack trace';
|
|
46
|
-
}
|
|
47
|
-
if (!(normalizedStackTrace in storage)) {
|
|
48
|
-
storage[normalizedStackTrace] = Object.create(null);
|
|
49
|
-
}
|
|
50
|
-
return storage[normalizedStackTrace];
|
|
51
|
-
};
|
|
52
|
-
const getErrorCodeGroup = (error, storage) => {
|
|
53
|
-
let { code } = error;
|
|
54
|
-
if (code === undefined) {
|
|
55
|
-
code = 'missing error code';
|
|
56
|
-
}
|
|
57
|
-
if (!(code in storage)) {
|
|
58
|
-
storage[code] = Object.create(null);
|
|
59
|
-
}
|
|
60
|
-
return storage[String(code)];
|
|
61
|
-
};
|
|
62
|
-
const getErrorNameGroup = (error, storage) => {
|
|
63
|
-
const { name } = error;
|
|
64
|
-
if (!(name in storage)) {
|
|
65
|
-
storage[name] = Object.create(null);
|
|
66
|
-
}
|
|
67
|
-
return storage[name];
|
|
68
|
-
};
|
|
69
|
-
const findBiggestWordIntersection = (a, b) => {
|
|
70
|
-
let maxStreak = 0;
|
|
71
|
-
let bStreakIndex = -1;
|
|
72
|
-
let aStreakIndex = -1;
|
|
73
|
-
for (let aIndex = 0; aIndex < a.length; aIndex++) {
|
|
74
|
-
let bIndex = -1;
|
|
75
|
-
do {
|
|
76
|
-
let aWalkIndex = aIndex;
|
|
77
|
-
bIndex = b.indexOf(a[aIndex], bIndex + 1);
|
|
78
|
-
let bWalkIndex = bIndex;
|
|
79
|
-
let streak = 0;
|
|
80
|
-
while (aWalkIndex < a.length && bWalkIndex < b.length && b[bWalkIndex++] === a[aWalkIndex++]) {
|
|
81
|
-
streak++;
|
|
82
|
-
}
|
|
83
|
-
if (streak > maxStreak) {
|
|
84
|
-
maxStreak = streak;
|
|
85
|
-
aStreakIndex = aIndex;
|
|
86
|
-
bStreakIndex = bIndex;
|
|
87
|
-
}
|
|
88
|
-
} while (bIndex !== -1);
|
|
89
|
-
}
|
|
90
|
-
return {
|
|
91
|
-
maxStreak,
|
|
92
|
-
aStreakIndex,
|
|
93
|
-
bStreakIndex,
|
|
94
|
-
};
|
|
95
|
-
};
|
|
96
|
-
const arrayCount = (array, target) => {
|
|
97
|
-
let result = 0;
|
|
98
|
-
for (const item of array) {
|
|
99
|
-
if (item === target) {
|
|
100
|
-
result++;
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
return result;
|
|
104
|
-
};
|
|
105
|
-
const calculatePlaceholder = (a, b) => {
|
|
106
|
-
const { maxStreak, aStreakIndex, bStreakIndex } = findBiggestWordIntersection(a, b);
|
|
107
|
-
if (maxStreak === 0) {
|
|
108
|
-
return ['_'];
|
|
109
|
-
}
|
|
110
|
-
const leftA = a.slice(0, aStreakIndex);
|
|
111
|
-
const leftB = b.slice(0, bStreakIndex);
|
|
112
|
-
const rightA = a.slice(aStreakIndex + maxStreak);
|
|
113
|
-
const rightB = b.slice(bStreakIndex + maxStreak);
|
|
114
|
-
const output = [];
|
|
115
|
-
if (leftA.length !== 0 || leftB.length !== 0) {
|
|
116
|
-
output.push(...calculatePlaceholder(leftA, leftB));
|
|
117
|
-
}
|
|
118
|
-
output.push(...a.slice(aStreakIndex, aStreakIndex + maxStreak));
|
|
119
|
-
if (rightA.length !== 0 || rightB.length !== 0) {
|
|
120
|
-
output.push(...calculatePlaceholder(rightA, rightB));
|
|
121
|
-
}
|
|
122
|
-
return output;
|
|
123
|
-
};
|
|
124
|
-
const normalizedCalculatePlaceholder = (a, b) => {
|
|
125
|
-
const output = calculatePlaceholder(a, b);
|
|
126
|
-
// We can't be too general
|
|
127
|
-
if (arrayCount(output, '_') / output.length >= 0.5) {
|
|
128
|
-
return ['_'];
|
|
129
|
-
}
|
|
130
|
-
return output;
|
|
131
|
-
};
|
|
132
|
-
// Merge A (missing placeholders) into B (can contain placeholders but does not have to)
|
|
133
|
-
const mergeMessages = (a, b, storage) => {
|
|
134
|
-
const placeholder = normalizedCalculatePlaceholder(a.split(' '), b.split(' ')).join(' ');
|
|
135
|
-
if (placeholder === '_') {
|
|
136
|
-
return undefined;
|
|
137
|
-
}
|
|
138
|
-
const count = storage[a].count + storage[b].count;
|
|
139
|
-
delete storage[a];
|
|
140
|
-
delete storage[b];
|
|
141
|
-
storage[placeholder] = Object.assign(Object.create(null), {
|
|
142
|
-
count,
|
|
143
|
-
});
|
|
144
|
-
return placeholder;
|
|
145
|
-
};
|
|
146
|
-
const getErrorMessageGroup = (error, storage, showFullMessage) => {
|
|
147
|
-
let { message } = error;
|
|
148
|
-
if (!message) {
|
|
149
|
-
try {
|
|
150
|
-
message =
|
|
151
|
-
typeof error === 'string'
|
|
152
|
-
? error
|
|
153
|
-
: `Unknown error message. Received non-error object: ${JSON.stringify(error)}`;
|
|
154
|
-
}
|
|
155
|
-
catch {
|
|
156
|
-
message = `Unknown error message. Received non-error object, and could not stringify it: ${inspect(error, {
|
|
157
|
-
depth: 0,
|
|
158
|
-
})}`;
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
if (!showFullMessage) {
|
|
162
|
-
const newLineIndex = message.indexOf('\n');
|
|
163
|
-
message = message.slice(0, newLineIndex === -1 ? undefined : newLineIndex);
|
|
164
|
-
}
|
|
165
|
-
if (!(message in storage)) {
|
|
166
|
-
storage[message] = Object.assign(Object.create(null), {
|
|
167
|
-
count: 0,
|
|
168
|
-
});
|
|
169
|
-
// This actually safe, since we Object.create(null) so no prototype pollution can happen.
|
|
170
|
-
// eslint-disable-next-line no-restricted-syntax, guard-for-in
|
|
171
|
-
for (const existingMessage in storage) {
|
|
172
|
-
const newMessage = mergeMessages(message, existingMessage, storage);
|
|
173
|
-
if (newMessage) {
|
|
174
|
-
message = newMessage;
|
|
175
|
-
break;
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
return storage[message];
|
|
180
|
-
};
|
|
181
|
-
const increaseCount = (group) => {
|
|
182
|
-
if (!('count' in group)) {
|
|
183
|
-
// In case users don't want to display error message
|
|
184
|
-
group.count = 0;
|
|
185
|
-
}
|
|
186
|
-
group.count++;
|
|
187
|
-
};
|
|
188
|
-
/**
|
|
189
|
-
* This class tracks errors and computes a summary of information like:
|
|
190
|
-
* - where the errors happened
|
|
191
|
-
* - what the error names are
|
|
192
|
-
* - what the error codes are
|
|
193
|
-
* - what is the general error message
|
|
194
|
-
*
|
|
195
|
-
* This is extremely useful when there are dynamic error messages, such as argument validation.
|
|
196
|
-
*
|
|
197
|
-
* Since the structure of the `tracker.result` object differs when using different options,
|
|
198
|
-
* it's typed as `Record<string, unknown>`. The most deep object has a `count` property, which is a number.
|
|
199
|
-
*
|
|
200
|
-
* It's possible to get the total amount of errors via the `tracker.total` property.
|
|
201
|
-
*/
|
|
202
|
-
export class ErrorTracker {
|
|
203
|
-
#options;
|
|
204
|
-
result;
|
|
205
|
-
total;
|
|
206
|
-
errorSnapshotter;
|
|
207
|
-
constructor(options = {}) {
|
|
208
|
-
this.#options = {
|
|
209
|
-
showErrorCode: true,
|
|
210
|
-
showErrorName: true,
|
|
211
|
-
showStackTrace: true,
|
|
212
|
-
showFullStack: false,
|
|
213
|
-
showErrorMessage: true,
|
|
214
|
-
showFullMessage: false,
|
|
215
|
-
saveErrorSnapshots: false,
|
|
216
|
-
...options,
|
|
217
|
-
};
|
|
218
|
-
if (this.#options.saveErrorSnapshots) {
|
|
219
|
-
this.errorSnapshotter = new ErrorSnapshotter();
|
|
220
|
-
}
|
|
221
|
-
this.result = Object.create(null);
|
|
222
|
-
this.total = 0;
|
|
223
|
-
}
|
|
224
|
-
updateGroup(error) {
|
|
225
|
-
let group = this.result;
|
|
226
|
-
if (this.#options.showStackTrace) {
|
|
227
|
-
group = getStackTraceGroup(error, group, this.#options.showFullStack);
|
|
228
|
-
}
|
|
229
|
-
if (this.#options.showErrorCode) {
|
|
230
|
-
group = getErrorCodeGroup(error, group);
|
|
231
|
-
}
|
|
232
|
-
if (this.#options.showErrorName) {
|
|
233
|
-
group = getErrorNameGroup(error, group);
|
|
234
|
-
}
|
|
235
|
-
if (this.#options.showErrorMessage) {
|
|
236
|
-
group = getErrorMessageGroup(error, group, this.#options.showFullMessage);
|
|
237
|
-
}
|
|
238
|
-
increaseCount(group);
|
|
239
|
-
return group;
|
|
240
|
-
}
|
|
241
|
-
add(error) {
|
|
242
|
-
this.total++;
|
|
243
|
-
this.updateGroup(error);
|
|
244
|
-
if (typeof error.cause === 'object' && error.cause !== null) {
|
|
245
|
-
this.add(error.cause);
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
/**
|
|
249
|
-
* This method is async, because it captures a snapshot of the error context.
|
|
250
|
-
* We added this new method to avoid breaking changes.
|
|
251
|
-
*/
|
|
252
|
-
async addAsync(error, context) {
|
|
253
|
-
this.total++;
|
|
254
|
-
const group = this.updateGroup(error);
|
|
255
|
-
// Capture a snapshot (screenshot and HTML) on the first occurrence of an error
|
|
256
|
-
if (group.count === 1 && context) {
|
|
257
|
-
await this.captureSnapshot(group, error, context).catch(() => { });
|
|
258
|
-
}
|
|
259
|
-
if (typeof error.cause === 'object' && error.cause !== null) {
|
|
260
|
-
await this.addAsync(error.cause);
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
getUniqueErrorCount() {
|
|
264
|
-
let count = 0;
|
|
265
|
-
const goDeeper = (group) => {
|
|
266
|
-
if ('count' in group) {
|
|
267
|
-
count++;
|
|
268
|
-
return;
|
|
269
|
-
}
|
|
270
|
-
// eslint-disable-next-line guard-for-in, no-restricted-syntax
|
|
271
|
-
for (const key in group) {
|
|
272
|
-
goDeeper(group[key]);
|
|
273
|
-
}
|
|
274
|
-
};
|
|
275
|
-
goDeeper(this.result);
|
|
276
|
-
return count;
|
|
277
|
-
}
|
|
278
|
-
getMostPopularErrors(count) {
|
|
279
|
-
const result = [];
|
|
280
|
-
const goDeeper = (group, path) => {
|
|
281
|
-
if ('count' in group) {
|
|
282
|
-
result.push([group.count, path]);
|
|
283
|
-
return;
|
|
284
|
-
}
|
|
285
|
-
// eslint-disable-next-line guard-for-in, no-restricted-syntax
|
|
286
|
-
for (const key in group) {
|
|
287
|
-
goDeeper(group[key], [...path, key]);
|
|
288
|
-
}
|
|
289
|
-
};
|
|
290
|
-
goDeeper(this.result, []);
|
|
291
|
-
return result.sort((a, b) => b[0] - a[0]).slice(0, count);
|
|
292
|
-
}
|
|
293
|
-
async captureSnapshot(storage, error, context) {
|
|
294
|
-
if (!this.errorSnapshotter) {
|
|
295
|
-
return;
|
|
296
|
-
}
|
|
297
|
-
const { screenshotFileUrl, htmlFileUrl } = await this.errorSnapshotter.captureSnapshot(error, context);
|
|
298
|
-
storage.firstErrorScreenshotUrl = screenshotFileUrl;
|
|
299
|
-
storage.firstErrorHtmlUrl = htmlFileUrl;
|
|
300
|
-
}
|
|
301
|
-
reset() {
|
|
302
|
-
// This actually safe, since we Object.create(null) so no prototype pollution can happen.
|
|
303
|
-
// eslint-disable-next-line no-restricted-syntax, guard-for-in
|
|
304
|
-
for (const key in this.result) {
|
|
305
|
-
delete this.result[key];
|
|
306
|
-
}
|
|
307
|
-
}
|
|
308
|
-
}
|
package/crawlers/index.d.ts
DELETED
package/crawlers/index.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/crawlers/statistics.d.ts
DELETED
|
@@ -1,328 +0,0 @@
|
|
|
1
|
-
import type { CrawleeLogger } from '../log.js';
|
|
2
|
-
import type { SyncStateConversion } from '../recoverable_state.js';
|
|
3
|
-
import { KeyValueStore } from '../storages/key_value_store.js';
|
|
4
|
-
import { ErrorTracker } from './error_tracker.js';
|
|
5
|
-
/**
|
|
6
|
-
* Persistence-related options to control how and when crawler's data gets persisted.
|
|
7
|
-
*/
|
|
8
|
-
export interface PersistenceOptions {
|
|
9
|
-
/**
|
|
10
|
-
* Use this flag to disable or enable periodic persistence to key value store.
|
|
11
|
-
* @default true
|
|
12
|
-
*/
|
|
13
|
-
enable?: boolean;
|
|
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
|
-
}
|
|
77
|
-
/**
|
|
78
|
-
* The statistics class provides an interface to collecting and logging run
|
|
79
|
-
* statistics for requests.
|
|
80
|
-
*
|
|
81
|
-
* All statistic information is saved on key value store
|
|
82
|
-
* under the key `CRAWLEE_CRAWLER_STATISTICS_*`, persists between
|
|
83
|
-
* migrations and abort/resurrect
|
|
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
|
-
*
|
|
88
|
-
* @category Crawlers
|
|
89
|
-
*/
|
|
90
|
-
export declare class Statistics<StateExtension extends object = {}, PersistedStateExtension extends object = StateExtension> implements IStatistics<StateExtension> {
|
|
91
|
-
#private;
|
|
92
|
-
private static id;
|
|
93
|
-
/**
|
|
94
|
-
* An error tracker for final retry errors.
|
|
95
|
-
*/
|
|
96
|
-
readonly errorTracker: ErrorTracker;
|
|
97
|
-
/**
|
|
98
|
-
* An error tracker for retry errors prior to the final retry.
|
|
99
|
-
*/
|
|
100
|
-
readonly errorTrackerRetry: ErrorTracker;
|
|
101
|
-
/**
|
|
102
|
-
* Statistic instance id.
|
|
103
|
-
*/
|
|
104
|
-
readonly id: string;
|
|
105
|
-
private readonly log;
|
|
106
|
-
/**
|
|
107
|
-
* Current statistic state used for doing calculations on {@link Statistics.calculate} calls
|
|
108
|
-
*/
|
|
109
|
-
get state(): StatisticState & StateExtension;
|
|
110
|
-
/**
|
|
111
|
-
* Contains the current retries histogram. Index 0 means 0 retries, index 2, 2 retries, and so on
|
|
112
|
-
*/
|
|
113
|
-
get requestRetryHistogram(): number[];
|
|
114
|
-
/**
|
|
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`.
|
|
117
|
-
*/
|
|
118
|
-
constructor(options?: StatisticsOptions<StateExtension, PersistedStateExtension>);
|
|
119
|
-
/**
|
|
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.
|
|
123
|
-
*/
|
|
124
|
-
reset(): void;
|
|
125
|
-
/**
|
|
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.
|
|
129
|
-
*/
|
|
130
|
-
resetStore(): Promise<void>;
|
|
131
|
-
/**
|
|
132
|
-
* Increments the status code counter.
|
|
133
|
-
*/
|
|
134
|
-
registerStatusCode(code: number): void;
|
|
135
|
-
/**
|
|
136
|
-
* Starts a job
|
|
137
|
-
* @ignore
|
|
138
|
-
*/
|
|
139
|
-
startJob(id: number | string): void;
|
|
140
|
-
/**
|
|
141
|
-
* Mark job as finished and sets the state
|
|
142
|
-
* @ignore
|
|
143
|
-
*/
|
|
144
|
-
finishJob(id: number | string, retryCount: number): void;
|
|
145
|
-
/**
|
|
146
|
-
* Mark job as failed and sets the state
|
|
147
|
-
* @ignore
|
|
148
|
-
*/
|
|
149
|
-
failJob(id: number | string, retryCount: number): void;
|
|
150
|
-
/**
|
|
151
|
-
* Discards a started job without affecting the finished/failed counters, e.g. when a request
|
|
152
|
-
* turns out to be skipped (robots.txt, enqueue strategy) after `startJob` was already called for it.
|
|
153
|
-
* @ignore
|
|
154
|
-
*/
|
|
155
|
-
discardJob(id: number | string): void;
|
|
156
|
-
/**
|
|
157
|
-
* Calculate the current statistics
|
|
158
|
-
*/
|
|
159
|
-
calculate(): CalculatedStatistics;
|
|
160
|
-
/**
|
|
161
|
-
* Initializes the key value store for persisting the statistics,
|
|
162
|
-
* displaying the current state in predefined intervals
|
|
163
|
-
*/
|
|
164
|
-
startCapturing(): Promise<void>;
|
|
165
|
-
/**
|
|
166
|
-
* Stops logging and remove event listeners, then persist
|
|
167
|
-
*/
|
|
168
|
-
stopCapturing(): Promise<void>;
|
|
169
|
-
private saveRetryCountForJob;
|
|
170
|
-
/**
|
|
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.
|
|
175
|
-
*/
|
|
176
|
-
persistState(): Promise<void>;
|
|
177
|
-
/**
|
|
178
|
-
* Make this class serializable when called with `JSON.stringify(statsInstance)` directly
|
|
179
|
-
* or through `keyValueStore.setValue('KEY', statsInstance)`
|
|
180
|
-
*/
|
|
181
|
-
toJSON(): StatisticPersistedState & PersistedStateExtension;
|
|
182
|
-
}
|
|
183
|
-
/**
|
|
184
|
-
* Configuration for the {@link Statistics} instance used by the crawler
|
|
185
|
-
*/
|
|
186
|
-
export interface StatisticsOptions<StateExtension extends object = {}, PersistedStateExtension extends object = StateExtension> {
|
|
187
|
-
/**
|
|
188
|
-
* Interval in seconds to log the current statistics
|
|
189
|
-
* @default 60
|
|
190
|
-
*/
|
|
191
|
-
logIntervalSecs?: number;
|
|
192
|
-
/**
|
|
193
|
-
* Message to log with the current statistics
|
|
194
|
-
* @default 'Statistics'
|
|
195
|
-
*/
|
|
196
|
-
logMessage?: string;
|
|
197
|
-
/**
|
|
198
|
-
* Parent logger instance, the statistics will create a child logger from this.
|
|
199
|
-
* @default crawler.log
|
|
200
|
-
*/
|
|
201
|
-
log?: CrawleeLogger;
|
|
202
|
-
/**
|
|
203
|
-
* Key value store instance to persist the statistics.
|
|
204
|
-
* If not provided, the default one will be used when capturing starts
|
|
205
|
-
*/
|
|
206
|
-
keyValueStore?: KeyValueStore;
|
|
207
|
-
/**
|
|
208
|
-
* Control how and when to persist the statistics.
|
|
209
|
-
*/
|
|
210
|
-
persistenceOptions?: PersistenceOptions;
|
|
211
|
-
/**
|
|
212
|
-
* Save HTML snapshot (and a screenshot if possible) when an error occurs.
|
|
213
|
-
* @default false
|
|
214
|
-
*/
|
|
215
|
-
saveErrorSnapshots?: boolean;
|
|
216
|
-
/**
|
|
217
|
-
* A unique identifier for this statistics instance. This ID is used for persistence
|
|
218
|
-
* to the key value store, ensuring the same statistics can be loaded after script restarts.
|
|
219
|
-
*
|
|
220
|
-
* If not provided, an auto-incremented ID will be used for backward compatibility.
|
|
221
|
-
* This means statistics may not persist correctly across script restarts
|
|
222
|
-
* if crawler creation order changes.
|
|
223
|
-
*/
|
|
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>;
|
|
236
|
-
}
|
|
237
|
-
/**
|
|
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.
|
|
241
|
-
*/
|
|
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'> {
|
|
284
|
-
statsId: string;
|
|
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;
|
|
296
|
-
requestTotalDurationMillis: number;
|
|
297
|
-
requestsTotal: number;
|
|
298
|
-
/** {@link StatisticState.instanceStart} of the run that wrote the record. */
|
|
299
|
-
crawlerLastStartTimestamp: number;
|
|
300
|
-
}
|
|
301
|
-
/**
|
|
302
|
-
* Contains the statistics state
|
|
303
|
-
*/
|
|
304
|
-
export interface StatisticState {
|
|
305
|
-
requestsFinished: number;
|
|
306
|
-
requestsFailed: number;
|
|
307
|
-
requestsRetries: number;
|
|
308
|
-
requestsFailedPerMinute: number;
|
|
309
|
-
requestsFinishedPerMinute: number;
|
|
310
|
-
requestMinDurationMillis: number;
|
|
311
|
-
requestMaxDurationMillis: number;
|
|
312
|
-
requestTotalFailedDurationMillis: number;
|
|
313
|
-
requestTotalFinishedDurationMillis: number;
|
|
314
|
-
crawlerStartedAt: Date | string | null;
|
|
315
|
-
crawlerFinishedAt: Date | string | null;
|
|
316
|
-
crawlerRuntimeMillis: number;
|
|
317
|
-
statsPersistedAt: Date | string | null;
|
|
318
|
-
errors: Record<string, unknown>;
|
|
319
|
-
retryErrors: Record<string, unknown>;
|
|
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;
|
|
328
|
-
}
|