@crawlee/playwright 4.0.0-rc.1 → 4.0.0-rc.3

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,14 +1,95 @@
1
1
  import { setTimeout as delay } from 'node:timers/promises';
2
2
  import { isDeepStrictEqual } from 'node:util';
3
- import { BasicCrawler, ContextPipeline, ContextPipelineInitializationError, ContextPipelineInterruptedError, RequestHandlerError, resolveBaseUrlForEnqueueLinksFiltering, Router, Statistics, } from '@crawlee/basic';
4
- 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';
5
5
  import { CheerioCrawler } from '@crawlee/cheerio';
6
+ import { ResponseWithUrl } from '@crawlee/http-client';
6
7
  import { createStorageTransaction, EnqueueStrategy, OwnedOrInjected } from '@crawlee/core';
7
- import { extractUrlsFromCheerio, parseArgument } from '@crawlee/utils/internal';
8
+ import { extractUrlsFromCheerio, MutationJournal, parseArgument } from '@crawlee/utils/internal';
8
9
  import { z } from 'zod';
9
10
  import { addTimeoutToPromise } from '@apify/timeout';
10
11
  import { PlaywrightCrawler } from './playwright-crawler.js';
11
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(() => { });
29
+ }
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]);
40
+ }
41
+ fail(reason) {
42
+ this.#failed = true;
43
+ this.#failure.reject(reason);
44
+ }
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
+ };
54
+ }
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
+ }
65
+ }
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
+ }
91
+ }
92
+ }
12
93
  const adaptiveStatisticStateSchema = z.object({
13
94
  /** How many requests were handled by the HTTP-only request handler. */
14
95
  httpOnlyRequestHandlerRuns: z.number().default(0),
@@ -43,9 +124,9 @@ const proxyLogMethods = [
43
124
  * ```javascript
44
125
  * const crawler = new AdaptivePlaywrightCrawler({
45
126
  * renderingTypeDetectionRatio: 0.1,
46
- * async requestHandler({ querySelector, pushData, enqueueLinks, request, log }) {
127
+ * async requestHandler({ querySelectorAll, pushData, enqueueLinks, request, log }) {
47
128
  * // This function is called to extract data from a single web page
48
- * const $prices = await querySelector('span.price')
129
+ * const $prices = await querySelectorAll('span.price')
49
130
  *
50
131
  * await pushData({
51
132
  * url: request.url,
@@ -61,8 +142,6 @@ const proxyLogMethods = [
61
142
  * 'http://www.example.com/page-2',
62
143
  * ]);
63
144
  * ```
64
- *
65
- * @experimental
66
145
  */
67
146
  export class AdaptivePlaywrightCrawler extends BasicCrawler {
68
147
  #renderingTypePredictor;
@@ -90,7 +169,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
90
169
  */
91
170
  #shutDown = false;
92
171
  constructor(options = {}) {
93
- const { requestHandler, renderingTypeDetectionRatio = 0.1, renderingTypePredictor, resultChecker, shouldPropagateError, resultComparator, statistics, requestHandlerTimeoutSecs = 60, errorHandler, failedRequestHandler, preNavigationHooks = [], postNavigationHooks = [], extendContext, transactionalStorage, launchContext, headless, browserPool, remoteBrowser, ...rest } = options;
172
+ 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;
94
173
  // The user's value is replaced by `false` in the `super` call below — validate it separately,
95
174
  // wrapped in an object so the error still names the field.
96
175
  parseArgument({ transactionalStorage }, z.object({ transactionalStorage: BasicCrawler.optionsShape.transactionalStorage }), 'AdaptivePlaywrightCrawlerOptions');
@@ -135,7 +214,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
135
214
  this.#individualRequestHandlerTimeoutMillis = requestHandlerTimeoutSecs * 1000;
136
215
  // `renderingTypeDetectionRatio` only configures the default predictor - an injected one brings its own
137
216
  // detection ratio (and its own state), so the option is ignored in that case.
138
- this.#renderingTypePredictor = OwnedOrInjected.resolve(renderingTypePredictor, () => new RenderingTypePredictor({ detectionRatio: renderingTypeDetectionRatio }));
217
+ this.#renderingTypePredictor = OwnedOrInjected.resolve(renderingTypePredictor, () => new RenderingTypePredictor({ detectionRatio: renderingTypeDetectionRatio, id: options.id }));
139
218
  this.#attemptWritePolicy = {
140
219
  requestQueue: 'deferred',
141
220
  ...(typeof transactionalStorage === 'object' ? transactionalStorage : {}),
@@ -146,7 +225,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
146
225
  this.#resultComparator = resultComparator;
147
226
  }
148
227
  else if (resultChecker !== undefined) {
149
- this.#resultComparator = (resultA, resultB) => this.#resultChecker(resultA) && this.#resultChecker(resultB);
228
+ this.#resultComparator = (resultA, resultB, context) => this.#resultChecker(resultA, context) && this.#resultChecker(resultB, context);
150
229
  }
151
230
  else {
152
231
  this.#resultComparator = (resultA, resultB) => {
@@ -171,6 +250,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
171
250
  preNavigationHooks,
172
251
  postNavigationHooks,
173
252
  extendContext,
253
+ navigationTimeoutSecs,
174
254
  });
175
255
  const browserCrawler = new PlaywrightCrawler({
176
256
  ...rest,
@@ -178,6 +258,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
178
258
  preNavigationHooks: preNavigationHooks,
179
259
  postNavigationHooks: postNavigationHooks,
180
260
  extendContext,
261
+ navigationTimeoutSecs,
181
262
  launchContext,
182
263
  headless,
183
264
  browserPool,
@@ -185,8 +266,26 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
185
266
  });
186
267
  this.#staticCrawler = staticCrawler;
187
268
  this.#browserCrawler = browserCrawler;
188
- this.#staticContextPipeline = staticCrawler.contextPipeline.compose(this.#adaptCheerioContext.bind(this));
189
- this.#browserContextPipeline = browserCrawler.contextPipeline.compose(this.#adaptPlaywrightContext.bind(this));
269
+ // Each attempt needs its own deferred cleanups, and they must share the attempt's cleanup stack: resources the
270
+ // pipeline defers releasing (the page) have to outlive the user's cleanups, which may still use them.
271
+ const deferredCleanup = ContextPipeline.create().compose((_context, onCleanup) => ({
272
+ registerDeferredCleanup: (cleanup) => {
273
+ onCleanup(async () => {
274
+ try {
275
+ await cleanup();
276
+ }
277
+ catch (error) {
278
+ this.log.debug('Error in deferred cleanup', { error });
279
+ }
280
+ });
281
+ },
282
+ }));
283
+ this.#staticContextPipeline = deferredCleanup
284
+ .chain(staticCrawler.contextPipeline)
285
+ .compose(this.#adaptCheerioContext.bind(this));
286
+ this.#browserContextPipeline = deferredCleanup
287
+ .chain(browserCrawler.contextPipeline)
288
+ .compose(this.#adaptPlaywrightContext.bind(this));
190
289
  }
191
290
  async init() {
192
291
  // A crawler can be run again after a teardown.
@@ -208,108 +307,124 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
208
307
  get page() {
209
308
  throw new Error(errorMessage('page'));
210
309
  },
211
- get querySelector() {
212
- throw new Error(errorMessage('querySelector'));
213
- },
214
310
  get querySelectorAll() {
215
311
  throw new Error(errorMessage('querySelectorAll'));
216
312
  },
313
+ get querySelectorOne() {
314
+ throw new Error(errorMessage('querySelectorOne'));
315
+ },
217
316
  get waitForSelector() {
218
317
  throw new Error(errorMessage('waitForSelector'));
219
318
  },
220
319
  get parseWithCheerio() {
221
320
  throw new Error(errorMessage('parseWithCheerio'));
222
321
  },
322
+ get extractLinks() {
323
+ throw new Error(errorMessage('extractLinks'));
324
+ },
223
325
  get enqueueLinks() {
224
326
  throw new Error(errorMessage('enqueueLinks'));
225
327
  },
226
328
  }));
227
329
  }
228
330
  async #adaptCheerioContext(cheerioContext) {
331
+ const extractLinks = async (options = {}) => extractUrlsFromCheerio(cheerioContext.$, options.selector, options.baseUrl ?? cheerioContext.request.loadedUrl);
229
332
  return {
230
333
  get page() {
231
334
  throw new Error('Page object was used in HTTP-only request handler');
232
335
  },
233
- async querySelector(selector) {
234
- return cheerioContext.$(selector).first();
235
- },
236
- async querySelectorAll(selector) {
237
- return cheerioContext.$(selector);
238
- },
239
- enqueueLinks: async (options = {}) => {
240
- const urls = extractUrlsFromCheerio(cheerioContext.$, options.selector, options.baseUrl ?? cheerioContext.request.loadedUrl);
241
- return (await this.#enqueueLinks(urls, options, cheerioContext.request));
242
- },
243
- response: cheerioContext.response,
336
+ extractLinks,
337
+ enqueueLinks: async (options = {}) => this.#enqueueLinks(await extractLinks(options), options, cheerioContext.request),
338
+ // `skipNavigation` keeps the inner throwing getter. The body is already consumed (and decoded to UTF-8).
339
+ ...(cheerioContext.request.skipNavigation
340
+ ? {}
341
+ : { response: new ResponseWithUrl(cheerioContext.body, cheerioContext.response) }),
244
342
  };
245
343
  }
246
344
  async #adaptPlaywrightContext(playwrightContext) {
247
- // Capture the original response to avoid infinite recursion when the getter is copied to the context
248
- const originalResponse = playwrightContext.response;
249
- return {
250
- response: new Response(Uint8Array.from(await originalResponse.body()), {
251
- headers: originalResponse.headers(),
345
+ // Capture the original response to avoid infinite recursion when the getter is copied to the context.
346
+ // The inner getter throws with `skipNavigation` or when navigation produced no response; it then stays.
347
+ let originalResponse;
348
+ try {
349
+ originalResponse = playwrightContext.response;
350
+ }
351
+ catch { }
352
+ let response;
353
+ if (originalResponse) {
354
+ // `headers()` can return repeated headers (e.g. `set-cookie`) joined with `\n`, which `Headers` rejects
355
+ const headers = new Headers();
356
+ for (const { name, value } of await originalResponse.headersArray()) {
357
+ headers.append(name, value);
358
+ }
359
+ // `body()` throws for redirects, `304` cache hits included, and for responses the page navigated away from
360
+ const body = await originalResponse
361
+ .body()
362
+ .catch(async () => Buffer.from(await playwrightContext.page.content()));
363
+ response = new ResponseWithUrl(Uint8Array.from(body), {
364
+ headers,
252
365
  status: originalResponse.status(),
253
366
  statusText: originalResponse.statusText(),
254
- }),
255
- async querySelector(selector, timeoutMs = 5000) {
256
- const locator = playwrightContext.page.locator(selector).first();
257
- await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
258
- const $ = await playwrightContext.parseWithCheerio();
259
- return $(selector).first();
260
- },
261
- async querySelectorAll(selector, timeoutMs = 5000) {
262
- const locator = playwrightContext.page.locator(selector).first();
263
- await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
264
- const $ = await playwrightContext.parseWithCheerio();
265
- return $(selector);
266
- },
267
- enqueueLinks: async (options = {}, timeoutMs = 5000) => {
268
- // TODO consider using `context.parseWithCheerio` to make this universal and avoid code duplication
269
- const selector = options.selector ?? 'a';
270
- const locator = playwrightContext.page.locator(selector).first();
271
- await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
272
- const urls = await extractUrlsFromPage(playwrightContext.page, selector, options.baseUrl ?? playwrightContext.request.loadedUrl);
273
- return (await this.#enqueueLinks(urls, options, playwrightContext.request));
274
- },
367
+ url: originalResponse.url(),
368
+ });
369
+ }
370
+ const extractLinks = async (options = {}, timeoutMs = 5000) => {
371
+ // TODO consider using `context.parseWithCheerio` to make this universal and avoid code duplication
372
+ const selector = options.selector ?? 'a';
373
+ const locator = playwrightContext.page.locator(selector).first();
374
+ // Wait for client-rendered links, but like the HTTP side, return nothing when there are none.
375
+ await locator.waitFor({ timeout: timeoutMs, state: 'attached' }).catch((error) => {
376
+ if (error.name !== 'TimeoutError')
377
+ throw error;
378
+ });
379
+ return extractUrlsFromPage(playwrightContext.page, selector, options.baseUrl ?? playwrightContext.request.loadedUrl);
380
+ };
381
+ return {
382
+ ...(response && { response }),
383
+ extractLinks,
384
+ enqueueLinks: async (options = {}, timeoutMs = 5000) => this.#enqueueLinks(await extractLinks(options, timeoutMs), options, playwrightContext.request),
275
385
  };
276
386
  }
277
387
  /**
278
- * Runs one request handler attempt inside its own {@link StorageTransaction}, wrapping the inner
279
- * (static or browser) context pipeline. The transaction is pushed to `transactions` *at creation
280
- * time, before the `try`* - the `ok: false` branch of the returned {@link Result} carries no
281
- * result, and failed attempts are routine here. The caller owns the outcome and disposal.
388
+ * Runs one request handler attempt inside the attempt's {@link StorageTransaction}, wrapping the inner
389
+ * (static or browser) context pipeline. The caller owns the outcome and settles the attempt, including
390
+ * closing or reverting the {@link ContextModifications}.
391
+ *
392
+ * `request` defaults to the context's; a detection rerun passes a copy so it sees the request as it
393
+ * was before the browser attempt.
282
394
  */
283
- async #crawlOne(renderingType, context, useStateFunction, transactions) {
284
- const transaction = createStorageTransaction({
285
- policy: this.#attemptWritePolicy,
286
- commitTimeoutMillis: this.internalTimeoutMillis,
287
- });
288
- transactions.push(transaction);
395
+ async #crawlOne(renderingType, context, useStateFunction, attempt, request = context.request) {
396
+ const { transaction } = attempt;
289
397
  const logs = [];
290
- const deferredCleanup = [];
398
+ const contextModifications = {
399
+ request: new MutationJournal(),
400
+ state: new MutationJournal(),
401
+ };
402
+ const subCrawlerContext = Object.defineProperties({}, Object.getOwnPropertyDescriptors(context));
291
403
  const attemptBoundContextHelpers = {
292
- useState: useStateFunction,
404
+ request: contextModifications.request.track(request),
405
+ useState: async (defaultValue) => contextModifications.state.track(await useStateFunction(defaultValue)),
293
406
  log: this.#createLogProxy(context.log, logs),
294
- registerDeferredCleanup: (cleanup) => deferredCleanup.push(cleanup),
407
+ // The sub-crawler pipeline keeps this attempt's navigation deadline on `subCrawlerContext`, but the
408
+ // outer `extendTimeout` only pushes the deadline it finds on `context`, so push this one as well.
409
+ extendTimeout: (secs) => {
410
+ context.extendTimeout(secs);
411
+ if (subCrawlerContext[navigationDeadlineKey] !== undefined) {
412
+ subCrawlerContext[navigationDeadlineKey] += secs * 1000;
413
+ }
414
+ },
295
415
  };
296
- const subCrawlerContext = Object.defineProperties({}, Object.getOwnPropertyDescriptors(context));
297
416
  // Mark attempt-bound helpers as non-configurable so they survive the sub-crawler context pipeline
298
417
  // (which would otherwise override them with the sub-crawler's own versions, losing the binding).
299
418
  for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(attemptBoundContextHelpers))) {
300
419
  Object.defineProperty(subCrawlerContext, key, { ...descriptor, configurable: false });
301
420
  }
302
421
  try {
303
- // Any failure - middleware or handler - ends up in the `ok: false` branch below.
304
- const rethrow = (error) => {
305
- throw error;
306
- };
307
422
  const callAdaptiveRequestHandler = async () => {
308
423
  if (renderingType === 'static') {
309
- await this.#staticContextPipeline.call(subCrawlerContext, this.requestHandler.bind(this), rethrow);
424
+ await attempt.run(this.#staticContextPipeline, subCrawlerContext, this.requestHandler.bind(this));
310
425
  }
311
426
  else if (renderingType === 'clientOnly') {
312
- await this.#browserContextPipeline.call(subCrawlerContext, this.requestHandler.bind(this), rethrow);
427
+ await attempt.run(this.#browserContextPipeline, subCrawlerContext, attempt.abandonable(this.requestHandler.bind(this)));
313
428
  }
314
429
  };
315
430
  // this crawler overrides `runRequestHandler` and times each rendering-type run itself, so it has
@@ -317,13 +432,11 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
317
432
  const routeTimeoutSecs = this.requestHandler.getTimeoutSecs?.(context.request.label);
318
433
  const timeoutMillis = routeTimeoutSecs === undefined ? this.#individualRequestHandlerTimeoutMillis : routeTimeoutSecs * 1000;
319
434
  await addTimeoutToPromise(async () => transaction.run(callAdaptiveRequestHandler), timeoutMillis, 'Request handler timed out');
320
- return { result: transaction, ok: true, logs };
435
+ return { ok: true, transaction, contextModifications, logs };
321
436
  }
322
437
  catch (error) {
323
- return { error, ok: false, logs };
324
- }
325
- finally {
326
- await Promise.all(deferredCleanup.map((cleanup) => cleanup()));
438
+ attempt.fail(error);
439
+ return { ok: false, error, transaction, contextModifications, logs };
327
440
  }
328
441
  }
329
442
  async runRequestHandler(crawlingContext) {
@@ -332,19 +445,31 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
332
445
  if (!shouldDetectRenderingType) {
333
446
  crawlingContext.log.debug(`Predicted rendering type ${renderingTypePrediction.renderingType} for ${crawlingContext.request.url}`);
334
447
  }
335
- // Every transaction created for this request - up to two, since the static-then-browser
336
- // fall-through and the browser-then-detection pair are mutually exclusive. Disposed in the
337
- // `finally` below, not earlier: the comparators read the journals after `crawlOne` returns.
338
- const transactions = [];
448
+ // Settled only in the `finally` below - the comparators read the journals after `crawlOne` returns.
449
+ const attempts = [];
450
+ const startAttempt = () => {
451
+ const attempt = new Attempt(createStorageTransaction({
452
+ policy: this.#attemptWritePolicy,
453
+ commitTimeoutMillis: this.internalTimeoutMillis,
454
+ }));
455
+ attempts.push(attempt);
456
+ return attempt;
457
+ };
339
458
  try {
459
+ // A result the `resultChecker` rejected is as good as a detection saying the page needs a browser - but
460
+ // only once the browser run has succeeded. A thrown error says nothing about rendering.
461
+ let resultCheckerRejectedHttpResult = false;
340
462
  if (renderingTypePrediction.renderingType === 'static' && !shouldDetectRenderingType) {
341
463
  crawlingContext.log.debug(`Running HTTP-only request handler for ${crawlingContext.request.url}`);
342
464
  this.statistics.state.httpOnlyRequestHandlerRuns++;
343
- const plainHTTPRun = await this.#crawlOne('static', crawlingContext, crawlingContext.useState, transactions);
344
- if (plainHTTPRun.ok && this.#resultChecker(plainHTTPRun.result)) {
465
+ const httpAttempt = startAttempt();
466
+ const plainHTTPRun = await this.#crawlOne('static', crawlingContext, crawlingContext.useState, httpAttempt);
467
+ if (plainHTTPRun.ok &&
468
+ this.#resultChecker(plainHTTPRun.transaction, { request: crawlingContext.request })) {
345
469
  crawlingContext.log.debug(`HTTP-only request handler succeeded for ${crawlingContext.request.url}`);
346
- plainHTTPRun.logs?.forEach(([log, method, ...args]) => log[method](...args));
347
- await plainHTTPRun.result.commit();
470
+ plainHTTPRun.logs.forEach(([log, method, ...args]) => log[method](...args));
471
+ this.#keepContextModifications(plainHTTPRun.contextModifications);
472
+ await plainHTTPRun.transaction.commit();
348
473
  return;
349
474
  }
350
475
  // Execution will "fall through" and try running the request handler in a browser
@@ -355,54 +480,62 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
355
480
  : plainHTTPRun.error;
356
481
  if (actualError instanceof ContextPipelineInterruptedError ||
357
482
  (await this.#shouldPropagateError(actualError, crawlingContext))) {
483
+ this.#keepContextModifications(plainHTTPRun.contextModifications);
484
+ httpAttempt.exposeToErrorHandlers(crawlingContext);
358
485
  throw actualError;
359
486
  }
360
487
  crawlingContext.log.exception(actualError, `HTTP-only request handler failed for ${crawlingContext.request.url}`);
488
+ await httpAttempt.release();
361
489
  }
362
490
  else {
363
491
  crawlingContext.log.warning(`HTTP-only request handler returned a suspicious result for ${crawlingContext.request.url}`);
364
492
  this.statistics.state.renderingTypeMispredictions++;
493
+ resultCheckerRejectedHttpResult = true;
365
494
  }
495
+ // The browser attempt starts from the request and state as they were before the rejected one.
496
+ this.#discardContextModifications(plainHTTPRun.contextModifications, crawlingContext);
366
497
  }
367
498
  crawlingContext.log.debug(`Running browser request handler for ${crawlingContext.request.url}`);
368
499
  this.statistics.state.browserRequestHandlerRuns++;
369
- // Run the request handler in a browser. The copy of the crawler state is kept so that we can perform
370
- // a rendering type detection if necessary. Without this measure, the HTTP request handler would run
371
- // under different conditions, which could change its behavior. Changes done to the crawler state by
372
- // the HTTP request handler will not be committed to the actual storage.
373
- const stateTracker = {
374
- stateCopy: null,
375
- async getLiveState(defaultValue = {}) {
376
- const state = await crawlingContext.useState(defaultValue);
377
- if (this.stateCopy === null) {
378
- this.stateCopy = JSON.parse(JSON.stringify(state));
379
- }
380
- return state;
381
- },
382
- async getStateCopy(defaultValue = {}) {
383
- if (this.stateCopy === null) {
384
- return defaultValue;
385
- }
386
- return this.stateCopy;
387
- },
388
- };
389
- const browserRun = await this.#crawlOne('clientOnly', crawlingContext, stateTracker.getLiveState.bind(stateTracker), transactions);
500
+ const browserAttempt = startAttempt();
501
+ const browserRun = await this.#crawlOne('clientOnly', crawlingContext, crawlingContext.useState, browserAttempt);
390
502
  if (!browserRun.ok) {
503
+ // A failed browser attempt is handed to the retry logic with its writes - `userData` stashed for the
504
+ // next attempt must survive.
505
+ this.#keepContextModifications(browserRun.contextModifications);
506
+ browserAttempt.exposeToErrorHandlers(crawlingContext);
391
507
  throw browserRun.error;
392
508
  }
393
- browserRun.logs?.forEach(([log, method, ...args]) => log[method](...args));
394
- await browserRun.result.commit();
509
+ try {
510
+ browserRun.logs.forEach(([log, method, ...args]) => log[method](...args));
511
+ // The `afterStorageCommit` callbacks belong to this attempt, so the detection rerun undoes their
512
+ // writes too - the journals stay open until they have run.
513
+ await browserRun.transaction.commit();
514
+ }
515
+ finally {
516
+ this.#keepContextModifications(browserRun.contextModifications);
517
+ }
518
+ // Past the shutdown fence, `teardown()` has already drained - and possibly torn down the predictor.
519
+ if (resultCheckerRejectedHttpResult && !this.#shutDown) {
520
+ this.#storeRenderingType(crawlingContext.request, 'clientOnly');
521
+ }
395
522
  if (shouldDetectRenderingType) {
396
523
  const detectionPromise = (async () => {
397
524
  crawlingContext.log.debug(`Detecting rendering type for ${crawlingContext.request.url}`);
398
525
  // The detection attempt's transaction is never committed - its writes exist only for the
399
- // result comparison.
400
- const plainHTTPRun = await this.#crawlOne('static', crawlingContext, stateTracker.getStateCopy.bind(stateTracker), transactions);
526
+ // result comparison. It runs on copies of the request and the crawler state with the browser
527
+ // attempt's writes undone, so both attempts start from the same conditions, and the copies go
528
+ // away with it.
529
+ const { request: requestJournal, state: stateJournal } = browserRun.contextModifications;
530
+ let stateCopy;
531
+ 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)))));
401
532
  const detectionResult = (() => {
402
533
  if (!plainHTTPRun.ok) {
403
534
  return 'clientOnly';
404
535
  }
405
- const comparisonResult = this.#resultComparator(plainHTTPRun.result, browserRun.result);
536
+ const comparisonResult = this.#resultComparator(plainHTTPRun.transaction, browserRun.transaction, {
537
+ request: crawlingContext.request,
538
+ });
406
539
  if (comparisonResult === true || comparisonResult === 'equal') {
407
540
  return 'static';
408
541
  }
@@ -413,24 +546,39 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
413
546
  })();
414
547
  crawlingContext.log.debug(`Detected rendering type ${detectionResult} for ${crawlingContext.request.url}`);
415
548
  if (detectionResult !== undefined) {
416
- // Deliberately not awaited: a predictor that persists asynchronously gets to keep
417
- // batching its writes, and the drain below catches whatever is still pending.
418
- const stored = this.#renderingTypePredictor.value.storeResult(crawlingContext.request, detectionResult);
419
- if (stored !== undefined) {
420
- // Nothing downstream awaits this, so a failed write would otherwise be silent.
421
- void this.#trackDetection(Promise.resolve(stored).catch((error) => this.log.exception(error, `Failed to store the rendering type detection result for ${crawlingContext.request.url}`)));
422
- }
549
+ this.#storeRenderingType(crawlingContext.request, detectionResult);
423
550
  }
424
551
  })();
425
552
  await this.#trackDetection(detectionPromise);
426
553
  }
427
554
  }
428
555
  finally {
429
- // A still-open transaction here belongs to a discarded attempt - roll it back, then release.
430
- for (const transaction of transactions) {
431
- transaction.rollback();
432
- transaction.dispose();
433
- }
556
+ await Promise.all(attempts.map(async (attempt) => attempt.settle()));
557
+ }
558
+ }
559
+ #keepContextModifications(modifications) {
560
+ modifications.request.close();
561
+ modifications.state.close();
562
+ }
563
+ #discardContextModifications(modifications, { request, log }) {
564
+ // Nothing else writes to a request while its handler runs, so a conflict means a write that bypassed
565
+ // the context (e.g. through a stashed reference) - it stays, but it is not what the retry logic expects.
566
+ modifications.request.revert({
567
+ onConflict: (key) => log.warning(`Request ${request.url}: '${String(key)}' was modified outside the request handler`),
568
+ });
569
+ // The state is shared with concurrent handlers; a conflict is one of them having written the same
570
+ // property meanwhile. Their value wins, and this attempt's write stays with it.
571
+ modifications.state.revert({
572
+ onConflict: (key) => log.debug(`Crawler state '${String(key)}' was changed concurrently; keeping the newer value`),
573
+ });
574
+ }
575
+ #storeRenderingType(request, renderingType) {
576
+ // Deliberately not awaited: a predictor that persists asynchronously gets to keep batching its writes,
577
+ // and `drainRenderingDetections()` catches whatever is still pending.
578
+ const stored = this.#renderingTypePredictor.value.storeResult(request, renderingType);
579
+ if (stored !== undefined) {
580
+ // Nothing downstream awaits this, so a failed write would otherwise be silent.
581
+ void this.#trackDetection(Promise.resolve(stored).catch((error) => this.log.exception(error, `Failed to store the rendering type detection result for ${request.url}`)));
434
582
  }
435
583
  }
436
584
  async #enqueueLinks(urls, options, request) {
@@ -1,8 +1,16 @@
1
- import type { Configuration } from '@crawlee/browser';
2
- import type { BrowserPool, BrowserPoolHooks, BrowserPoolOptions, PlaywrightPlugin, RemoteBrowserPool, RemoteBrowserPoolOptions } from '@crawlee/browser-pool';
1
+ import type { Configuration, CrawlerRemoteBrowserOptions } from '@crawlee/browser';
2
+ import type { BrowserPool, BrowserPoolHooks, BrowserPoolOptions, PlaywrightPlugin } from '@crawlee/browser-pool';
3
3
  // @ts-ignore optional peer dependency or compatibility with es2022
4
4
  import type { Page } from 'playwright';
5
5
  import type { PlaywrightLaunchContext } from './playwright-launcher.js';
6
+ /** {@link BrowserCrawlerOptions.remoteBrowser|`remoteBrowser`} for Playwright, with the protocol to connect over. */
7
+ export interface PlaywrightRemoteBrowserOptions extends CrawlerRemoteBrowserOptions {
8
+ /**
9
+ * `'cdp'` uses `connectOverCDP()` (the default), `'playwright'` uses `connect()` (Playwright's own WebSocket
10
+ * protocol, for endpoints started with `launchServer()`).
11
+ */
12
+ protocol?: 'cdp' | 'playwright';
13
+ }
6
14
  /** A {@link BrowserPool} of Playwright browsers, as built by {@link playwrightBrowserPool}. */
7
15
  export type PlaywrightBrowserPool = BrowserPool<{
8
16
  browserPlugins: [PlaywrightPlugin];
@@ -17,8 +25,8 @@ export interface PlaywrightBrowserPoolOptions extends Omit<BrowserPoolOptions, '
17
25
  headless?: boolean;
18
26
  /** Configuration to read the browser defaults from. Defaults to the global configuration. */
19
27
  configuration?: Configuration;
20
- }
21
- export interface RemotePlaywrightBrowserPoolOptions extends Pick<PlaywrightBrowserPoolOptions, 'launchContext' | 'headless' | 'configuration'>, Omit<RemoteBrowserPoolOptions, 'browserPlugins'> {
28
+ /** Connect to a remote browser service instead of launching locally; see {@link BrowserCrawlerOptions.remoteBrowser}. */
29
+ remoteBrowser?: PlaywrightRemoteBrowserOptions;
22
30
  }
23
31
  /**
24
32
  * Builds a {@link BrowserPool} of Playwright browsers to pass to a {@link PlaywrightCrawler} as its
@@ -45,27 +53,3 @@ export interface RemotePlaywrightBrowserPoolOptions extends Pick<PlaywrightBrows
45
53
  * @category Browser management
46
54
  */
47
55
  export declare function playwrightBrowserPool(options?: PlaywrightBrowserPoolOptions): PlaywrightBrowserPool;
48
- /**
49
- * The {@link RemoteBrowserPool} counterpart of {@link playwrightBrowserPool}: connects to a remote browser
50
- * service (Browserbase, Browserless, Steel, ...) with a Playwright plugin derived from `launchContext`.
51
- *
52
- * A {@link PlaywrightCrawler} accepts the same connection details directly via
53
- * {@link BrowserCrawlerOptions.remoteBrowser|`remoteBrowser`}; reach for this factory when you also need to
54
- * tune the wrapping pool, or to share one remote pool between crawlers.
55
- *
56
- * **Example usage:**
57
- *
58
- * ```javascript
59
- * const crawler = new PlaywrightCrawler({
60
- * browserPool: remotePlaywrightBrowserPool({
61
- * endpoint: 'wss://production-sfo.browserless.io?token=xxx',
62
- * maxOpenBrowsers: 2,
63
- * browserPoolOptions: { useFingerprints: false },
64
- * }),
65
- * requestHandler: async ({ page }) => { ... },
66
- * });
67
- * ```
68
- *
69
- * @category Browser management
70
- */
71
- export declare function remotePlaywrightBrowserPool(options: RemotePlaywrightBrowserPoolOptions): RemoteBrowserPool<Page>;