@crawlee/playwright 4.0.0-beta.25 → 4.0.0-beta.250
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 +15 -15
- package/index.d.ts +4 -3
- package/index.js +2 -2
- package/internals/adaptive-playwright-crawler.d.ts +145 -74
- package/internals/adaptive-playwright-crawler.js +471 -293
- package/internals/enqueue-links/click-elements.d.ts +36 -64
- package/internals/enqueue-links/click-elements.js +65 -67
- package/internals/playwright-browser-pool.d.ts +55 -0
- package/internals/playwright-browser-pool.js +34 -0
- package/internals/playwright-crawler.d.ts +179 -149
- package/internals/playwright-crawler.js +93 -79
- package/internals/playwright-launcher.d.ts +30 -20
- package/internals/playwright-launcher.js +24 -18
- package/internals/utils/playwright-utils.d.ts +64 -56
- package/internals/utils/playwright-utils.js +117 -138
- package/internals/utils/rendering-type-prediction.d.ts +34 -14
- package/internals/utils/rendering-type-prediction.js +87 -35
- package/package.json +19 -22
- package/index.d.ts.map +0 -1
- package/index.js.map +0 -1
- package/internals/adaptive-playwright-crawler.d.ts.map +0 -1
- package/internals/adaptive-playwright-crawler.js.map +0 -1
- package/internals/enqueue-links/click-elements.d.ts.map +0 -1
- package/internals/enqueue-links/click-elements.js.map +0 -1
- package/internals/playwright-crawler.d.ts.map +0 -1
- package/internals/playwright-crawler.js.map +0 -1
- package/internals/playwright-launcher.d.ts.map +0 -1
- package/internals/playwright-launcher.js.map +0 -1
- package/internals/utils/playwright-utils.d.ts.map +0 -1
- package/internals/utils/playwright-utils.js.map +0 -1
- package/internals/utils/rendering-type-prediction.d.ts.map +0 -1
- package/internals/utils/rendering-type-prediction.js.map +0 -1
|
@@ -1,47 +1,31 @@
|
|
|
1
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
1
2
|
import { isDeepStrictEqual } from 'node:util';
|
|
2
|
-
import { BasicCrawler } from '@crawlee/basic';
|
|
3
|
-
import { extractUrlsFromPage } from '@crawlee/browser';
|
|
3
|
+
import { BasicCrawler, ContextPipeline, ContextPipelineInitializationError, ContextPipelineInterruptedError, navigationDeadlineKey, RequestHandlerError, resolveBaseUrlForEnqueueLinksFiltering, Router, Statistics, } from '@crawlee/basic';
|
|
4
|
+
import { CrawlingRequest, extractUrlsFromPage } from '@crawlee/browser';
|
|
4
5
|
import { CheerioCrawler } from '@crawlee/cheerio';
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
6
|
+
import { ResponseWithUrl } from '@crawlee/http-client';
|
|
7
|
+
import { createStorageTransaction, EnqueueStrategy, OwnedOrInjected } from '@crawlee/core';
|
|
8
|
+
import { extractUrlsFromCheerio, MutationJournal, parseArgument } from '@crawlee/utils/internal';
|
|
9
|
+
import { z } from 'zod';
|
|
7
10
|
import { addTimeoutToPromise } from '@apify/timeout';
|
|
8
11
|
import { PlaywrightCrawler } from './playwright-crawler.js';
|
|
9
|
-
import { RenderingTypePredictor } from './utils/rendering-type-prediction.js';
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
return;
|
|
27
|
-
}
|
|
28
|
-
this.state.httpOnlyRequestHandlerRuns = savedState.httpOnlyRequestHandlerRuns;
|
|
29
|
-
this.state.browserRequestHandlerRuns = savedState.browserRequestHandlerRuns;
|
|
30
|
-
this.state.renderingTypeMispredictions = savedState.renderingTypeMispredictions;
|
|
31
|
-
}
|
|
32
|
-
trackHttpOnlyRequestHandlerRun() {
|
|
33
|
-
this.state.httpOnlyRequestHandlerRuns ??= 0;
|
|
34
|
-
this.state.httpOnlyRequestHandlerRuns += 1;
|
|
35
|
-
}
|
|
36
|
-
trackBrowserRequestHandlerRun() {
|
|
37
|
-
this.state.browserRequestHandlerRuns ??= 0;
|
|
38
|
-
this.state.browserRequestHandlerRuns += 1;
|
|
39
|
-
}
|
|
40
|
-
trackRenderingTypeMisprediction() {
|
|
41
|
-
this.state.renderingTypeMispredictions ??= 0;
|
|
42
|
-
this.state.renderingTypeMispredictions += 1;
|
|
43
|
-
}
|
|
44
|
-
}
|
|
12
|
+
import { RenderingTypePredictor, } from './utils/rendering-type-prediction.js';
|
|
13
|
+
const adaptiveStatisticStateSchema = z.object({
|
|
14
|
+
/** How many requests were handled by the HTTP-only request handler. */
|
|
15
|
+
httpOnlyRequestHandlerRuns: z.number().default(0),
|
|
16
|
+
/** How many requests were handled in a browser. */
|
|
17
|
+
browserRequestHandlerRuns: z.number().default(0),
|
|
18
|
+
/** How many times the HTTP-only handler produced a result the `resultChecker` rejected. */
|
|
19
|
+
renderingTypeMispredictions: z.number().default(0),
|
|
20
|
+
});
|
|
21
|
+
/**
|
|
22
|
+
* The {@link AdaptivePlaywrightCrawlerStatisticState} fields as a {@link Statistics} state extension, defaults
|
|
23
|
+
* and all. A {@link Statistics} instance to be injected into an {@link AdaptivePlaywrightCrawler} has to carry
|
|
24
|
+
* them - `deserialize.extend()` your own fields onto this one and pass the result as `stateExtension`.
|
|
25
|
+
*/
|
|
26
|
+
export const adaptivePlaywrightCrawlerStatisticState = {
|
|
27
|
+
deserialize: adaptiveStatisticStateSchema,
|
|
28
|
+
};
|
|
45
29
|
const proxyLogMethods = [
|
|
46
30
|
'error',
|
|
47
31
|
'exception',
|
|
@@ -60,9 +44,9 @@ const proxyLogMethods = [
|
|
|
60
44
|
* ```javascript
|
|
61
45
|
* const crawler = new AdaptivePlaywrightCrawler({
|
|
62
46
|
* renderingTypeDetectionRatio: 0.1,
|
|
63
|
-
* async requestHandler({
|
|
47
|
+
* async requestHandler({ querySelectorAll, pushData, enqueueLinks, request, log }) {
|
|
64
48
|
* // This function is called to extract data from a single web page
|
|
65
|
-
* const $prices = await
|
|
49
|
+
* const $prices = await querySelectorAll('span.price')
|
|
66
50
|
*
|
|
67
51
|
* await pushData({
|
|
68
52
|
* url: request.url,
|
|
@@ -78,46 +62,93 @@ const proxyLogMethods = [
|
|
|
78
62
|
* 'http://www.example.com/page-2',
|
|
79
63
|
* ]);
|
|
80
64
|
* ```
|
|
81
|
-
*
|
|
82
|
-
* @experimental
|
|
83
65
|
*/
|
|
84
66
|
export class AdaptivePlaywrightCrawler extends BasicCrawler {
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
resultComparator;
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
67
|
+
#renderingTypePredictor;
|
|
68
|
+
#resultChecker;
|
|
69
|
+
#shouldPropagateError;
|
|
70
|
+
#resultComparator;
|
|
71
|
+
#staticContextPipeline;
|
|
72
|
+
#browserContextPipeline;
|
|
73
|
+
#individualRequestHandlerTimeoutMillis;
|
|
74
|
+
/**
|
|
75
|
+
* The write policy of the per-attempt transactions. Defaults the request queue to `deferred`:
|
|
76
|
+
* a discarded attempt's enqueues must never reach the queue.
|
|
77
|
+
*/
|
|
78
|
+
#attemptWritePolicy;
|
|
79
|
+
/** Owns the browser pool this crawler's runs use, so its per-run resources are released with ours. */
|
|
80
|
+
#browserCrawler;
|
|
81
|
+
/** Nothing of its state is per-run, but it owns a session pool that outlives one. */
|
|
82
|
+
#staticCrawler;
|
|
83
|
+
/**
|
|
84
|
+
* In-flight rendering type detections, plus the pending results of an asynchronous `storeResult`.
|
|
85
|
+
*/
|
|
86
|
+
#activeDetections = new Set();
|
|
87
|
+
/**
|
|
88
|
+
* Set once `teardown()` starts, so that requests still in the pool stop opening new detections.
|
|
89
|
+
*/
|
|
90
|
+
#shutDown = false;
|
|
91
|
+
constructor(options = {}) {
|
|
92
|
+
const { requestHandler, renderingTypeDetectionRatio = 0.1, renderingTypePredictor, resultChecker, shouldPropagateError, resultComparator, statistics, requestHandlerTimeoutSecs = 60, errorHandler, failedRequestHandler, preNavigationHooks = [], postNavigationHooks = [], extendContext, transactionalStorage, navigationTimeoutSecs, launchContext, headless, browserPool, remoteBrowser, ...rest } = options;
|
|
93
|
+
// The user's value is replaced by `false` in the `super` call below — validate it separately,
|
|
94
|
+
// wrapped in an object so the error still names the field.
|
|
95
|
+
parseArgument({ transactionalStorage }, z.object({ transactionalStorage: BasicCrawler.optionsShape.transactionalStorage }), 'AdaptivePlaywrightCrawlerOptions');
|
|
96
|
+
// The extra fields are only tracked if the injected instance was built with them - the types enforce that,
|
|
97
|
+
// but plain JS callers would otherwise silently increment `undefined` into a sticky `NaN`. Extend
|
|
98
|
+
// `adaptivePlaywrightCrawlerStatisticState` to satisfy this.
|
|
99
|
+
if (statistics !== undefined) {
|
|
100
|
+
parseArgument(statistics.state, z.object({
|
|
101
|
+
httpOnlyRequestHandlerRuns: z.number(),
|
|
102
|
+
browserRequestHandlerRuns: z.number(),
|
|
103
|
+
renderingTypeMispredictions: z.number(),
|
|
104
|
+
}), 'statistics.state');
|
|
105
|
+
}
|
|
106
|
+
// Per-attempt buffering is load-bearing here: the handler runs up to twice per request and the
|
|
107
|
+
// losing attempt's writes must be discardable.
|
|
108
|
+
if (transactionalStorage === false) {
|
|
109
|
+
throw new Error('AdaptivePlaywrightCrawler requires transactional storage - it runs the request handler ' +
|
|
110
|
+
'multiple times per request and must be able to discard the storage writes of losing ' +
|
|
111
|
+
'attempts. `transactionalStorage: false` is therefore not supported; a write policy ' +
|
|
112
|
+
'object is accepted and forwarded to the per-attempt transactions.');
|
|
113
|
+
}
|
|
97
114
|
super({
|
|
98
115
|
...rest,
|
|
99
|
-
// Pass error handlers to the "main" crawler - we only pluck them from `rest` so that they don't go to the sub crawlers
|
|
100
116
|
errorHandler,
|
|
101
117
|
failedRequestHandler,
|
|
102
|
-
// Same for request handler
|
|
103
118
|
requestHandler,
|
|
104
|
-
|
|
105
|
-
//
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
119
|
+
requestHandlerTimeoutSecs,
|
|
120
|
+
// The base would build a `Statistics` without the adaptive fields, so provide a default that has them.
|
|
121
|
+
// The cast covers a `StatisticStateExtension` that adds further fields - those can only come from an
|
|
122
|
+
// injected instance, in which case this default is never built.
|
|
123
|
+
statistics: statistics ??
|
|
124
|
+
new Statistics({
|
|
125
|
+
logMessage: `${AdaptivePlaywrightCrawler.name} request statistics:`,
|
|
126
|
+
stateExtension: adaptivePlaywrightCrawlerStatisticState,
|
|
127
|
+
}),
|
|
128
|
+
contextPipelineBuilder: () => this.#buildContextPipeline(),
|
|
129
|
+
// The base crawler must not wrap requests in a transaction of its own - this crawler opens
|
|
130
|
+
// one per request handler attempt in `crawlOne` instead, forwarding the write policy of the
|
|
131
|
+
// user-facing option (validated above) to those.
|
|
132
|
+
transactionalStorage: false,
|
|
133
|
+
});
|
|
134
|
+
this.#individualRequestHandlerTimeoutMillis = requestHandlerTimeoutSecs * 1000;
|
|
135
|
+
// `renderingTypeDetectionRatio` only configures the default predictor - an injected one brings its own
|
|
136
|
+
// detection ratio (and its own state), so the option is ignored in that case.
|
|
137
|
+
this.#renderingTypePredictor = OwnedOrInjected.resolve(renderingTypePredictor, () => new RenderingTypePredictor({ detectionRatio: renderingTypeDetectionRatio }));
|
|
138
|
+
this.#attemptWritePolicy = {
|
|
139
|
+
requestQueue: 'deferred',
|
|
140
|
+
...(typeof transactionalStorage === 'object' ? transactionalStorage : {}),
|
|
141
|
+
};
|
|
142
|
+
this.#resultChecker = resultChecker ?? (() => true);
|
|
143
|
+
this.#shouldPropagateError = shouldPropagateError ?? (() => false);
|
|
113
144
|
if (resultComparator !== undefined) {
|
|
114
|
-
this
|
|
145
|
+
this.#resultComparator = resultComparator;
|
|
115
146
|
}
|
|
116
147
|
else if (resultChecker !== undefined) {
|
|
117
|
-
this
|
|
148
|
+
this.#resultComparator = (resultA, resultB, context) => this.#resultChecker(resultA, context) && this.#resultChecker(resultB, context);
|
|
118
149
|
}
|
|
119
150
|
else {
|
|
120
|
-
this
|
|
151
|
+
this.#resultComparator = (resultA, resultB) => {
|
|
121
152
|
return (resultA.datasetItems.length === resultB.datasetItems.length &&
|
|
122
153
|
resultA.datasetItems.every((itemA, i) => {
|
|
123
154
|
const itemB = resultB.datasetItems[i];
|
|
@@ -125,304 +156,451 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
|
|
|
125
156
|
}));
|
|
126
157
|
};
|
|
127
158
|
}
|
|
159
|
+
// `extendContext` is forwarded to the inner crawlers, which run it *before* navigation (see
|
|
160
|
+
// `BasicCrawler`), keeping the behavior consistent with the non-adaptive crawlers: the
|
|
161
|
+
// extension is visible to the pre/post-navigation hooks and the request handler, but cannot
|
|
162
|
+
// access navigation-dependent members (`page`, `response`, `$`, ...).
|
|
163
|
+
//
|
|
164
|
+
// The adaptive hooks target a subset context (`AdaptiveHookContext`); the casts to the inner
|
|
165
|
+
// crawlers' `PlaywrightHook` type relax that nominal difference. The `ContextPipeline` merges
|
|
166
|
+
// each hook's overrides at runtime regardless of the static type.
|
|
128
167
|
const staticCrawler = new CheerioCrawler({
|
|
129
168
|
...rest,
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
for (const hook of preNavigationHooks ?? []) {
|
|
137
|
-
await hook(context, undefined);
|
|
138
|
-
}
|
|
139
|
-
},
|
|
140
|
-
],
|
|
141
|
-
postNavigationHooks: [
|
|
142
|
-
async (context) => {
|
|
143
|
-
for (const hook of postNavigationHooks ?? []) {
|
|
144
|
-
await hook(context, undefined);
|
|
145
|
-
}
|
|
146
|
-
},
|
|
147
|
-
],
|
|
148
|
-
}, config);
|
|
169
|
+
statistics: new Statistics({ persistenceOptions: { enable: false } }),
|
|
170
|
+
preNavigationHooks,
|
|
171
|
+
postNavigationHooks,
|
|
172
|
+
extendContext,
|
|
173
|
+
navigationTimeoutSecs,
|
|
174
|
+
});
|
|
149
175
|
const browserCrawler = new PlaywrightCrawler({
|
|
150
176
|
...rest,
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
},
|
|
161
|
-
],
|
|
162
|
-
postNavigationHooks: [
|
|
163
|
-
async (context, gotoOptions) => {
|
|
164
|
-
for (const hook of postNavigationHooks ?? []) {
|
|
165
|
-
await hook(context, gotoOptions);
|
|
166
|
-
}
|
|
167
|
-
},
|
|
168
|
-
],
|
|
169
|
-
}, config);
|
|
170
|
-
this.teardownHooks.push(browserCrawler.teardown.bind(browserCrawler));
|
|
171
|
-
this.staticContextPipeline = staticCrawler.contextPipeline
|
|
172
|
-
.compose({
|
|
173
|
-
action: this.adaptCheerioContext.bind(this),
|
|
174
|
-
})
|
|
175
|
-
.compose({
|
|
176
|
-
action: async (context) => extendContext ? await extendContext(context) : context,
|
|
177
|
-
});
|
|
178
|
-
this.browserContextPipeline = browserCrawler.contextPipeline
|
|
179
|
-
.compose({
|
|
180
|
-
action: this.adaptPlaywrightContext.bind(this),
|
|
181
|
-
})
|
|
182
|
-
.compose({
|
|
183
|
-
action: async (context) => extendContext ? await extendContext(context) : context,
|
|
177
|
+
statistics: new Statistics({ persistenceOptions: { enable: false } }),
|
|
178
|
+
preNavigationHooks: preNavigationHooks,
|
|
179
|
+
postNavigationHooks: postNavigationHooks,
|
|
180
|
+
extendContext,
|
|
181
|
+
navigationTimeoutSecs,
|
|
182
|
+
launchContext,
|
|
183
|
+
headless,
|
|
184
|
+
browserPool,
|
|
185
|
+
remoteBrowser,
|
|
184
186
|
});
|
|
185
|
-
this
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
});
|
|
190
|
-
this.preventDirectStorageAccess = preventDirectStorageAccess;
|
|
187
|
+
this.#staticCrawler = staticCrawler;
|
|
188
|
+
this.#browserCrawler = browserCrawler;
|
|
189
|
+
this.#staticContextPipeline = staticCrawler.contextPipeline.compose(this.#adaptCheerioContext.bind(this));
|
|
190
|
+
this.#browserContextPipeline = browserCrawler.contextPipeline.compose(this.#adaptPlaywrightContext.bind(this));
|
|
191
191
|
}
|
|
192
|
-
async
|
|
193
|
-
|
|
194
|
-
|
|
192
|
+
async init() {
|
|
193
|
+
// A crawler can be run again after a teardown.
|
|
194
|
+
this.#shutDown = false;
|
|
195
|
+
// Only the predictor we built ourselves is ours to initialize - an injected one is borrowed, so its
|
|
196
|
+
// lifecycle (including restoring persisted state) stays with whoever created it.
|
|
197
|
+
await this.#renderingTypePredictor.ifOwned((predictor) => predictor.initialize());
|
|
198
|
+
return await super.init();
|
|
195
199
|
}
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
200
|
+
#buildContextPipeline() {
|
|
201
|
+
const errorMessage = (prop) => `The \`${prop}\` property is not available on the outer context pipeline of AdaptivePlaywrightCrawler - it is provided by the inner (static/browser) pipelines`;
|
|
202
|
+
return ContextPipeline.create().compose(async ({ request }) => ({
|
|
203
|
+
get request() {
|
|
204
|
+
return request;
|
|
205
|
+
},
|
|
206
|
+
get response() {
|
|
207
|
+
throw new Error(errorMessage('response'));
|
|
208
|
+
},
|
|
209
|
+
get page() {
|
|
210
|
+
throw new Error(errorMessage('page'));
|
|
211
|
+
},
|
|
212
|
+
get querySelectorAll() {
|
|
213
|
+
throw new Error(errorMessage('querySelectorAll'));
|
|
214
|
+
},
|
|
215
|
+
get querySelectorOne() {
|
|
216
|
+
throw new Error(errorMessage('querySelectorOne'));
|
|
217
|
+
},
|
|
218
|
+
get waitForSelector() {
|
|
219
|
+
throw new Error(errorMessage('waitForSelector'));
|
|
220
|
+
},
|
|
221
|
+
get parseWithCheerio() {
|
|
222
|
+
throw new Error(errorMessage('parseWithCheerio'));
|
|
223
|
+
},
|
|
224
|
+
get enqueueLinks() {
|
|
225
|
+
throw new Error(errorMessage('enqueueLinks'));
|
|
226
|
+
},
|
|
227
|
+
}));
|
|
228
|
+
}
|
|
229
|
+
async #adaptCheerioContext(cheerioContext) {
|
|
202
230
|
return {
|
|
203
231
|
get page() {
|
|
204
232
|
throw new Error('Page object was used in HTTP-only request handler');
|
|
205
233
|
},
|
|
206
|
-
async querySelector(selector) {
|
|
207
|
-
return cheerioContext.$(selector);
|
|
208
|
-
},
|
|
209
234
|
enqueueLinks: async (options = {}) => {
|
|
210
|
-
const urls = options.
|
|
211
|
-
|
|
212
|
-
return (await this.enqueueLinks({ ...options, urls }, cheerioContext.request, result));
|
|
235
|
+
const urls = extractUrlsFromCheerio(cheerioContext.$, options.selector, options.baseUrl ?? cheerioContext.request.loadedUrl);
|
|
236
|
+
return (await this.#enqueueLinks(urls, options, cheerioContext.request));
|
|
213
237
|
},
|
|
214
|
-
|
|
238
|
+
// The HTTP crawler has already consumed the body; hand out a fresh copy, like the browser side does.
|
|
239
|
+
// HTML bodies are already decoded to UTF-8, so `arrayBuffer()` may disagree with the original headers.
|
|
240
|
+
response: new ResponseWithUrl(cheerioContext.body, cheerioContext.response),
|
|
215
241
|
};
|
|
216
242
|
}
|
|
217
|
-
async adaptPlaywrightContext(playwrightContext) {
|
|
243
|
+
async #adaptPlaywrightContext(playwrightContext) {
|
|
244
|
+
// Capture the original response to avoid infinite recursion when the getter is copied to the context
|
|
218
245
|
const originalResponse = playwrightContext.response;
|
|
219
|
-
const result = this.resultObjects.get(playwrightContext);
|
|
220
|
-
if (result === undefined) {
|
|
221
|
-
throw new Error('Logical error - `this.resultObjects` does not contain the result object');
|
|
222
|
-
}
|
|
223
246
|
return {
|
|
224
|
-
response: new
|
|
247
|
+
response: new ResponseWithUrl(Uint8Array.from(await originalResponse.body()), {
|
|
225
248
|
headers: originalResponse.headers(),
|
|
226
249
|
status: originalResponse.status(),
|
|
227
250
|
statusText: originalResponse.statusText(),
|
|
251
|
+
url: originalResponse.url(),
|
|
228
252
|
}),
|
|
229
|
-
async querySelector(selector, timeoutMs = 5000) {
|
|
230
|
-
const locator = playwrightContext.page.locator(selector).first();
|
|
231
|
-
await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
|
|
232
|
-
const $ = await playwrightContext.parseWithCheerio();
|
|
233
|
-
return $(selector);
|
|
234
|
-
},
|
|
235
253
|
enqueueLinks: async (options = {}, timeoutMs = 5000) => {
|
|
236
254
|
// TODO consider using `context.parseWithCheerio` to make this universal and avoid code duplication
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
else {
|
|
247
|
-
urls = options.urls;
|
|
248
|
-
}
|
|
249
|
-
return (await this.enqueueLinks({ ...options, urls }, playwrightContext.request, result));
|
|
255
|
+
const selector = options.selector ?? 'a';
|
|
256
|
+
const locator = playwrightContext.page.locator(selector).first();
|
|
257
|
+
// Wait for client-rendered links, but like the HTTP side, enqueue nothing when there are none.
|
|
258
|
+
await locator.waitFor({ timeout: timeoutMs, state: 'attached' }).catch((error) => {
|
|
259
|
+
if (error.name !== 'TimeoutError')
|
|
260
|
+
throw error;
|
|
261
|
+
});
|
|
262
|
+
const urls = await extractUrlsFromPage(playwrightContext.page, selector, options.baseUrl ?? playwrightContext.request.loadedUrl);
|
|
263
|
+
return (await this.#enqueueLinks(urls, options, playwrightContext.request));
|
|
250
264
|
},
|
|
251
265
|
};
|
|
252
266
|
}
|
|
253
|
-
|
|
254
|
-
|
|
267
|
+
/**
|
|
268
|
+
* Runs one request handler attempt inside its own {@link StorageTransaction}, wrapping the inner
|
|
269
|
+
* (static or browser) context pipeline. The transaction is pushed to `transactions` *at creation
|
|
270
|
+
* time, before the `try`*, as failed attempts are routine here. The caller owns the outcome and
|
|
271
|
+
* disposal, including closing or reverting the {@link ContextModifications}.
|
|
272
|
+
*
|
|
273
|
+
* `request` defaults to the context's; a detection rerun passes a copy so it sees the request as it
|
|
274
|
+
* was before the browser attempt.
|
|
275
|
+
*/
|
|
276
|
+
async #crawlOne(renderingType, context, useStateFunction, transactions, request = context.request) {
|
|
277
|
+
const transaction = createStorageTransaction({
|
|
278
|
+
policy: this.#attemptWritePolicy,
|
|
279
|
+
commitTimeoutMillis: this.internalTimeoutMillis,
|
|
280
|
+
});
|
|
281
|
+
transactions.push(transaction);
|
|
255
282
|
const logs = [];
|
|
256
283
|
const deferredCleanup = [];
|
|
257
|
-
const
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
log: this
|
|
284
|
+
const contextModifications = {
|
|
285
|
+
request: new MutationJournal(),
|
|
286
|
+
state: new MutationJournal(),
|
|
287
|
+
};
|
|
288
|
+
const subCrawlerContext = Object.defineProperties({}, Object.getOwnPropertyDescriptors(context));
|
|
289
|
+
const attemptBoundContextHelpers = {
|
|
290
|
+
request: contextModifications.request.track(request),
|
|
291
|
+
useState: async (defaultValue) => contextModifications.state.track(await useStateFunction(defaultValue)),
|
|
292
|
+
log: this.#createLogProxy(context.log, logs),
|
|
266
293
|
registerDeferredCleanup: (cleanup) => deferredCleanup.push(cleanup),
|
|
294
|
+
// The sub-crawler pipeline keeps this attempt's navigation deadline on `subCrawlerContext`, but the
|
|
295
|
+
// outer `extendTimeout` only pushes the deadline it finds on `context`, so push this one as well.
|
|
296
|
+
extendTimeout: (secs) => {
|
|
297
|
+
context.extendTimeout(secs);
|
|
298
|
+
if (subCrawlerContext[navigationDeadlineKey] !== undefined) {
|
|
299
|
+
subCrawlerContext[navigationDeadlineKey] += secs * 1000;
|
|
300
|
+
}
|
|
301
|
+
},
|
|
267
302
|
};
|
|
268
|
-
|
|
269
|
-
|
|
303
|
+
// Mark attempt-bound helpers as non-configurable so they survive the sub-crawler context pipeline
|
|
304
|
+
// (which would otherwise override them with the sub-crawler's own versions, losing the binding).
|
|
305
|
+
for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(attemptBoundContextHelpers))) {
|
|
306
|
+
Object.defineProperty(subCrawlerContext, key, { ...descriptor, configurable: false });
|
|
307
|
+
}
|
|
270
308
|
try {
|
|
309
|
+
// Any failure - middleware or handler - ends up in the `ok: false` branch below.
|
|
310
|
+
const rethrow = (error) => {
|
|
311
|
+
throw error;
|
|
312
|
+
};
|
|
271
313
|
const callAdaptiveRequestHandler = async () => {
|
|
272
314
|
if (renderingType === 'static') {
|
|
273
|
-
await this
|
|
315
|
+
await this.#staticContextPipeline.call(subCrawlerContext, this.requestHandler.bind(this), rethrow);
|
|
274
316
|
}
|
|
275
317
|
else if (renderingType === 'clientOnly') {
|
|
276
|
-
await this
|
|
318
|
+
await this.#browserContextPipeline.call(subCrawlerContext, this.requestHandler.bind(this), rethrow);
|
|
277
319
|
}
|
|
278
320
|
};
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
return {
|
|
321
|
+
// this crawler overrides `runRequestHandler` and times each rendering-type run itself, so it has
|
|
322
|
+
// to resolve any per-route override too - otherwise routes would be silently ignored here
|
|
323
|
+
const routeTimeoutSecs = this.requestHandler.getTimeoutSecs?.(context.request.label);
|
|
324
|
+
const timeoutMillis = routeTimeoutSecs === undefined ? this.#individualRequestHandlerTimeoutMillis : routeTimeoutSecs * 1000;
|
|
325
|
+
await addTimeoutToPromise(async () => transaction.run(callAdaptiveRequestHandler), timeoutMillis, 'Request handler timed out');
|
|
326
|
+
return { ok: true, transaction, contextModifications, logs };
|
|
285
327
|
}
|
|
286
328
|
catch (error) {
|
|
287
|
-
return {
|
|
329
|
+
return { ok: false, error, transaction, contextModifications, logs };
|
|
288
330
|
}
|
|
289
331
|
finally {
|
|
290
332
|
await Promise.all(deferredCleanup.map((cleanup) => cleanup()));
|
|
291
333
|
}
|
|
292
334
|
}
|
|
293
335
|
async runRequestHandler(crawlingContext) {
|
|
294
|
-
const renderingTypePrediction = this
|
|
295
|
-
const shouldDetectRenderingType = Math.random() < renderingTypePrediction.detectionProbabilityRecommendation;
|
|
336
|
+
const renderingTypePrediction = await this.#renderingTypePredictor.value.predict(crawlingContext.request);
|
|
337
|
+
const shouldDetectRenderingType = !this.#shutDown && Math.random() < renderingTypePrediction.detectionProbabilityRecommendation;
|
|
296
338
|
if (!shouldDetectRenderingType) {
|
|
297
339
|
crawlingContext.log.debug(`Predicted rendering type ${renderingTypePrediction.renderingType} for ${crawlingContext.request.url}`);
|
|
298
340
|
}
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
this.stats.trackRenderingTypeMisprediction();
|
|
319
|
-
}
|
|
320
|
-
}
|
|
321
|
-
crawlingContext.log.debug(`Running browser request handler for ${crawlingContext.request.url}`);
|
|
322
|
-
this.stats.trackBrowserRequestHandlerRun();
|
|
323
|
-
// Run the request handler in a browser. The copy of the crawler state is kept so that we can perform
|
|
324
|
-
// a rendering type detection if necessary. Without this measure, the HTTP request handler would run
|
|
325
|
-
// under different conditions, which could change its behavior. Changes done to the crawler state by
|
|
326
|
-
// the HTTP request handler will not be committed to the actual storage.
|
|
327
|
-
const stateTracker = {
|
|
328
|
-
stateCopy: null,
|
|
329
|
-
async getLiveState(defaultValue = {}) {
|
|
330
|
-
const state = await crawlingContext.useState(defaultValue);
|
|
331
|
-
if (this.stateCopy === null) {
|
|
332
|
-
this.stateCopy = JSON.parse(JSON.stringify(state));
|
|
333
|
-
}
|
|
334
|
-
return state;
|
|
335
|
-
},
|
|
336
|
-
async getStateCopy(defaultValue = {}) {
|
|
337
|
-
if (this.stateCopy === null) {
|
|
338
|
-
return defaultValue;
|
|
341
|
+
// Every transaction created for this request - up to two, since the static-then-browser
|
|
342
|
+
// fall-through and the browser-then-detection pair are mutually exclusive. Disposed in the
|
|
343
|
+
// `finally` below, not earlier: the comparators read the journals after `crawlOne` returns.
|
|
344
|
+
const transactions = [];
|
|
345
|
+
try {
|
|
346
|
+
// A result the `resultChecker` rejected is as good as a detection saying the page needs a browser - but
|
|
347
|
+
// only once the browser run has succeeded. A thrown error says nothing about rendering.
|
|
348
|
+
let httpResultRejected = false;
|
|
349
|
+
if (renderingTypePrediction.renderingType === 'static' && !shouldDetectRenderingType) {
|
|
350
|
+
crawlingContext.log.debug(`Running HTTP-only request handler for ${crawlingContext.request.url}`);
|
|
351
|
+
this.statistics.state.httpOnlyRequestHandlerRuns++;
|
|
352
|
+
const plainHTTPRun = await this.#crawlOne('static', crawlingContext, crawlingContext.useState, transactions);
|
|
353
|
+
if (plainHTTPRun.ok &&
|
|
354
|
+
this.#resultChecker(plainHTTPRun.transaction, { request: crawlingContext.request })) {
|
|
355
|
+
crawlingContext.log.debug(`HTTP-only request handler succeeded for ${crawlingContext.request.url}`);
|
|
356
|
+
plainHTTPRun.logs.forEach(([log, method, ...args]) => log[method](...args));
|
|
357
|
+
this.#keepContextModifications(plainHTTPRun.contextModifications);
|
|
358
|
+
await plainHTTPRun.transaction.commit();
|
|
359
|
+
return;
|
|
339
360
|
}
|
|
340
|
-
|
|
341
|
-
},
|
|
342
|
-
};
|
|
343
|
-
const browserRun = await this.crawlOne('clientOnly', crawlingContext, stateTracker.getLiveState.bind(stateTracker));
|
|
344
|
-
if (!browserRun.ok) {
|
|
345
|
-
throw browserRun.error;
|
|
346
|
-
}
|
|
347
|
-
await this.commitResult(crawlingContext, browserRun.result);
|
|
348
|
-
if (shouldDetectRenderingType) {
|
|
349
|
-
crawlingContext.log.debug(`Detecting rendering type for ${crawlingContext.request.url}`);
|
|
350
|
-
const plainHTTPRun = await this.crawlOne('static', crawlingContext, stateTracker.getStateCopy.bind(stateTracker));
|
|
351
|
-
const detectionResult = (() => {
|
|
361
|
+
// Execution will "fall through" and try running the request handler in a browser
|
|
352
362
|
if (!plainHTTPRun.ok) {
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
363
|
+
const actualError = plainHTTPRun.error instanceof RequestHandlerError ||
|
|
364
|
+
plainHTTPRun.error instanceof ContextPipelineInitializationError
|
|
365
|
+
? plainHTTPRun.error.cause
|
|
366
|
+
: plainHTTPRun.error;
|
|
367
|
+
if (actualError instanceof ContextPipelineInterruptedError ||
|
|
368
|
+
(await this.#shouldPropagateError(actualError, crawlingContext))) {
|
|
369
|
+
this.#keepContextModifications(plainHTTPRun.contextModifications);
|
|
370
|
+
throw actualError;
|
|
371
|
+
}
|
|
372
|
+
crawlingContext.log.exception(actualError, `HTTP-only request handler failed for ${crawlingContext.request.url}`);
|
|
358
373
|
}
|
|
359
|
-
|
|
360
|
-
|
|
374
|
+
else {
|
|
375
|
+
crawlingContext.log.warning(`HTTP-only request handler returned a suspicious result for ${crawlingContext.request.url}`);
|
|
376
|
+
this.statistics.state.renderingTypeMispredictions++;
|
|
377
|
+
httpResultRejected = true;
|
|
361
378
|
}
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
379
|
+
// The browser attempt starts from the request and state as they were before the rejected one.
|
|
380
|
+
this.#discardContextModifications(plainHTTPRun.contextModifications, crawlingContext);
|
|
381
|
+
}
|
|
382
|
+
crawlingContext.log.debug(`Running browser request handler for ${crawlingContext.request.url}`);
|
|
383
|
+
this.statistics.state.browserRequestHandlerRuns++;
|
|
384
|
+
const browserRun = await this.#crawlOne('clientOnly', crawlingContext, crawlingContext.useState, transactions);
|
|
385
|
+
if (!browserRun.ok) {
|
|
386
|
+
// A failed browser attempt is handed to the retry logic with its writes - `userData` stashed for the
|
|
387
|
+
// next attempt must survive.
|
|
388
|
+
this.#keepContextModifications(browserRun.contextModifications);
|
|
389
|
+
throw browserRun.error;
|
|
390
|
+
}
|
|
391
|
+
try {
|
|
392
|
+
browserRun.logs.forEach(([log, method, ...args]) => log[method](...args));
|
|
393
|
+
// The `afterStorageCommit` callbacks belong to this attempt, so the detection rerun undoes their
|
|
394
|
+
// writes too - the journals stay open until they have run.
|
|
395
|
+
await browserRun.transaction.commit();
|
|
396
|
+
}
|
|
397
|
+
finally {
|
|
398
|
+
this.#keepContextModifications(browserRun.contextModifications);
|
|
399
|
+
}
|
|
400
|
+
// Past the shutdown fence, `teardown()` has already drained - and possibly torn down the predictor.
|
|
401
|
+
if (httpResultRejected && !this.#shutDown) {
|
|
402
|
+
this.#storeRenderingType(crawlingContext.request, 'clientOnly');
|
|
403
|
+
}
|
|
404
|
+
if (shouldDetectRenderingType) {
|
|
405
|
+
const detectionPromise = (async () => {
|
|
406
|
+
crawlingContext.log.debug(`Detecting rendering type for ${crawlingContext.request.url}`);
|
|
407
|
+
// The detection attempt's transaction is never committed - its writes exist only for the
|
|
408
|
+
// result comparison. It runs on copies of the request and the crawler state with the browser
|
|
409
|
+
// attempt's writes undone, so both attempts start from the same conditions, and the copies go
|
|
410
|
+
// away with it.
|
|
411
|
+
const { request: requestJournal, state: stateJournal } = browserRun.contextModifications;
|
|
412
|
+
let stateCopy;
|
|
413
|
+
const plainHTTPRun = await this.#crawlOne('static', crawlingContext, async (defaultValue) => (stateCopy ??= stateJournal.undoOnto(JSON.parse(JSON.stringify(await crawlingContext.useState(defaultValue))))), transactions, requestJournal.undoOnto(CrawlingRequest.fromSchema(JSON.parse(JSON.stringify(crawlingContext.request)))));
|
|
414
|
+
const detectionResult = (() => {
|
|
415
|
+
if (!plainHTTPRun.ok) {
|
|
416
|
+
return 'clientOnly';
|
|
417
|
+
}
|
|
418
|
+
const comparisonResult = this.#resultComparator(plainHTTPRun.transaction, browserRun.transaction, {
|
|
419
|
+
request: crawlingContext.request,
|
|
420
|
+
});
|
|
421
|
+
if (comparisonResult === true || comparisonResult === 'equal') {
|
|
422
|
+
return 'static';
|
|
423
|
+
}
|
|
424
|
+
if (comparisonResult === false || comparisonResult === 'different') {
|
|
425
|
+
return 'clientOnly';
|
|
426
|
+
}
|
|
427
|
+
return undefined;
|
|
428
|
+
})();
|
|
429
|
+
crawlingContext.log.debug(`Detected rendering type ${detectionResult} for ${crawlingContext.request.url}`);
|
|
430
|
+
if (detectionResult !== undefined) {
|
|
431
|
+
this.#storeRenderingType(crawlingContext.request, detectionResult);
|
|
432
|
+
}
|
|
433
|
+
})();
|
|
434
|
+
await this.#trackDetection(detectionPromise);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
finally {
|
|
438
|
+
// A still-open transaction here belongs to a discarded attempt - roll it back, then release.
|
|
439
|
+
for (const transaction of transactions) {
|
|
440
|
+
transaction.rollback();
|
|
441
|
+
transaction.dispose();
|
|
367
442
|
}
|
|
368
443
|
}
|
|
369
444
|
}
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
...calls.addRequests.map(async (params) => crawlingContext.addRequests(...params)),
|
|
374
|
-
...Object.entries(keyValueStoreChanges).map(async ([storeIdOrName, changes]) => {
|
|
375
|
-
const store = await crawlingContext.getKeyValueStore(storeIdOrName);
|
|
376
|
-
await Promise.all(Object.entries(changes).map(async ([key, { changedValue, options }]) => store.setValue(key, changedValue, options)));
|
|
377
|
-
}),
|
|
378
|
-
]);
|
|
445
|
+
#keepContextModifications(modifications) {
|
|
446
|
+
modifications.request.close();
|
|
447
|
+
modifications.state.close();
|
|
379
448
|
}
|
|
380
|
-
|
|
381
|
-
|
|
449
|
+
#discardContextModifications(modifications, { request, log }) {
|
|
450
|
+
// Nothing else writes to a request while its handler runs, so a conflict means a write that bypassed
|
|
451
|
+
// the context (e.g. through a stashed reference) - it stays, but it is not what the retry logic expects.
|
|
452
|
+
modifications.request.revert({
|
|
453
|
+
onConflict: (key) => log.warning(`Request ${request.url}: '${String(key)}' was modified outside the request handler`),
|
|
454
|
+
});
|
|
455
|
+
// The state is shared with concurrent handlers; a conflict is one of them having written the same
|
|
456
|
+
// property meanwhile. Their value wins, and this attempt's write stays with it.
|
|
457
|
+
modifications.state.revert({
|
|
458
|
+
onConflict: (key) => log.debug(`Crawler state '${String(key)}' was changed concurrently; keeping the newer value`),
|
|
459
|
+
});
|
|
382
460
|
}
|
|
383
|
-
|
|
461
|
+
#storeRenderingType(request, renderingType) {
|
|
462
|
+
// Deliberately not awaited: a predictor that persists asynchronously gets to keep batching its writes,
|
|
463
|
+
// and `drainRenderingDetections()` catches whatever is still pending.
|
|
464
|
+
const stored = this.#renderingTypePredictor.value.storeResult(request, renderingType);
|
|
465
|
+
if (stored !== undefined) {
|
|
466
|
+
// Nothing downstream awaits this, so a failed write would otherwise be silent.
|
|
467
|
+
void this.#trackDetection(Promise.resolve(stored).catch((error) => this.log.exception(error, `Failed to store the rendering type detection result for ${request.url}`)));
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
async #enqueueLinks(urls, options, request) {
|
|
384
471
|
const baseUrl = resolveBaseUrlForEnqueueLinksFiltering({
|
|
385
472
|
enqueueStrategy: options?.strategy,
|
|
386
473
|
finalRequestUrl: request.loadedUrl,
|
|
387
474
|
originalRequestUrl: request.url,
|
|
388
475
|
userProvidedBaseUrl: options?.baseUrl,
|
|
389
476
|
});
|
|
390
|
-
const
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
})),
|
|
399
|
-
waitForAllRequestsToBeAdded: Promise.resolve([]),
|
|
400
|
-
};
|
|
401
|
-
};
|
|
402
|
-
// We need to use a mock request queue implementation, in order to add the requests into our result object
|
|
403
|
-
const mockRequestQueue = { addRequestsBatched };
|
|
404
|
-
return await this.enqueueLinksWithCrawlDepth({ ...options, baseUrl }, request, mockRequestQueue);
|
|
477
|
+
const requestsWithDepth = this.addCrawlDepthRequestGenerator(urls, request.crawlDepth + 1);
|
|
478
|
+
// The per-attempt transaction buffers these (the queue policy defaults to `deferred` here),
|
|
479
|
+
// so a discarded attempt's enqueues never reach the queue.
|
|
480
|
+
return await this.addRequests(requestsWithDepth, {
|
|
481
|
+
...options,
|
|
482
|
+
baseUrl,
|
|
483
|
+
strategy: options.strategy ?? EnqueueStrategy.SameHostname,
|
|
484
|
+
});
|
|
405
485
|
}
|
|
406
|
-
createLogProxy(log, logs) {
|
|
486
|
+
#createLogProxy(log, logs) {
|
|
407
487
|
return new Proxy(log, {
|
|
408
|
-
get(target, propertyName
|
|
488
|
+
get(target, propertyName) {
|
|
409
489
|
if (proxyLogMethods.includes(propertyName)) {
|
|
410
490
|
return (...args) => {
|
|
411
491
|
logs.push([target, propertyName, ...args]);
|
|
412
492
|
};
|
|
413
493
|
}
|
|
414
|
-
|
|
494
|
+
const value = Reflect.get(target, propertyName, target);
|
|
495
|
+
// Bind non-intercepted methods to the target instance so private #-fields
|
|
496
|
+
// (e.g. BaseCrawleeLogger.#options, #warningsLogged) do not throw TypeError at runtime.
|
|
497
|
+
if (typeof value === 'function') {
|
|
498
|
+
return value.bind(target);
|
|
499
|
+
}
|
|
500
|
+
return value;
|
|
415
501
|
},
|
|
416
502
|
});
|
|
417
503
|
}
|
|
504
|
+
#trackDetection(promise) {
|
|
505
|
+
this.#activeDetections.add(promise);
|
|
506
|
+
// Not `finally()`: the promise it derives would reject on its own and go unhandled. A rejection here
|
|
507
|
+
// belongs to whoever awaits the original, or to `allSettled` in the drain.
|
|
508
|
+
void promise.catch(() => { }).then(() => this.#activeDetections.delete(promise));
|
|
509
|
+
return promise;
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* Number of rendering type detections that have not settled yet, including results the predictor is
|
|
513
|
+
* still persisting.
|
|
514
|
+
*/
|
|
515
|
+
get inFlightRenderingTypeDetectionCount() {
|
|
516
|
+
return this.#activeDetections.size;
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* Waits for in-flight rendering type detections to settle, bounded by `timeoutMillis` (defaults to the
|
|
520
|
+
* internal timeout).
|
|
521
|
+
*/
|
|
522
|
+
async drainRenderingDetections({ timeoutMillis } = {}) {
|
|
523
|
+
if (this.#activeDetections.size === 0) {
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
const drained = (async () => {
|
|
527
|
+
while (this.#activeDetections.size > 0) {
|
|
528
|
+
await Promise.allSettled(Array.from(this.#activeDetections));
|
|
529
|
+
}
|
|
530
|
+
})();
|
|
531
|
+
const millis = timeoutMillis ?? this.internalTimeoutMillis;
|
|
532
|
+
// A caller opting out of the bound would otherwise get an immediate spurious timeout - `setTimeout`
|
|
533
|
+
// clamps a non-finite delay to 1ms.
|
|
534
|
+
if (!Number.isFinite(millis)) {
|
|
535
|
+
await drained;
|
|
536
|
+
return;
|
|
537
|
+
}
|
|
538
|
+
const abortTimer = new AbortController();
|
|
539
|
+
try {
|
|
540
|
+
const outcome = await Promise.race([
|
|
541
|
+
drained.then(() => 'drained'),
|
|
542
|
+
delay(millis, 'timedOut', { signal: abortTimer.signal }).catch(() => 'aborted'),
|
|
543
|
+
]);
|
|
544
|
+
if (outcome === 'timedOut') {
|
|
545
|
+
this.log.warning(`Timed out after ${millis / 1e3} seconds waiting for ${this.#activeDetections.size} rendering type detection(s) to settle - their results may be lost.`);
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
finally {
|
|
549
|
+
abortTimer.abort();
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* Stops the crawler immediately, but not before rendering type detections already under way (and results
|
|
554
|
+
* the predictor is still persisting) have settled - see
|
|
555
|
+
* {@link AdaptivePlaywrightCrawler.drainRenderingDetections|`drainRenderingDetections()`}. Requests
|
|
556
|
+
* that are still running are not waited for, unlike {@link BasicCrawler.stop|`stop()`}.
|
|
557
|
+
*/
|
|
418
558
|
async teardown() {
|
|
559
|
+
// Called from outside `run()` - under `keepAlive`, say - the pool keeps dispatching until
|
|
560
|
+
// `super.teardown()` aborts it, and a request starting during the drain would open a detection the
|
|
561
|
+
// drain has already passed. Closing that first makes the drain a fence.
|
|
562
|
+
this.#shutDown = true;
|
|
563
|
+
await this.drainRenderingDetections();
|
|
419
564
|
await super.teardown();
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
565
|
+
// Mirrors the owned-only `initialize()` in `init()` - without this, the predictor we built keeps its
|
|
566
|
+
// PERSIST_STATE listener registered after the crawl and never gets a final write.
|
|
567
|
+
await this.#renderingTypePredictor.ifOwned((predictor) => predictor.teardown());
|
|
568
|
+
await this.#browserCrawler.teardown();
|
|
423
569
|
}
|
|
570
|
+
async destroy() {
|
|
571
|
+
await super.destroy();
|
|
572
|
+
await this.#staticCrawler.destroy();
|
|
573
|
+
await this.#browserCrawler.destroy();
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
export function createAdaptivePlaywrightRouter(routesOrSchemas) {
|
|
577
|
+
return Router.create(routesOrSchemas);
|
|
424
578
|
}
|
|
425
|
-
|
|
426
|
-
|
|
579
|
+
/**
|
|
580
|
+
* An opt-in {@link AdaptivePlaywrightCrawlerOptions.resultComparator|`resultComparator`} that considers two
|
|
581
|
+
* request handler results equal only if *all* of their observable effects match - the pushed dataset items, the
|
|
582
|
+
* enqueued requests, and the key-value store changes. This is stricter than the default comparator, which only
|
|
583
|
+
* compares dataset items.
|
|
584
|
+
*
|
|
585
|
+
* **Beware:** enqueued URLs are compared exactly. The same page rendered in a browser and via plain HTTP often
|
|
586
|
+
* yields links that differ only in tracking query parameters, for example:
|
|
587
|
+
* - `https://sdk.apify.com/docs/guides/getting-started`
|
|
588
|
+
* - `https://sdk.apify.com/docs/guides/getting-started?__hsfp=1136113150&__hssc=7591405.1.173549427712`
|
|
589
|
+
*
|
|
590
|
+
* Such links are treated as *different*, which will make the crawler favor browser rendering for those pages.
|
|
591
|
+
*
|
|
592
|
+
* **Example usage:**
|
|
593
|
+
* ```ts
|
|
594
|
+
* const crawler = new AdaptivePlaywrightCrawler({
|
|
595
|
+
* resultComparator: fullResultComparator,
|
|
596
|
+
* async requestHandler({ pushData, enqueueLinks }) {
|
|
597
|
+
* // ...
|
|
598
|
+
* },
|
|
599
|
+
* });
|
|
600
|
+
* ```
|
|
601
|
+
*/
|
|
602
|
+
export function fullResultComparator(resultA, resultB) {
|
|
603
|
+
return (isDeepStrictEqual(resultA.datasetItems, resultB.datasetItems) &&
|
|
604
|
+
isDeepStrictEqual(resultA.enqueuedUrls, resultB.enqueuedUrls) &&
|
|
605
|
+
isDeepStrictEqual(resultA.keyValueStoreChanges, resultB.keyValueStoreChanges));
|
|
427
606
|
}
|
|
428
|
-
//# sourceMappingURL=adaptive-playwright-crawler.js.map
|