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