forked from apify/crawlee
/
basic-crawler.ts
1470 lines (1271 loc) · 61.4 KB
/
basic-crawler.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import defaultLog, { LogLevel } from '@apify/log';
import type { Log } from '@apify/log';
import { addTimeoutToPromise, tryCancel, TimeoutError } from '@apify/timeout';
import { cryptoRandomObjectId } from '@apify/utilities';
import type {
AddRequestsBatchedOptions,
AddRequestsBatchedResult,
AutoscaledPoolOptions,
CrawlingContext,
EnqueueLinksOptions,
EventManager,
FinalStatistics,
GetUserDataFromRequest,
ProxyInfo,
Request,
RequestList,
RequestOptions,
RouterHandler,
RouterRoutes,
Session,
SessionPoolOptions,
Source,
StatisticState,
} from '@crawlee/core';
import {
mergeCookies,
AutoscaledPool,
Configuration,
enqueueLinks,
EventType,
KeyValueStore,
CriticalError,
NonRetryableError,
RequestQueue,
RequestState,
Router,
SessionPool,
Statistics,
purgeDefaultStorages,
validators,
RetryRequestError,
SessionError,
} from '@crawlee/core';
import type { Dictionary, Awaitable, BatchAddRequestsResult, SetStatusMessageOptions } from '@crawlee/types';
import { ROTATE_PROXY_ERRORS } from '@crawlee/utils';
import type { Method, OptionsInit } from 'got-scraping';
import { gotScraping } from 'got-scraping';
import ow, { ArgumentError } from 'ow';
import { getDomain } from 'tldts';
import type { SetRequired } from 'type-fest';
export interface BasicCrawlingContext<
UserData extends Dictionary = Dictionary,
> extends CrawlingContext<BasicCrawler, UserData> {
/**
* This function automatically finds and enqueues links from the current page, adding them to the {@apilink RequestQueue}
* currently used by the crawler.
*
* Optionally, the function allows you to filter the target links' URLs using an array of globs or regular expressions
* and override settings of the enqueued {@apilink Request} objects.
*
* Check out the [Crawl a website with relative links](https://crawlee.dev/docs/examples/crawl-relative-links) example
* for more details regarding its usage.
*
* **Example usage**
*
* ```ts
* async requestHandler({ enqueueLinks }) {
* await enqueueLinks({
* urls: [...],
* });
* },
* ```
*
* @param [options] All `enqueueLinks()` parameters are passed via an options object.
* @returns Promise that resolves to {@apilink BatchAddRequestsResult} object.
*/
enqueueLinks(options?: SetRequired<EnqueueLinksOptions, 'urls'>): Promise<BatchAddRequestsResult>;
}
/**
* Since there's no set number of seconds before the container is terminated after
* a migration event, we need some reasonable number to use for RequestList persistence.
* Once a migration event is received, the crawler will be paused, and it will wait for
* this long before persisting the RequestList state. This should allow most healthy
* requests to finish and be marked as handled, thus lowering the amount of duplicate
* results after migration.
* @ignore
*/
const SAFE_MIGRATION_WAIT_MILLIS = 20000;
export type RequestHandler<Context extends CrawlingContext = BasicCrawlingContext> = (inputs: Context) => Awaitable<void>;
export type ErrorHandler<Context extends CrawlingContext = BasicCrawlingContext> = (inputs: Context, error: Error) => Awaitable<void>;
export interface StatusMessageCallbackParams<
Context extends CrawlingContext = BasicCrawlingContext,
Crawler extends BasicCrawler<any> = BasicCrawler<Context>,
> {
state: StatisticState;
crawler: Crawler;
previousState: StatisticState;
message: string;
}
export type StatusMessageCallback<
Context extends CrawlingContext = BasicCrawlingContext,
Crawler extends BasicCrawler<any> = BasicCrawler<Context>,
> = (params: StatusMessageCallbackParams<Context, Crawler>) => Awaitable<void>;
export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCrawlingContext> {
/**
* User-provided function that performs the logic of the crawler. It is called for each URL to crawl.
*
* The function receives the {@apilink BasicCrawlingContext} as an argument,
* where the {@apilink BasicCrawlingContext.request|`request`} represents the URL to crawl.
*
* The function must return a promise, which is then awaited by the crawler.
*
* If the function throws an exception, the crawler will try to re-crawl the
* request later, up to the {@apilink BasicCrawlerOptions.maxRequestRetries|`maxRequestRetries`} times.
* If all the retries fail, the crawler calls the function
* provided to the {@apilink BasicCrawlerOptions.failedRequestHandler|`failedRequestHandler`} parameter.
* To make this work, we should **always**
* let our function throw exceptions rather than catch them.
* The exceptions are logged to the request using the
* {@apilink Request.pushErrorMessage|`Request.pushErrorMessage()`} function.
*/
requestHandler?: RequestHandler<Context>;
/**
* User-provided function that performs the logic of the crawler. It is called for each URL to crawl.
*
* The function receives the {@apilink BasicCrawlingContext} as an argument,
* where the {@apilink BasicCrawlingContext.request|`request`} represents the URL to crawl.
*
* The function must return a promise, which is then awaited by the crawler.
*
* If the function throws an exception, the crawler will try to re-crawl the
* request later, up to the {@apilink BasicCrawlerOptions.maxRequestRetries|`maxRequestRetries`} times.
* If all the retries fail, the crawler calls the function
* provided to the {@apilink BasicCrawlerOptions.failedRequestHandler|`failedRequestHandler`} parameter.
* To make this work, we should **always**
* let our function throw exceptions rather than catch them.
* The exceptions are logged to the request using the
* {@apilink Request.pushErrorMessage|`Request.pushErrorMessage()`} function.
*
* @deprecated `handleRequestFunction` has been renamed to `requestHandler` and will be removed in a future version.
* @ignore
*/
handleRequestFunction?: RequestHandler<Context>;
/**
* Static list of URLs to be processed.
* If not provided, the crawler will open the default request queue when the {@apilink BasicCrawler.addRequests|`crawler.addRequests()`} function is called.
* > Alternatively, `requests` parameter of {@apilink BasicCrawler.run|`crawler.run()`} could be used to enqueue the initial requests -
* it is a shortcut for running `crawler.addRequests()` before the `crawler.run()`.
*/
requestList?: RequestList;
/**
* Dynamic queue of URLs to be processed. This is useful for recursive crawling of websites.
* If not provided, the crawler will open the default request queue when the {@apilink BasicCrawler.addRequests|`crawler.addRequests()`} function is called.
* > Alternatively, `requests` parameter of {@apilink BasicCrawler.run|`crawler.run()`} could be used to enqueue the initial requests -
* it is a shortcut for running `crawler.addRequests()` before the `crawler.run()`.
*/
requestQueue?: RequestQueue;
/**
* Timeout in which the function passed as {@apilink BasicCrawlerOptions.requestHandler|`requestHandler`} needs to finish, in seconds.
* @default 60
*/
requestHandlerTimeoutSecs?: number;
/**
* Timeout in which the function passed as {@apilink BasicCrawlerOptions.requestHandler|`requestHandler`} needs to finish, in seconds.
* @default 60
* @deprecated `handleRequestTimeoutSecs` has been renamed to `requestHandlerTimeoutSecs` and will be removed in a future version.
* @ignore
*/
handleRequestTimeoutSecs?: number;
/**
* User-provided function that allows modifying the request object before it gets retried by the crawler.
* It's executed before each retry for the requests that failed less than {@apilink BasicCrawlerOptions.maxRequestRetries|`maxRequestRetries`} times.
*
* The function receives the {@apilink BasicCrawlingContext} as the first argument,
* where the {@apilink BasicCrawlingContext.request|`request`} corresponds to the request to be retried.
* Second argument is the `Error` instance that
* represents the last error thrown during processing of the request.
*/
errorHandler?: ErrorHandler<Context>;
/**
* A function to handle requests that failed more than {@apilink BasicCrawlerOptions.maxRequestRetries|`maxRequestRetries`} times.
*
* The function receives the {@apilink BasicCrawlingContext} as the first argument,
* where the {@apilink BasicCrawlingContext.request|`request`} corresponds to the failed request.
* Second argument is the `Error` instance that
* represents the last error thrown during processing of the request.
*/
failedRequestHandler?: ErrorHandler<Context>;
/**
* A function to handle requests that failed more than {@apilink BasicCrawlerOptions.maxRequestRetries|`maxRequestRetries`} times.
*
* The function receives the {@apilink BasicCrawlingContext} as the first argument,
* where the {@apilink BasicCrawlingContext.request|`request`} corresponds to the failed request.
* Second argument is the `Error` instance that
* represents the last error thrown during processing of the request.
*
* @deprecated `handleFailedRequestFunction` has been renamed to `failedRequestHandler` and will be removed in a future version.
* @ignore
*/
handleFailedRequestFunction?: ErrorHandler<Context>;
/**
* Indicates how many times the request is retried if {@apilink BasicCrawlerOptions.requestHandler|`requestHandler`} fails.
* @default 3
*/
maxRequestRetries?: number;
/**
* Indicates how much time wait before crawling same domain request
* @default 0
*/
sameDomainDelay?: number;
/**
* Maximum number of session rotations per request.
* The crawler will automatically rotate the session in case of a proxy error or if it gets blocked by the website.
*
* The session rotations are not counted towards the {@apilink BasicCrawlerOptions.maxRequestRetries|`maxRequestRetries`} limit.
* @default 10
*/
maxSessionRotations?: number;
/**
* Maximum number of pages that the crawler will open. The crawl will stop when this limit is reached.
* This value should always be set in order to prevent infinite loops in misconfigured crawlers.
* > *NOTE:* In cases of parallel crawling, the actual number of pages visited might be slightly higher than this value.
*/
maxRequestsPerCrawl?: number;
/**
* Custom options passed to the underlying {@apilink AutoscaledPool} constructor.
* > *NOTE:* The {@apilink AutoscaledPoolOptions.runTaskFunction|`runTaskFunction`}
* and {@apilink AutoscaledPoolOptions.isTaskReadyFunction|`isTaskReadyFunction`} options
* are provided by the crawler and cannot be overridden.
* However, we can provide a custom implementation of {@apilink AutoscaledPoolOptions.isFinishedFunction|`isFinishedFunction`}.
*/
autoscaledPoolOptions?: AutoscaledPoolOptions;
/**
* Sets the minimum concurrency (parallelism) for the crawl. Shortcut for the
* AutoscaledPool {@apilink AutoscaledPoolOptions.minConcurrency|`minConcurrency`} option.
* > *WARNING:* If we set this value too high with respect to the available system memory and CPU, our crawler will run extremely slow or crash.
* If not sure, it's better to keep the default value and the concurrency will scale up automatically.
*/
minConcurrency?: number;
/**
* Sets the maximum concurrency (parallelism) for the crawl. Shortcut for the
* AutoscaledPool {@apilink AutoscaledPoolOptions.maxConcurrency|`maxConcurrency`} option.
*/
maxConcurrency?: number;
/**
* The maximum number of requests per minute the crawler should run.
* By default, this is set to `Infinity`, but we can pass any positive, non-zero integer.
* Shortcut for the AutoscaledPool {@apilink AutoscaledPoolOptions.maxTasksPerMinute|`maxTasksPerMinute`} option.
*/
maxRequestsPerMinute?: number;
/**
* Allows to keep the crawler alive even if the {@apilink RequestQueue} gets empty.
* By default, the `crawler.run()` will resolve once the queue is empty. With `keepAlive: true` it will keep running,
* waiting for more requests to come. Use `crawler.teardown()` to exit the crawler.
*/
keepAlive?: boolean;
/**
* Basic crawler will initialize the {@apilink SessionPool} with the corresponding {@apilink SessionPoolOptions|`sessionPoolOptions`}.
* The session instance will be than available in the {@apilink BasicCrawlerOptions.requestHandler|`requestHandler`}.
*/
useSessionPool?: boolean;
/**
* The configuration options for {@apilink SessionPool} to use.
*/
sessionPoolOptions?: SessionPoolOptions;
/**
* Defines the length of the interval for calling the `setStatusMessage` in seconds.
*/
statusMessageLoggingInterval?: number;
/**
* Allows overriding the default status message. The callback needs to call `crawler.setStatusMessage()` explicitly.
* The default status message is provided in the parameters.
*
* ```ts
* const crawler = new CheerioCrawler({
* statusMessageCallback: async (ctx) => {
* return ctx.crawler.setStatusMessage(`this is status message from ${new Date().toISOString()}`, { level: 'INFO' }); // log level defaults to 'DEBUG'
* },
* statusMessageLoggingInterval: 1, // defaults to 10s
* async requestHandler({ $, enqueueLinks, request, log }) {
* // ...
* },
* });
* ```
*/
statusMessageCallback?: StatusMessageCallback;
/**
* If set to `true`, the crawler will automatically try to bypass any detected bot protection.
*
* Currently supports:
* - [**Cloudflare** Bot Management](https://www.cloudflare.com/products/bot-management/)
* - [**Google Search** Rate Limiting](https://www.google.com/sorry/)
*/
retryOnBlocked?: boolean;
/** @internal */
log?: Log;
}
/**
* Provides a simple framework for parallel crawling of web pages.
* The URLs to crawl are fed either from a static list of URLs
* or from a dynamic queue of URLs enabling recursive crawling of websites.
*
* `BasicCrawler` is a low-level tool that requires the user to implement the page
* download and data extraction functionality themselves.
* If we want a crawler that already facilitates this functionality,
* we should consider using {@apilink CheerioCrawler}, {@apilink PuppeteerCrawler} or {@apilink PlaywrightCrawler}.
*
* `BasicCrawler` invokes the user-provided {@apilink BasicCrawlerOptions.requestHandler|`requestHandler`}
* for each {@apilink Request} object, which represents a single URL to crawl.
* The {@apilink Request} objects are fed from the {@apilink RequestList} or {@apilink RequestQueue}
* instances provided by the {@apilink BasicCrawlerOptions.requestList|`requestList`} or {@apilink BasicCrawlerOptions.requestQueue|`requestQueue`}
* constructor options, respectively. If neither `requestList` nor `requestQueue` options are provided,
* the crawler will open the default request queue either when the {@apilink BasicCrawler.addRequests|`crawler.addRequests()`} function is called,
* or if `requests` parameter (representing the initial requests) of the {@apilink BasicCrawler.run|`crawler.run()`} function is provided.
*
* If both {@apilink BasicCrawlerOptions.requestList|`requestList`} and {@apilink BasicCrawlerOptions.requestQueue|`requestQueue`} options are used,
* the instance first processes URLs from the {@apilink RequestList} and automatically enqueues all of them
* to the {@apilink RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
*
* The crawler finishes if there are no more {@apilink Request} objects to crawl.
*
* New requests are only dispatched when there is enough free CPU and memory available,
* using the functionality provided by the {@apilink AutoscaledPool} class.
* All {@apilink AutoscaledPool} configuration options can be passed to the {@apilink BasicCrawlerOptions.autoscaledPoolOptions|`autoscaledPoolOptions`}
* parameter of the `BasicCrawler` constructor.
* For user convenience, the {@apilink AutoscaledPoolOptions.minConcurrency|`minConcurrency`} and
* {@apilink AutoscaledPoolOptions.maxConcurrency|`maxConcurrency`} options of the
* underlying {@apilink AutoscaledPool} constructor are available directly in the `BasicCrawler` constructor.
*
* **Example usage:**
*
* ```javascript
* import { BasicCrawler, Dataset } from 'crawlee';
*
* // Create a crawler instance
* const crawler = new BasicCrawler({
* async requestHandler({ request, sendRequest }) {
* // 'request' contains an instance of the Request class
* // Here we simply fetch the HTML of the page and store it to a dataset
* const { body } = await sendRequest({
* url: request.url,
* method: request.method,
* body: request.payload,
* headers: request.headers,
* });
*
* await Dataset.pushData({
* url: request.url,
* html: body,
* })
* },
* });
*
* // Enqueue the initial requests and run the crawler
* await crawler.run([
* 'http://www.example.com/page-1',
* 'http://www.example.com/page-2',
* ]);
* ```
* @category Crawlers
*/
export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContext> {
private static readonly CRAWLEE_STATE_KEY = 'CRAWLEE_STATE';
/**
* A reference to the underlying {@apilink Statistics} class that collects and logs run statistics for requests.
*/
readonly stats: Statistics;
/**
* A reference to the underlying {@apilink RequestList} class that manages the crawler's {@apilink Request|requests}.
* Only available if used by the crawler.
*/
requestList?: RequestList;
/**
* Dynamic queue of URLs to be processed. This is useful for recursive crawling of websites.
* A reference to the underlying {@apilink RequestQueue} class that manages the crawler's {@apilink Request|requests}.
* Only available if used by the crawler.
*/
requestQueue?: RequestQueue;
/**
* A reference to the underlying {@apilink SessionPool} class that manages the crawler's {@apilink Session|sessions}.
* Only available if used by the crawler.
*/
sessionPool?: SessionPool;
/**
* A reference to the underlying {@apilink AutoscaledPool} class that manages the concurrency of the crawler.
* > *NOTE:* This property is only initialized after calling the {@apilink BasicCrawler.run|`crawler.run()`} function.
* We can use it to change the concurrency settings on the fly,
* to pause the crawler by calling {@apilink AutoscaledPool.pause|`autoscaledPool.pause()`}
* or to abort it by calling {@apilink AutoscaledPool.abort|`autoscaledPool.abort()`}.
*/
autoscaledPool?: AutoscaledPool;
/**
* Default {@apilink Router} instance that will be used if we don't specify any {@apilink BasicCrawlerOptions.requestHandler|`requestHandler`}.
* See {@apilink Router.addHandler|`router.addHandler()`} and {@apilink Router.addDefaultHandler|`router.addDefaultHandler()`}.
*/
readonly router: RouterHandler<Context> = Router.create<Context>();
running?: boolean;
protected log: Log;
protected requestHandler!: RequestHandler<Context>;
protected errorHandler?: ErrorHandler<Context>;
protected failedRequestHandler?: ErrorHandler<Context>;
protected requestHandlerTimeoutMillis!: number;
protected internalTimeoutMillis: number;
protected maxRequestRetries: number;
protected sameDomainDelay: number;
protected domainAccessedTime: Map<string, number>;
protected maxSessionRotations: number;
protected handledRequestsCount: number;
protected statusMessageLoggingInterval: number;
protected statusMessageCallback?: StatusMessageCallback;
protected sessionPoolOptions: SessionPoolOptions;
protected useSessionPool: boolean;
protected crawlingContexts = new Map<string, Context>();
protected autoscaledPoolOptions: AutoscaledPoolOptions;
protected events: EventManager;
protected retryOnBlocked: boolean;
private _closeEvents?: boolean;
protected static optionsShape = {
requestList: ow.optional.object.validate(validators.requestList),
requestQueue: ow.optional.object.validate(validators.requestQueue),
// Subclasses override this function instead of passing it
// in constructor, so this validation needs to apply only
// if the user creates an instance of BasicCrawler directly.
requestHandler: ow.optional.function,
// TODO: remove in a future release
handleRequestFunction: ow.optional.function,
requestHandlerTimeoutSecs: ow.optional.number,
// TODO: remove in a future release
handleRequestTimeoutSecs: ow.optional.number,
errorHandler: ow.optional.function,
failedRequestHandler: ow.optional.function,
// TODO: remove in a future release
handleFailedRequestFunction: ow.optional.function,
maxRequestRetries: ow.optional.number,
sameDomainDelay: ow.optional.number,
maxSessionRotations: ow.optional.number,
maxRequestsPerCrawl: ow.optional.number,
autoscaledPoolOptions: ow.optional.object,
sessionPoolOptions: ow.optional.object,
useSessionPool: ow.optional.boolean,
statusMessageLoggingInterval: ow.optional.number,
statusMessageCallback: ow.optional.function,
retryOnBlocked: ow.optional.boolean,
// AutoscaledPool shorthands
minConcurrency: ow.optional.number,
maxConcurrency: ow.optional.number,
maxRequestsPerMinute: ow.optional.number.integerOrInfinite.positive.greaterThanOrEqual(1),
keepAlive: ow.optional.boolean,
// internal
log: ow.optional.object,
};
/**
* All `BasicCrawler` parameters are passed via an options object.
*/
constructor(options: BasicCrawlerOptions<Context> = {}, readonly config = Configuration.getGlobalConfig()) {
ow(options, 'BasicCrawlerOptions', ow.object.exactShape(BasicCrawler.optionsShape));
const {
requestList,
requestQueue,
maxRequestRetries = 3,
sameDomainDelay = 0,
maxSessionRotations = 10,
maxRequestsPerCrawl,
autoscaledPoolOptions = {},
keepAlive,
sessionPoolOptions = {},
useSessionPool = true,
// AutoscaledPool shorthands
minConcurrency,
maxConcurrency,
maxRequestsPerMinute,
retryOnBlocked = false,
// internal
log = defaultLog.child({ prefix: this.constructor.name }),
// Old and new request handler methods
handleRequestFunction,
requestHandler,
handleRequestTimeoutSecs,
requestHandlerTimeoutSecs,
errorHandler,
handleFailedRequestFunction,
failedRequestHandler,
statusMessageLoggingInterval = 10,
statusMessageCallback,
} = options;
this.requestList = requestList;
this.requestQueue = requestQueue;
this.log = log;
this.statusMessageLoggingInterval = statusMessageLoggingInterval;
this.statusMessageCallback = statusMessageCallback as StatusMessageCallback;
this.events = config.getEventManager();
this.domainAccessedTime = new Map();
this._handlePropertyNameChange({
newName: 'requestHandler',
oldName: 'handleRequestFunction',
propertyKey: 'requestHandler',
newProperty: requestHandler,
oldProperty: handleRequestFunction,
allowUndefined: true, // fallback to the default router
});
if (!this.requestHandler) {
this.requestHandler = this.router;
}
this.errorHandler = errorHandler;
this._handlePropertyNameChange({
newName: 'failedRequestHandler',
oldName: 'handleFailedRequestFunction',
propertyKey: 'failedRequestHandler',
newProperty: failedRequestHandler,
oldProperty: handleFailedRequestFunction,
allowUndefined: true,
});
let newRequestHandlerTimeout: number | undefined;
if (!handleRequestTimeoutSecs) {
if (!requestHandlerTimeoutSecs) {
newRequestHandlerTimeout = 60_000;
} else {
newRequestHandlerTimeout = requestHandlerTimeoutSecs * 1000;
}
} else if (requestHandlerTimeoutSecs) {
newRequestHandlerTimeout = requestHandlerTimeoutSecs * 1000;
}
this.retryOnBlocked = retryOnBlocked;
this._handlePropertyNameChange({
newName: 'requestHandlerTimeoutSecs',
oldName: 'handleRequestTimeoutSecs',
propertyKey: 'requestHandlerTimeoutMillis',
newProperty: newRequestHandlerTimeout,
oldProperty: handleRequestTimeoutSecs ? handleRequestTimeoutSecs * 1000 : undefined,
});
const tryEnv = (val?: string) => (val == null ? null : +val);
// allow at least 5min for internal timeouts
this.internalTimeoutMillis = tryEnv(process.env.CRAWLEE_INTERNAL_TIMEOUT) ?? Math.max(this.requestHandlerTimeoutMillis * 2, 300e3);
// override the default internal timeout of request queue to respect `requestHandlerTimeoutMillis`
if (this.requestQueue) {
this.requestQueue.internalTimeoutMillis = this.internalTimeoutMillis;
}
this.maxRequestRetries = maxRequestRetries;
this.sameDomainDelay = sameDomainDelay;
this.maxSessionRotations = maxSessionRotations;
this.handledRequestsCount = 0;
this.stats = new Statistics({ logMessage: `${log.getOptions().prefix} request statistics:`, config });
this.sessionPoolOptions = {
...sessionPoolOptions,
log,
};
if (this.retryOnBlocked) {
this.sessionPoolOptions.blockedStatusCodes = sessionPoolOptions.blockedStatusCodes ?? [];
if (this.sessionPoolOptions.blockedStatusCodes.length !== 0) {
// eslint-disable-next-line max-len
log.warning(`Both 'blockedStatusCodes' and 'retryOnBlocked' are set. Please note that the 'retryOnBlocked' feature might not work as expected.`);
}
}
this.useSessionPool = useSessionPool;
this.crawlingContexts = new Map();
const maxSignedInteger = 2 ** 31 - 1;
if (this.requestHandlerTimeoutMillis > maxSignedInteger) {
log.warning(`requestHandlerTimeoutMillis ${this.requestHandlerTimeoutMillis}`
+ ` does not fit a signed 32-bit integer. Limiting the value to ${maxSignedInteger}`);
this.requestHandlerTimeoutMillis = maxSignedInteger;
}
this.internalTimeoutMillis = Math.min(this.internalTimeoutMillis, maxSignedInteger);
let shouldLogMaxPagesExceeded = true;
const isMaxPagesExceeded = () => maxRequestsPerCrawl && maxRequestsPerCrawl <= this.handledRequestsCount;
let { isFinishedFunction } = autoscaledPoolOptions;
// override even if `isFinishedFunction` provided by user - `keepAlive` has higher priority
if (keepAlive) {
isFinishedFunction = async () => false;
}
const basicCrawlerAutoscaledPoolConfiguration: Partial<AutoscaledPoolOptions> = {
minConcurrency: minConcurrency ?? autoscaledPoolOptions?.minConcurrency,
maxConcurrency: maxConcurrency ?? autoscaledPoolOptions?.maxConcurrency,
maxTasksPerMinute: maxRequestsPerMinute ?? autoscaledPoolOptions?.maxTasksPerMinute,
runTaskFunction: this._runTaskFunction.bind(this),
isTaskReadyFunction: async () => {
if (isMaxPagesExceeded()) {
if (shouldLogMaxPagesExceeded) {
log.info('Crawler reached the maxRequestsPerCrawl limit of '
+ `${maxRequestsPerCrawl} requests and will shut down soon. Requests that are in progress will be allowed to finish.`);
shouldLogMaxPagesExceeded = false;
}
return false;
}
return this._isTaskReadyFunction();
},
isFinishedFunction: async () => {
if (isMaxPagesExceeded()) {
log.info(`Earlier, the crawler reached the maxRequestsPerCrawl limit of ${maxRequestsPerCrawl} requests `
+ 'and all requests that were in progress at that time have now finished. '
+ `In total, the crawler processed ${this.handledRequestsCount} requests and will shut down.`);
return true;
}
const isFinished = isFinishedFunction
? await isFinishedFunction()
: await this._defaultIsFinishedFunction();
if (isFinished) {
const reason = isFinishedFunction
? 'Crawler\'s custom isFinishedFunction() returned true, the crawler will shut down.'
: 'All requests from the queue have been processed, the crawler will shut down.';
log.info(reason);
}
return isFinished;
},
log,
};
this.autoscaledPoolOptions = { ...autoscaledPoolOptions, ...basicCrawlerAutoscaledPoolConfiguration };
}
/**
* Checks if the given error is a proxy error by comparing its message to a list of known proxy error messages.
* Used for retrying requests that failed due to proxy errors.
*
* @param error The error to check.
*/
protected isProxyError(error: Error): boolean {
return ROTATE_PROXY_ERRORS.some((x: string) => (this._getMessageFromError(error) as any)?.includes(x));
}
protected isRequestBlocked(_crawlingContext: Context) {
throw new Error('the "isRequestBlocked" method is not implemented in this crawler.');
}
/**
* This method is periodically called by the crawler, every `statusMessageLoggingInterval` seconds.
*/
setStatusMessage(message: string, options: SetStatusMessageOptions = {}) {
const data = options.isStatusMessageTerminal != null ? { terminal: options.isStatusMessageTerminal } : undefined;
this.log.internal(LogLevel[options.level as 'DEBUG' ?? 'DEBUG'], message, data);
const client = this.config.getStorageClient();
return client.setStatusMessage?.(message, options);
}
private getPeriodicLogger() {
let previousState = { ...this.stats.state };
const getOperationMode = () => {
const { requestsFailed } = this.stats.state;
const { requestsFailed: previousRequestsFailed } = previousState;
previousState = { ...this.stats.state };
if (requestsFailed - previousRequestsFailed > 0) {
return 'ERROR';
}
return 'REGULAR';
};
const log = async () => {
const operationMode = getOperationMode();
let message: string;
if (operationMode === 'ERROR') {
// eslint-disable-next-line max-len
message = `Experiencing problems, ${this.stats.state.requestsFailed - previousState.requestsFailed || this.stats.state.requestsFailed} failed requests in the past ${this.statusMessageLoggingInterval} seconds.`;
} else {
const total = this.requestQueue?.assumedTotalCount || this.requestList?.length();
message = `Crawled ${this.stats.state.requestsFinished}${total ? `/${total}` : ''} pages, ${this.stats.state.requestsFailed} failed requests.`;
}
if (this.statusMessageCallback) {
return this.statusMessageCallback({ crawler: this as any, state: this.stats.state, previousState, message });
}
await this.setStatusMessage(message);
};
const interval = setInterval(log, this.statusMessageLoggingInterval * 1e3);
return { log, stop: () => clearInterval(interval) };
}
/**
* Runs the crawler. Returns a promise that gets resolved once all the requests are processed.
* We can use the `requests` parameter to enqueue the initial requests - it is a shortcut for
* running {@apilink BasicCrawler.addRequests|`crawler.addRequests()`} before the {@apilink BasicCrawler.run|`crawler.run()`}.
*
* @param [requests] The requests to add
* @param [options] Options for the request queue
*/
async run(requests?: (string | Request | RequestOptions)[], options?: CrawlerRunOptions): Promise<FinalStatistics> {
if (this.running) {
throw new Error('This crawler instance is already running, you can add more requests to it via `crawler.addRequests()`.');
}
const purgeRequestQueue = options?.purgeRequestQueue ?? true;
// When executing the run method for the second time explicitly (the first time `this.running` is `undefined`),
// we need to purge the default RQ to allow processing the same requests again - this is important so users can
// pass in failed requests back to the `crawler.run()`, otherwise they would be considered as handled and
// ignored - as a failed requests is still handled.
if (this.running === false && this.requestQueue?.name === 'default' && purgeRequestQueue) {
await this.requestQueue.drop();
this.requestQueue = await RequestQueue.open();
}
this.running = true;
this.stats.reset();
await this.stats.resetStore();
await purgeDefaultStorages();
if (requests) {
await this.addRequests(requests, options);
}
await this._init();
await this.stats.startCapturing();
const periodicLogger = this.getPeriodicLogger();
await this.setStatusMessage(`Initializing the crawler.`, { level: 'INFO' });
const sigintHandler = async () => {
this.log.warning('Pausing... Press CTRL+C again to force exit. To resume, do: CRAWLEE_PURGE_ON_START=0 npm start');
await this._pauseOnMigration();
await this.autoscaledPool!.abort();
};
// Attach a listener to handle migration and aborting events gracefully.
const boundPauseOnMigration = this._pauseOnMigration.bind(this);
process.once('SIGINT', sigintHandler);
this.events.on(EventType.MIGRATING, boundPauseOnMigration);
this.events.on(EventType.ABORTING, boundPauseOnMigration);
try {
await this.autoscaledPool!.run();
} finally {
await this.teardown();
await this.stats.stopCapturing();
process.off('SIGINT', sigintHandler);
this.events.off(EventType.MIGRATING, boundPauseOnMigration);
this.events.off(EventType.ABORTING, boundPauseOnMigration);
}
const finalStats = this.stats.calculate();
const stats = {
requestsFinished: this.stats.state.requestsFinished,
requestsFailed: this.stats.state.requestsFailed,
retryHistogram: this.stats.requestRetryHistogram,
...finalStats,
};
this.log.info('Final request statistics:', stats);
if (this.stats.errorTracker.total !== 0) {
const prettify = ([count, info]: [number, string[]]) => `${count}x: ${info.at(-1)!.trim()} (${info[0]})`;
this.log.info(`Error analysis:`, {
totalErrors: this.stats.errorTracker.total,
uniqueErrors: this.stats.errorTracker.getUniqueErrorCount(),
mostCommonErrors: this.stats.errorTracker.getMostPopularErrors(3).map(prettify),
});
}
const client = this.config.getStorageClient();
if (client.teardown) {
let finished = false;
setTimeout(() => {
if (!finished) {
this.log.info('Waiting for the storage to write its state to file system.');
}
}, 1000);
await client.teardown();
finished = true;
}
periodicLogger.stop();
// eslint-disable-next-line max-len
await this.setStatusMessage(`Finished! Total ${this.stats.state.requestsFinished + this.stats.state.requestsFailed} requests: ${this.stats.state.requestsFinished} succeeded, ${this.stats.state.requestsFailed} failed.`, { isStatusMessageTerminal: true, level: 'INFO' });
this.running = false;
return stats;
}
async getRequestQueue() {
this.requestQueue ??= await RequestQueue.open();
return this.requestQueue!;
}
async useState<State extends Dictionary = Dictionary>(defaultValue = {} as State): Promise<State> {
const kvs = await KeyValueStore.open(null, { config: this.config });
return kvs.getAutoSavedValue<State>(BasicCrawler.CRAWLEE_STATE_KEY, defaultValue);
}
/**
* Adds requests to the queue in batches. By default, it will resolve after the initial batch is added, and continue
* adding the rest in background. You can configure the batch size via `batchSize` option and the sleep time in between
* the batches via `waitBetweenBatchesMillis`. If you want to wait for all batches to be added to the queue, you can use
* the `waitForAllRequestsToBeAdded` promise you get in the response object.
*
* @param requests The requests to add
* @param options Options for the request queue
*/
async addRequests(requests: (string | Source)[], options: CrawlerAddRequestsOptions = {}): Promise<CrawlerAddRequestsResult> {
const requestQueue = await this.getRequestQueue();
return requestQueue.addRequestsBatched(requests, options);
}
protected async _init(): Promise<void> {
if (!this.events.isInitialized()) {
await this.events.init();
this._closeEvents = true;
}
// Initialize AutoscaledPool before awaiting _loadHandledRequestCount(),
// so that the caller can get a reference to it before awaiting the promise returned from run()
// (otherwise there would be no way)
this.autoscaledPool = new AutoscaledPool(this.autoscaledPoolOptions, this.config);
if (this.useSessionPool) {
this.sessionPool = await SessionPool.open(this.sessionPoolOptions, this.config);
// Assuming there are not more than 20 browsers running at once;
this.sessionPool.setMaxListeners(20);
}
await this._loadHandledRequestCount();
}
protected async _runRequestHandler(crawlingContext: Context): Promise<void> {
await this.requestHandler(crawlingContext);
}
/**
* Handles blocked request
*/
protected _throwOnBlockedRequest(session: Session, statusCode: number) {
const isBlocked = session.retireOnBlockedStatusCodes(statusCode);
if (isBlocked) {
throw new Error(`Request blocked - received ${statusCode} status code.`);
}
}
protected async _pauseOnMigration() {
if (this.autoscaledPool) {
// if run wasn't called, this is going to crash
await this.autoscaledPool.pause(SAFE_MIGRATION_WAIT_MILLIS)
.catch((err) => {
if (err.message.includes('running tasks did not finish')) {
this.log.error('The crawler was paused due to migration to another host, '
+ 'but some requests did not finish in time. Those requests\' results may be duplicated.');
} else {
throw err;
}
});
}
const requestListPersistPromise = (async () => {
if (this.requestList) {
if (await this.requestList.isFinished()) return;
await this.requestList.persistState()
.catch((err) => {
if (err.message.includes('Cannot persist state.')) {
this.log.error('The crawler attempted to persist its request list\'s state and failed due to missing or '
+ 'invalid config. Make sure to use either RequestList.open() or the "stateKeyPrefix" option of RequestList '
+ 'constructor to ensure your crawling state is persisted through host migrations and restarts.');
} else {
this.log.exception(err, 'An unexpected error occurred when the crawler '
+ 'attempted to persist its request list\'s state.');
}
});
}
})();
await Promise.all([
requestListPersistPromise,
this.stats.persistState(),
]);
}
/**
* Fetches request from either RequestList or RequestQueue. If request comes from a RequestList
* and RequestQueue is present then enqueues it to the queue first.
*/
protected async _fetchNextRequest() {
if (!this.requestList) return this.requestQueue!.fetchNextRequest();
const request = await this.requestList.fetchNextRequest();
if (!this.requestQueue) return request;
if (!request) return this.requestQueue.fetchNextRequest();
try {
await this.requestQueue.addRequest(request, { forefront: true });
} catch (err) {
// If requestQueue.addRequest() fails here then we must reclaim it back to
// the RequestList because probably it's not yet in the queue!
this.log.error('Adding of request from the RequestList to the RequestQueue failed, reclaiming request back to the list.', { request });
await this.requestList.reclaimRequest(request);
return null;
}
await this.requestList.markRequestHandled(request);
return this.requestQueue.fetchNextRequest();
}
/**
* Executed when `errorHandler` finishes or the request is successful.
* Can be used to clean up orphaned browser pages.
*/
protected async _cleanupContext(
_crawlingContext: Context,
) {}
protected _handleRequestWithDelay(request:Request, source: RequestQueue | RequestList) {
const domain = getDomain(request.url);
if (!domain || !request) {
return false;
}
const now = Date.now();
const lastAccessTime = this.domainAccessedTime.get(domain);
if (!lastAccessTime || (now - lastAccessTime) >= this.sameDomainDelay) {
this.domainAccessedTime.set(domain, now);
return false;
}
const delay = lastAccessTime + this.sameDomainDelay - now;
this.log.debug(`Request ${request.url} (${request.id}) will be reclaimed after ${delay} milliseconds due to same domain delay`);
setTimeout(async () => {
this.log.debug(`Adding request ${request.url} (${request.id}) back to the queue`);
await source?.reclaimRequest(request);
}, delay);