@crawlee/playwright 4.0.0-rc.0 → 4.0.0-rc.2

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.
@@ -1,9 +1,11 @@
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 { createStorageTransaction, EnqueueStrategy, OwnedOrInjected, parseArgument, RequestHandlerError, resolveBaseUrlForEnqueueLinksFiltering, Router, Statistics, } from '@crawlee/core';
6
- import { extractUrlsFromCheerio } from '@crawlee/utils/internal';
6
+ import { ResponseWithUrl } from '@crawlee/http-client';
7
+ import { createStorageTransaction, EnqueueStrategy, OwnedOrInjected } from '@crawlee/core';
8
+ import { extractUrlsFromCheerio, MutationJournal, parseArgument } from '@crawlee/utils/internal';
7
9
  import { z } from 'zod';
8
10
  import { addTimeoutToPromise } from '@apify/timeout';
9
11
  import { PlaywrightCrawler } from './playwright-crawler.js';
@@ -42,9 +44,9 @@ const proxyLogMethods = [
42
44
  * ```javascript
43
45
  * const crawler = new AdaptivePlaywrightCrawler({
44
46
  * renderingTypeDetectionRatio: 0.1,
45
- * async requestHandler({ querySelector, pushData, enqueueLinks, request, log }) {
47
+ * async requestHandler({ querySelectorAll, pushData, enqueueLinks, request, log }) {
46
48
  * // This function is called to extract data from a single web page
47
- * const $prices = await querySelector('span.price')
49
+ * const $prices = await querySelectorAll('span.price')
48
50
  *
49
51
  * await pushData({
50
52
  * url: request.url,
@@ -60,8 +62,6 @@ const proxyLogMethods = [
60
62
  * 'http://www.example.com/page-2',
61
63
  * ]);
62
64
  * ```
63
- *
64
- * @experimental
65
65
  */
66
66
  export class AdaptivePlaywrightCrawler extends BasicCrawler {
67
67
  #renderingTypePredictor;
@@ -76,9 +76,20 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
76
76
  * a discarded attempt's enqueues must never reach the queue.
77
77
  */
78
78
  #attemptWritePolicy;
79
- #teardownHooks = [];
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;
80
91
  constructor(options = {}) {
81
- const { requestHandler, renderingTypeDetectionRatio = 0.1, renderingTypePredictor, resultChecker, shouldPropagateError, resultComparator, statistics, requestHandlerTimeoutSecs = 60, errorHandler, failedRequestHandler, preNavigationHooks = [], postNavigationHooks = [], extendContext, contextPipelineBuilder, transactionalStorage, ...rest } = 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;
82
93
  // The user's value is replaced by `false` in the `super` call below — validate it separately,
83
94
  // wrapped in an object so the error still names the field.
84
95
  parseArgument({ transactionalStorage }, z.object({ transactionalStorage: BasicCrawler.optionsShape.transactionalStorage }), 'AdaptivePlaywrightCrawlerOptions');
@@ -114,7 +125,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
114
125
  logMessage: `${AdaptivePlaywrightCrawler.name} request statistics:`,
115
126
  stateExtension: adaptivePlaywrightCrawlerStatisticState,
116
127
  }),
117
- contextPipelineBuilder: contextPipelineBuilder ?? (() => this.buildContextPipeline()),
128
+ contextPipelineBuilder: () => this.#buildContextPipeline(),
118
129
  // The base crawler must not wrap requests in a transaction of its own - this crawler opens
119
130
  // one per request handler attempt in `crawlOne` instead, forwarding the write policy of the
120
131
  // user-facing option (validated above) to those.
@@ -134,7 +145,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
134
145
  this.#resultComparator = resultComparator;
135
146
  }
136
147
  else if (resultChecker !== undefined) {
137
- this.#resultComparator = (resultA, resultB) => this.#resultChecker(resultA) && this.#resultChecker(resultB);
148
+ this.#resultComparator = (resultA, resultB, context) => this.#resultChecker(resultA, context) && this.#resultChecker(resultB, context);
138
149
  }
139
150
  else {
140
151
  this.#resultComparator = (resultA, resultB) => {
@@ -159,6 +170,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
159
170
  preNavigationHooks,
160
171
  postNavigationHooks,
161
172
  extendContext,
173
+ navigationTimeoutSecs,
162
174
  });
163
175
  const browserCrawler = new PlaywrightCrawler({
164
176
  ...rest,
@@ -166,133 +178,180 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
166
178
  preNavigationHooks: preNavigationHooks,
167
179
  postNavigationHooks: postNavigationHooks,
168
180
  extendContext,
181
+ navigationTimeoutSecs,
182
+ launchContext,
183
+ headless,
184
+ browserPool,
185
+ remoteBrowser,
169
186
  });
170
- this.#teardownHooks.push(browserCrawler.teardown.bind(browserCrawler));
171
- this.#staticContextPipeline = staticCrawler.contextPipeline.compose({
172
- action: this.adaptCheerioContext.bind(this),
173
- });
174
- this.#browserContextPipeline = browserCrawler.contextPipeline.compose({
175
- action: this.adaptPlaywrightContext.bind(this),
176
- });
187
+ this.#staticCrawler = staticCrawler;
188
+ this.#browserCrawler = browserCrawler;
189
+ // Each attempt needs its own deferred cleanups, and they must share the attempt's cleanup stack: resources the
190
+ // pipeline defers releasing (the page) have to outlive the user's cleanups, which may still use them.
191
+ const deferredCleanup = ContextPipeline.create().compose((_context, onCleanup) => ({
192
+ registerDeferredCleanup: (cleanup) => {
193
+ onCleanup(async () => {
194
+ try {
195
+ await cleanup();
196
+ }
197
+ catch (error) {
198
+ this.log.debug('Error in deferred cleanup', { error });
199
+ }
200
+ });
201
+ },
202
+ }));
203
+ this.#staticContextPipeline = deferredCleanup
204
+ .chain(staticCrawler.contextPipeline)
205
+ .compose(this.#adaptCheerioContext.bind(this));
206
+ this.#browserContextPipeline = deferredCleanup
207
+ .chain(browserCrawler.contextPipeline)
208
+ .compose(this.#adaptPlaywrightContext.bind(this));
177
209
  }
178
210
  async init() {
211
+ // A crawler can be run again after a teardown.
212
+ this.#shutDown = false;
179
213
  // Only the predictor we built ourselves is ours to initialize - an injected one is borrowed, so its
180
214
  // lifecycle (including restoring persisted state) stays with whoever created it.
181
215
  await this.#renderingTypePredictor.ifOwned((predictor) => predictor.initialize());
182
216
  return await super.init();
183
217
  }
184
- buildContextPipeline() {
218
+ #buildContextPipeline() {
185
219
  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`;
186
- return super.buildContextPipeline().compose({
187
- action: async ({ request }) => ({
188
- get request() {
189
- return request;
190
- },
191
- get response() {
192
- throw new Error(errorMessage('response'));
193
- },
194
- get page() {
195
- throw new Error(errorMessage('page'));
196
- },
197
- get querySelector() {
198
- throw new Error(errorMessage('querySelector'));
199
- },
200
- get querySelectorAll() {
201
- throw new Error(errorMessage('querySelectorAll'));
202
- },
203
- get waitForSelector() {
204
- throw new Error(errorMessage('waitForSelector'));
205
- },
206
- get parseWithCheerio() {
207
- throw new Error(errorMessage('parseWithCheerio'));
208
- },
209
- get enqueueLinks() {
210
- throw new Error(errorMessage('enqueueLinks'));
211
- },
212
- }),
213
- });
220
+ return ContextPipeline.create().compose(async ({ request }) => ({
221
+ get request() {
222
+ return request;
223
+ },
224
+ get response() {
225
+ throw new Error(errorMessage('response'));
226
+ },
227
+ get page() {
228
+ throw new Error(errorMessage('page'));
229
+ },
230
+ get querySelectorAll() {
231
+ throw new Error(errorMessage('querySelectorAll'));
232
+ },
233
+ get querySelectorOne() {
234
+ throw new Error(errorMessage('querySelectorOne'));
235
+ },
236
+ get waitForSelector() {
237
+ throw new Error(errorMessage('waitForSelector'));
238
+ },
239
+ get parseWithCheerio() {
240
+ throw new Error(errorMessage('parseWithCheerio'));
241
+ },
242
+ get enqueueLinks() {
243
+ throw new Error(errorMessage('enqueueLinks'));
244
+ },
245
+ }));
214
246
  }
215
- async adaptCheerioContext(cheerioContext) {
247
+ async #adaptCheerioContext(cheerioContext) {
216
248
  return {
217
249
  get page() {
218
250
  throw new Error('Page object was used in HTTP-only request handler');
219
251
  },
220
- async querySelector(selector) {
221
- return cheerioContext.$(selector).first();
222
- },
223
- async querySelectorAll(selector) {
224
- return cheerioContext.$(selector);
225
- },
226
252
  enqueueLinks: async (options = {}) => {
227
253
  const urls = extractUrlsFromCheerio(cheerioContext.$, options.selector, options.baseUrl ?? cheerioContext.request.loadedUrl);
228
- return (await this.enqueueLinks(urls, options, cheerioContext.request));
254
+ return (await this.#enqueueLinks(urls, options, cheerioContext.request));
229
255
  },
230
- response: cheerioContext.response,
256
+ // The HTTP crawler has already consumed the body; hand out a fresh copy, like the browser side does.
257
+ // HTML bodies are already decoded to UTF-8, so `arrayBuffer()` may disagree with the original headers.
258
+ response: new ResponseWithUrl(cheerioContext.body, cheerioContext.response),
231
259
  };
232
260
  }
233
- async adaptPlaywrightContext(playwrightContext) {
261
+ async #adaptPlaywrightContext(playwrightContext) {
234
262
  // Capture the original response to avoid infinite recursion when the getter is copied to the context
235
263
  const originalResponse = playwrightContext.response;
264
+ // `headers()` can return repeated headers (e.g. `set-cookie`) joined with `\n`, which `Headers` rejects
265
+ const headers = new Headers();
266
+ for (const { name, value } of await originalResponse.headersArray()) {
267
+ headers.append(name, value);
268
+ }
236
269
  return {
237
- response: new Response(Uint8Array.from(await originalResponse.body()), {
238
- headers: originalResponse.headers(),
270
+ response: new ResponseWithUrl(Uint8Array.from(await originalResponse.body()), {
271
+ headers,
239
272
  status: originalResponse.status(),
240
273
  statusText: originalResponse.statusText(),
274
+ url: originalResponse.url(),
241
275
  }),
242
- async querySelector(selector, timeoutMs = 5000) {
243
- const locator = playwrightContext.page.locator(selector).first();
244
- await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
245
- const $ = await playwrightContext.parseWithCheerio();
246
- return $(selector).first();
247
- },
248
- async querySelectorAll(selector, timeoutMs = 5000) {
249
- const locator = playwrightContext.page.locator(selector).first();
250
- await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
251
- const $ = await playwrightContext.parseWithCheerio();
252
- return $(selector);
253
- },
254
276
  enqueueLinks: async (options = {}, timeoutMs = 5000) => {
255
277
  // TODO consider using `context.parseWithCheerio` to make this universal and avoid code duplication
256
278
  const selector = options.selector ?? 'a';
257
279
  const locator = playwrightContext.page.locator(selector).first();
258
- await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
280
+ // Wait for client-rendered links, but like the HTTP side, enqueue nothing when there are none.
281
+ await locator.waitFor({ timeout: timeoutMs, state: 'attached' }).catch((error) => {
282
+ if (error.name !== 'TimeoutError')
283
+ throw error;
284
+ });
259
285
  const urls = await extractUrlsFromPage(playwrightContext.page, selector, options.baseUrl ?? playwrightContext.request.loadedUrl);
260
- return (await this.enqueueLinks(urls, options, playwrightContext.request));
286
+ return (await this.#enqueueLinks(urls, options, playwrightContext.request));
261
287
  },
262
288
  };
263
289
  }
264
290
  /**
265
291
  * Runs one request handler attempt inside its own {@link StorageTransaction}, wrapping the inner
266
292
  * (static or browser) context pipeline. The transaction is pushed to `transactions` *at creation
267
- * time, before the `try`* - the `ok: false` branch of the returned {@link Result} carries no
268
- * result, and failed attempts are routine here. The caller owns the outcome and disposal.
293
+ * time, before the `try`*, as failed attempts are routine here. The caller owns the outcome and
294
+ * disposal, including closing or reverting the {@link ContextModifications}.
295
+ *
296
+ * `request` defaults to the context's; a detection rerun passes a copy so it sees the request as it
297
+ * was before the browser attempt.
269
298
  */
270
- async crawlOne(renderingType, context, useStateFunction, transactions) {
299
+ async #crawlOne(renderingType, context, useStateFunction, transactions, request = context.request) {
271
300
  const transaction = createStorageTransaction({
272
301
  policy: this.#attemptWritePolicy,
273
302
  commitTimeoutMillis: this.internalTimeoutMillis,
274
303
  });
275
304
  transactions.push(transaction);
276
305
  const logs = [];
277
- const deferredCleanup = [];
278
- const attemptBoundContextHelpers = {
279
- useState: useStateFunction,
280
- log: this.createLogProxy(context.log, logs),
281
- registerDeferredCleanup: (cleanup) => deferredCleanup.push(cleanup),
306
+ const contextModifications = {
307
+ request: new MutationJournal(),
308
+ state: new MutationJournal(),
282
309
  };
283
310
  const subCrawlerContext = Object.defineProperties({}, Object.getOwnPropertyDescriptors(context));
311
+ const attemptBoundContextHelpers = {
312
+ request: contextModifications.request.track(request),
313
+ useState: async (defaultValue) => contextModifications.state.track(await useStateFunction(defaultValue)),
314
+ log: this.#createLogProxy(context.log, logs),
315
+ // The sub-crawler pipeline keeps this attempt's navigation deadline on `subCrawlerContext`, but the
316
+ // outer `extendTimeout` only pushes the deadline it finds on `context`, so push this one as well.
317
+ extendTimeout: (secs) => {
318
+ context.extendTimeout(secs);
319
+ if (subCrawlerContext[navigationDeadlineKey] !== undefined) {
320
+ subCrawlerContext[navigationDeadlineKey] += secs * 1000;
321
+ }
322
+ },
323
+ };
284
324
  // Mark attempt-bound helpers as non-configurable so they survive the sub-crawler context pipeline
285
325
  // (which would otherwise override them with the sub-crawler's own versions, losing the binding).
286
326
  for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(attemptBoundContextHelpers))) {
287
327
  Object.defineProperty(subCrawlerContext, key, { ...descriptor, configurable: false });
288
328
  }
329
+ // The timeout below does not stop the request handler, and the pipeline closes the page only after the handler
330
+ // settles. Racing the handler against this lets a timed-out attempt release its page right away.
331
+ const attemptFailed = new AbortController();
289
332
  try {
333
+ // Any failure - middleware or handler - ends up in the `ok: false` branch below.
334
+ const rethrow = (error) => {
335
+ throw error;
336
+ };
337
+ const abandonableRequestHandler = async (crawlingContext) => {
338
+ // The attempt may have failed before the handler starts, and a late abort listener would never fire.
339
+ attemptFailed.signal.throwIfAborted();
340
+ return Promise.race([
341
+ this.requestHandler(crawlingContext),
342
+ new Promise((_resolve, reject) => {
343
+ attemptFailed.signal.addEventListener('abort', () => reject(attemptFailed.signal.reason), {
344
+ once: true,
345
+ });
346
+ }),
347
+ ]);
348
+ };
290
349
  const callAdaptiveRequestHandler = async () => {
291
350
  if (renderingType === 'static') {
292
- await this.#staticContextPipeline.call(subCrawlerContext, this.requestHandler.bind(this));
351
+ await this.#staticContextPipeline.call(subCrawlerContext, this.requestHandler.bind(this), rethrow);
293
352
  }
294
353
  else if (renderingType === 'clientOnly') {
295
- await this.#browserContextPipeline.call(subCrawlerContext, this.requestHandler.bind(this));
354
+ await this.#browserContextPipeline.call(subCrawlerContext, abandonableRequestHandler, rethrow);
296
355
  }
297
356
  };
298
357
  // this crawler overrides `runRequestHandler` and times each rendering-type run itself, so it has
@@ -300,18 +359,16 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
300
359
  const routeTimeoutSecs = this.requestHandler.getTimeoutSecs?.(context.request.label);
301
360
  const timeoutMillis = routeTimeoutSecs === undefined ? this.#individualRequestHandlerTimeoutMillis : routeTimeoutSecs * 1000;
302
361
  await addTimeoutToPromise(async () => transaction.run(callAdaptiveRequestHandler), timeoutMillis, 'Request handler timed out');
303
- return { result: transaction, ok: true, logs };
362
+ return { ok: true, transaction, contextModifications, logs };
304
363
  }
305
364
  catch (error) {
306
- return { error, ok: false, logs };
307
- }
308
- finally {
309
- await Promise.all(deferredCleanup.map((cleanup) => cleanup()));
365
+ attemptFailed.abort(error);
366
+ return { ok: false, error, transaction, contextModifications, logs };
310
367
  }
311
368
  }
312
369
  async runRequestHandler(crawlingContext) {
313
- const renderingTypePrediction = this.#renderingTypePredictor.value.predict(crawlingContext.request);
314
- const shouldDetectRenderingType = Math.random() < renderingTypePrediction.detectionProbabilityRecommendation;
370
+ const renderingTypePrediction = await this.#renderingTypePredictor.value.predict(crawlingContext.request);
371
+ const shouldDetectRenderingType = !this.#shutDown && Math.random() < renderingTypePrediction.detectionProbabilityRecommendation;
315
372
  if (!shouldDetectRenderingType) {
316
373
  crawlingContext.log.debug(`Predicted rendering type ${renderingTypePrediction.renderingType} for ${crawlingContext.request.url}`);
317
374
  }
@@ -320,22 +377,30 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
320
377
  // `finally` below, not earlier: the comparators read the journals after `crawlOne` returns.
321
378
  const transactions = [];
322
379
  try {
380
+ // A result the `resultChecker` rejected is as good as a detection saying the page needs a browser - but
381
+ // only once the browser run has succeeded. A thrown error says nothing about rendering.
382
+ let httpResultRejected = false;
323
383
  if (renderingTypePrediction.renderingType === 'static' && !shouldDetectRenderingType) {
324
384
  crawlingContext.log.debug(`Running HTTP-only request handler for ${crawlingContext.request.url}`);
325
385
  this.statistics.state.httpOnlyRequestHandlerRuns++;
326
- const plainHTTPRun = await this.crawlOne('static', crawlingContext, crawlingContext.useState, transactions);
327
- if (plainHTTPRun.ok && this.#resultChecker(plainHTTPRun.result)) {
386
+ const plainHTTPRun = await this.#crawlOne('static', crawlingContext, crawlingContext.useState, transactions);
387
+ if (plainHTTPRun.ok &&
388
+ this.#resultChecker(plainHTTPRun.transaction, { request: crawlingContext.request })) {
328
389
  crawlingContext.log.debug(`HTTP-only request handler succeeded for ${crawlingContext.request.url}`);
329
- plainHTTPRun.logs?.forEach(([log, method, ...args]) => log[method](...args));
330
- await plainHTTPRun.result.commit();
390
+ plainHTTPRun.logs.forEach(([log, method, ...args]) => log[method](...args));
391
+ this.#keepContextModifications(plainHTTPRun.contextModifications);
392
+ await plainHTTPRun.transaction.commit();
331
393
  return;
332
394
  }
333
395
  // Execution will "fall through" and try running the request handler in a browser
334
396
  if (!plainHTTPRun.ok) {
335
- const actualError = plainHTTPRun.error instanceof RequestHandlerError
397
+ const actualError = plainHTTPRun.error instanceof RequestHandlerError ||
398
+ plainHTTPRun.error instanceof ContextPipelineInitializationError
336
399
  ? plainHTTPRun.error.cause
337
400
  : plainHTTPRun.error;
338
- if (await this.#shouldPropagateError(actualError, crawlingContext)) {
401
+ if (actualError instanceof ContextPipelineInterruptedError ||
402
+ (await this.#shouldPropagateError(actualError, crawlingContext))) {
403
+ this.#keepContextModifications(plainHTTPRun.contextModifications);
339
404
  throw actualError;
340
405
  }
341
406
  crawlingContext.log.exception(actualError, `HTTP-only request handler failed for ${crawlingContext.request.url}`);
@@ -343,58 +408,64 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
343
408
  else {
344
409
  crawlingContext.log.warning(`HTTP-only request handler returned a suspicious result for ${crawlingContext.request.url}`);
345
410
  this.statistics.state.renderingTypeMispredictions++;
411
+ httpResultRejected = true;
346
412
  }
413
+ // The browser attempt starts from the request and state as they were before the rejected one.
414
+ this.#discardContextModifications(plainHTTPRun.contextModifications, crawlingContext);
347
415
  }
348
416
  crawlingContext.log.debug(`Running browser request handler for ${crawlingContext.request.url}`);
349
417
  this.statistics.state.browserRequestHandlerRuns++;
350
- // Run the request handler in a browser. The copy of the crawler state is kept so that we can perform
351
- // a rendering type detection if necessary. Without this measure, the HTTP request handler would run
352
- // under different conditions, which could change its behavior. Changes done to the crawler state by
353
- // the HTTP request handler will not be committed to the actual storage.
354
- const stateTracker = {
355
- stateCopy: null,
356
- async getLiveState(defaultValue = {}) {
357
- const state = await crawlingContext.useState(defaultValue);
358
- if (this.stateCopy === null) {
359
- this.stateCopy = JSON.parse(JSON.stringify(state));
360
- }
361
- return state;
362
- },
363
- async getStateCopy(defaultValue = {}) {
364
- if (this.stateCopy === null) {
365
- return defaultValue;
366
- }
367
- return this.stateCopy;
368
- },
369
- };
370
- const browserRun = await this.crawlOne('clientOnly', crawlingContext, stateTracker.getLiveState.bind(stateTracker), transactions);
418
+ const browserRun = await this.#crawlOne('clientOnly', crawlingContext, crawlingContext.useState, transactions);
371
419
  if (!browserRun.ok) {
420
+ // A failed browser attempt is handed to the retry logic with its writes - `userData` stashed for the
421
+ // next attempt must survive.
422
+ this.#keepContextModifications(browserRun.contextModifications);
372
423
  throw browserRun.error;
373
424
  }
374
- browserRun.logs?.forEach(([log, method, ...args]) => log[method](...args));
375
- await browserRun.result.commit();
425
+ try {
426
+ browserRun.logs.forEach(([log, method, ...args]) => log[method](...args));
427
+ // The `afterStorageCommit` callbacks belong to this attempt, so the detection rerun undoes their
428
+ // writes too - the journals stay open until they have run.
429
+ await browserRun.transaction.commit();
430
+ }
431
+ finally {
432
+ this.#keepContextModifications(browserRun.contextModifications);
433
+ }
434
+ // Past the shutdown fence, `teardown()` has already drained - and possibly torn down the predictor.
435
+ if (httpResultRejected && !this.#shutDown) {
436
+ this.#storeRenderingType(crawlingContext.request, 'clientOnly');
437
+ }
376
438
  if (shouldDetectRenderingType) {
377
- crawlingContext.log.debug(`Detecting rendering type for ${crawlingContext.request.url}`);
378
- // The detection attempt's transaction is never committed - its writes exist only for the
379
- // result comparison.
380
- const plainHTTPRun = await this.crawlOne('static', crawlingContext, stateTracker.getStateCopy.bind(stateTracker), transactions);
381
- const detectionResult = (() => {
382
- if (!plainHTTPRun.ok) {
383
- return 'clientOnly';
384
- }
385
- const comparisonResult = this.#resultComparator(plainHTTPRun.result, browserRun.result);
386
- if (comparisonResult === true || comparisonResult === 'equal') {
387
- return 'static';
388
- }
389
- if (comparisonResult === false || comparisonResult === 'different') {
390
- return 'clientOnly';
439
+ const detectionPromise = (async () => {
440
+ crawlingContext.log.debug(`Detecting rendering type for ${crawlingContext.request.url}`);
441
+ // The detection attempt's transaction is never committed - its writes exist only for the
442
+ // result comparison. It runs on copies of the request and the crawler state with the browser
443
+ // attempt's writes undone, so both attempts start from the same conditions, and the copies go
444
+ // away with it.
445
+ const { request: requestJournal, state: stateJournal } = browserRun.contextModifications;
446
+ let stateCopy;
447
+ 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)))));
448
+ const detectionResult = (() => {
449
+ if (!plainHTTPRun.ok) {
450
+ return 'clientOnly';
451
+ }
452
+ const comparisonResult = this.#resultComparator(plainHTTPRun.transaction, browserRun.transaction, {
453
+ request: crawlingContext.request,
454
+ });
455
+ if (comparisonResult === true || comparisonResult === 'equal') {
456
+ return 'static';
457
+ }
458
+ if (comparisonResult === false || comparisonResult === 'different') {
459
+ return 'clientOnly';
460
+ }
461
+ return undefined;
462
+ })();
463
+ crawlingContext.log.debug(`Detected rendering type ${detectionResult} for ${crawlingContext.request.url}`);
464
+ if (detectionResult !== undefined) {
465
+ this.#storeRenderingType(crawlingContext.request, detectionResult);
391
466
  }
392
- return undefined;
393
467
  })();
394
- crawlingContext.log.debug(`Detected rendering type ${detectionResult} for ${crawlingContext.request.url}`);
395
- if (detectionResult !== undefined) {
396
- this.#renderingTypePredictor.value.storeResult(crawlingContext.request, detectionResult);
397
- }
468
+ await this.#trackDetection(detectionPromise);
398
469
  }
399
470
  }
400
471
  finally {
@@ -405,7 +476,32 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
405
476
  }
406
477
  }
407
478
  }
408
- async enqueueLinks(urls, options, request) {
479
+ #keepContextModifications(modifications) {
480
+ modifications.request.close();
481
+ modifications.state.close();
482
+ }
483
+ #discardContextModifications(modifications, { request, log }) {
484
+ // Nothing else writes to a request while its handler runs, so a conflict means a write that bypassed
485
+ // the context (e.g. through a stashed reference) - it stays, but it is not what the retry logic expects.
486
+ modifications.request.revert({
487
+ onConflict: (key) => log.warning(`Request ${request.url}: '${String(key)}' was modified outside the request handler`),
488
+ });
489
+ // The state is shared with concurrent handlers; a conflict is one of them having written the same
490
+ // property meanwhile. Their value wins, and this attempt's write stays with it.
491
+ modifications.state.revert({
492
+ onConflict: (key) => log.debug(`Crawler state '${String(key)}' was changed concurrently; keeping the newer value`),
493
+ });
494
+ }
495
+ #storeRenderingType(request, renderingType) {
496
+ // Deliberately not awaited: a predictor that persists asynchronously gets to keep batching its writes,
497
+ // and `drainRenderingDetections()` catches whatever is still pending.
498
+ const stored = this.#renderingTypePredictor.value.storeResult(request, renderingType);
499
+ if (stored !== undefined) {
500
+ // Nothing downstream awaits this, so a failed write would otherwise be silent.
501
+ void this.#trackDetection(Promise.resolve(stored).catch((error) => this.log.exception(error, `Failed to store the rendering type detection result for ${request.url}`)));
502
+ }
503
+ }
504
+ async #enqueueLinks(urls, options, request) {
409
505
  const baseUrl = resolveBaseUrlForEnqueueLinksFiltering({
410
506
  enqueueStrategy: options?.strategy,
411
507
  finalRequestUrl: request.loadedUrl,
@@ -421,23 +517,94 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
421
517
  strategy: options.strategy ?? EnqueueStrategy.SameHostname,
422
518
  });
423
519
  }
424
- createLogProxy(log, logs) {
520
+ #createLogProxy(log, logs) {
425
521
  return new Proxy(log, {
426
- get(target, propertyName, receiver) {
522
+ get(target, propertyName) {
427
523
  if (proxyLogMethods.includes(propertyName)) {
428
524
  return (...args) => {
429
525
  logs.push([target, propertyName, ...args]);
430
526
  };
431
527
  }
432
- return Reflect.get(target, propertyName, receiver);
528
+ const value = Reflect.get(target, propertyName, target);
529
+ // Bind non-intercepted methods to the target instance so private #-fields
530
+ // (e.g. BaseCrawleeLogger.#options, #warningsLogged) do not throw TypeError at runtime.
531
+ if (typeof value === 'function') {
532
+ return value.bind(target);
533
+ }
534
+ return value;
433
535
  },
434
536
  });
435
537
  }
538
+ #trackDetection(promise) {
539
+ this.#activeDetections.add(promise);
540
+ // Not `finally()`: the promise it derives would reject on its own and go unhandled. A rejection here
541
+ // belongs to whoever awaits the original, or to `allSettled` in the drain.
542
+ void promise.catch(() => { }).then(() => this.#activeDetections.delete(promise));
543
+ return promise;
544
+ }
545
+ /**
546
+ * Number of rendering type detections that have not settled yet, including results the predictor is
547
+ * still persisting.
548
+ */
549
+ get inFlightRenderingTypeDetectionCount() {
550
+ return this.#activeDetections.size;
551
+ }
552
+ /**
553
+ * Waits for in-flight rendering type detections to settle, bounded by `timeoutMillis` (defaults to the
554
+ * internal timeout).
555
+ */
556
+ async drainRenderingDetections({ timeoutMillis } = {}) {
557
+ if (this.#activeDetections.size === 0) {
558
+ return;
559
+ }
560
+ const drained = (async () => {
561
+ while (this.#activeDetections.size > 0) {
562
+ await Promise.allSettled(Array.from(this.#activeDetections));
563
+ }
564
+ })();
565
+ const millis = timeoutMillis ?? this.internalTimeoutMillis;
566
+ // A caller opting out of the bound would otherwise get an immediate spurious timeout - `setTimeout`
567
+ // clamps a non-finite delay to 1ms.
568
+ if (!Number.isFinite(millis)) {
569
+ await drained;
570
+ return;
571
+ }
572
+ const abortTimer = new AbortController();
573
+ try {
574
+ const outcome = await Promise.race([
575
+ drained.then(() => 'drained'),
576
+ delay(millis, 'timedOut', { signal: abortTimer.signal }).catch(() => 'aborted'),
577
+ ]);
578
+ if (outcome === 'timedOut') {
579
+ 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.`);
580
+ }
581
+ }
582
+ finally {
583
+ abortTimer.abort();
584
+ }
585
+ }
586
+ /**
587
+ * Stops the crawler immediately, but not before rendering type detections already under way (and results
588
+ * the predictor is still persisting) have settled - see
589
+ * {@link AdaptivePlaywrightCrawler.drainRenderingDetections|`drainRenderingDetections()`}. Requests
590
+ * that are still running are not waited for, unlike {@link BasicCrawler.stop|`stop()`}.
591
+ */
436
592
  async teardown() {
593
+ // Called from outside `run()` - under `keepAlive`, say - the pool keeps dispatching until
594
+ // `super.teardown()` aborts it, and a request starting during the drain would open a detection the
595
+ // drain has already passed. Closing that first makes the drain a fence.
596
+ this.#shutDown = true;
597
+ await this.drainRenderingDetections();
437
598
  await super.teardown();
438
- for (const hook of this.#teardownHooks) {
439
- await hook();
440
- }
599
+ // Mirrors the owned-only `initialize()` in `init()` - without this, the predictor we built keeps its
600
+ // PERSIST_STATE listener registered after the crawl and never gets a final write.
601
+ await this.#renderingTypePredictor.ifOwned((predictor) => predictor.teardown());
602
+ await this.#browserCrawler.teardown();
603
+ }
604
+ async destroy() {
605
+ await super.destroy();
606
+ await this.#staticCrawler.destroy();
607
+ await this.#browserCrawler.destroy();
441
608
  }
442
609
  }
443
610
  export function createAdaptivePlaywrightRouter(routesOrSchemas) {