@crawlee/cli 4.0.0-beta.34 → 4.0.0-beta.341
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/commands/{CreateProjectCommand.d.ts → create-project-command.d.ts} +0 -1
- package/commands/{CreateProjectCommand.js → create-project-command.js} +4 -6
- package/commands/{InstallPlaywrightBrowsersCommand.d.ts → install-playwright-browsers-command.d.ts} +0 -1
- package/commands/{InstallPlaywrightBrowsersCommand.js → install-playwright-browsers-command.js} +0 -1
- package/commands/{RunProjectCommand.d.ts → run-project-command.d.ts} +0 -1
- package/commands/{RunProjectCommand.js → run-project-command.js} +0 -1
- package/commands/upgrade-command.d.ts +19 -0
- package/commands/upgrade-command.js +150 -0
- package/index.d.ts +0 -1
- package/index.js +16 -5
- package/package.json +10 -10
- package/skills/crawlee-upgrade/SKILL.md +20 -0
- package/skills/crawlee-upgrade-v4/SKILL.md +58 -0
- package/skills/crawlee-upgrade-v4/guide/autoscaling.md +256 -0
- package/skills/crawlee-upgrade-v4/guide/browser-management.md +174 -0
- package/skills/crawlee-upgrade-v4/guide/http-clients.md +108 -0
- package/skills/crawlee-upgrade-v4/guide/internals.md +130 -0
- package/skills/crawlee-upgrade-v4/guide/removed-symbols.md +63 -0
- package/skills/crawlee-upgrade-v4/guide/request-loaders.md +241 -0
- package/skills/crawlee-upgrade-v4/guide/sessions-and-proxies.md +164 -0
- package/skills/crawlee-upgrade-v4/guide/statistics.md +56 -0
- package/skills/crawlee-upgrade-v4/guide/storage-backends.md +171 -0
- package/skills/crawlee-upgrade-v4/guide/upgrading-v4.md +1377 -0
- package/skills/crawlee-upgrade-v4/guide/utils-and-types.md +52 -0
- package/commands/CreateProjectCommand.d.ts.map +0 -1
- package/commands/CreateProjectCommand.js.map +0 -1
- package/commands/InstallPlaywrightBrowsersCommand.d.ts.map +0 -1
- package/commands/InstallPlaywrightBrowsersCommand.js.map +0 -1
- package/commands/RunProjectCommand.d.ts.map +0 -1
- package/commands/RunProjectCommand.js.map +0 -1
- package/index.d.ts.map +0 -1
- package/index.js.map +0 -1
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: internals
|
|
3
|
+
title: 'Upgrading to v4: subclassing and internals'
|
|
4
|
+
sidebar_label: Subclassing and internals
|
|
5
|
+
sidebar_position: 1
|
|
6
|
+
slug: /upgrading/upgrading-to-v4/internals
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
Skip this section unless you subclass Crawlee classes, override `protected` members, or read fields that were never documented. This page is part of the [Upgrading to v4](./upgrading-v4.md) guide.
|
|
10
|
+
|
|
11
|
+
## Underscore prefix is removed from many protected and private methods
|
|
12
|
+
|
|
13
|
+
The leading underscore was dropped from protected and private class members across the codebase. The most visible rename is:
|
|
14
|
+
|
|
15
|
+
- `BasicCrawler._runRequestHandler` -> `BasicCrawler.runRequestHandler`
|
|
16
|
+
|
|
17
|
+
If you subclass a crawler or implement a custom browser plugin, these `protected` extension points lost their underscore too:
|
|
18
|
+
|
|
19
|
+
- `BasicCrawler._init` -> `init`
|
|
20
|
+
- `BasicCrawler._throwOnBlockedRequest` -> `throwOnBlockedRequest`
|
|
21
|
+
- `BasicCrawler._getMessageFromError` -> `getMessageFromError`
|
|
22
|
+
- `BasicCrawler._getCookieHeaderFromRequest` -> `getCookieHeaderFromRequest`
|
|
23
|
+
- `BrowserCrawler._navigationHandler` -> `navigationHandler` (including the `PlaywrightCrawler`, `PuppeteerCrawler` and `StagehandCrawler` overrides)
|
|
24
|
+
- `BrowserPlugin._addProxyToLaunchOptions` -> `addProxyToLaunchOptions`
|
|
25
|
+
- `BrowserPlugin._isChromiumBasedBrowser` -> `isChromiumBasedBrowser`
|
|
26
|
+
- `BrowserPlugin._throwAugmentedLaunchError` -> `throwAugmentedLaunchError`
|
|
27
|
+
|
|
28
|
+
The `@internal` `PlaywrightBrowser._setBrowserType` was renamed the same way, to `setBrowserType`.
|
|
29
|
+
|
|
30
|
+
A handful of hooks intentionally keep the underscore, because the un-prefixed name is taken by their public wrapper method: `BrowserPlugin._launch` (wrapped by `launch()`) and `BrowserController._close`, `_kill`, `_newPage`, `_getCookies`, `_setCookies` (wrapped by the same names without the underscore). Custom plugin or controller implementations override these under their existing names, unchanged.
|
|
31
|
+
|
|
32
|
+
Members that were also made `private` in the same pass are listed under [Unintentionally exposed internals are now private](#unintentionally-exposed-internals-are-now-private) below.
|
|
33
|
+
|
|
34
|
+
## Private properties are native `#` fields now
|
|
35
|
+
|
|
36
|
+
Private class properties across the codebase were converted from TypeScript's compile-time `private` to native ECMAScript private fields (`#name`). Where a `private _foo` field backed a `get foo()` accessor, the field is now `#foo` — the public accessor is unchanged.
|
|
37
|
+
|
|
38
|
+
TypeScript's `private` was purely a compile-time construct: the properties still existed on the instances at runtime, so code could reach them via `(crawler as any).something` or `crawler['something']`, and they showed up in `Object.keys()`, object spread and `JSON.stringify()`. Native `#` fields close that hole — they are inaccessible outside the declaring class and invisible to enumeration and serialization. If you were reaching into any of them, that now fails at runtime, not just in the type checker. As with the visibility tightening above, the supported extension points (handlers, hooks, `ContextPipeline` composition and the `ISessionPool` / `IBrowserPool` / `IRequestManager` interfaces) are the way to go; open an issue if something you need is missing.
|
|
39
|
+
|
|
40
|
+
One related behavior change: `LaunchContext.extend()` now consistently rejects all declared fields as reserved keys — including `fingerprint` and `proxyUrl`, which previously slipped through the reserved-name check. Set those directly instead (e.g. `launchContext.fingerprint = ...`); `extend()` is only for attaching your own extra fields.
|
|
41
|
+
|
|
42
|
+
## Unintentionally exposed internals are now private
|
|
43
|
+
|
|
44
|
+
A number of class members were `public` or `protected` only by accident — they were never meant to be part of the extension surface, are not used by any subclass, and in most cases also carried a leading underscore to signal that. In v4 they are `private` (and where it applies, `readonly`). If you were reaching into any of these — either to read internal state or to override a helper in a subclass — that no longer compiles.
|
|
45
|
+
|
|
46
|
+
This is intentional: these were never a supported API. If you relied on overriding one of the now-private helpers, the supported extension points (the `requestHandler`, `errorHandler`, `failedRequestHandler`, `preNavigationHooks`/`postNavigationHooks`, `ContextPipeline` composition, and the `ISessionPool` / `IBrowserPool` / `IRequestManager` interfaces) should cover the same use cases. If something you genuinely need is missing, open an issue.
|
|
47
|
+
|
|
48
|
+
The change spans, among others:
|
|
49
|
+
|
|
50
|
+
- **`BasicCrawler`** — `unexpectedStop`, `requestHandlerTimeoutMillis`, `sameDomainDelayMillis`, `domainAccessedTime`, `handledRequestsCount`, `statusMessageLoggingInterval`, `statusMessageCallback`, `ignoreHttpErrorStatusCodes`, `taskLoopOptions` (was `autoscaledPoolOptions`), `autoscaledPool`, `respectRobotsTxtFile`, and the helpers `buildBasicContextPipeline`, `validateRequestUserData`, `pauseOnMigration`, `fetchNextRequest`, `delayRequest`, `handleRequest`, `timeoutAndRetry`, `isTaskReadyFunction`, `defaultIsFinishedFunction`, `requestFunctionErrorHandler`, `handleFailedRequestHandler`, `canRequestBeRetried`
|
|
51
|
+
- **`HttpCrawler`** — `preNavigationHooks`, `postNavigationHooks`, `saveResponseCookies`, `navigationTimeoutMillis`, `suggestResponseEncoding`, `forceResponseEncoding`, `supportedMimeTypes`, and the helpers `requestFunction`, `parseResponse`, `getRequestOptions`, `encodeResponse`, `extendSupportedMimeTypes`, `handleRequestTimeout`
|
|
52
|
+
- **`AutoscaledPool`** — the whole class is `@internal` in v4, so its members are not enumerated here; see [`AutoscaledPool` is no longer public API](./autoscaling.md#autoscaledpool-is-no-longer-public-api)
|
|
53
|
+
- **`SessionPool`** — all pool internals (`log`, `maxPoolSize`, `createSessionFunction`, `keyValueStore`, `sessions`, `sessionMap`, `sessionOptions`, `persistStateKey`, `persistStateKeyValueStoreId`, `events`, `persistenceOptions`, `sessionReuseStrategy`, and the helpers `ensureInitialized`, `maybeLoadSessionPool`, `registerSession`, `createSession`, `hasSpaceForSession`, `pickSession`, `removeRetiredSessions`, `getRandomIndex`, `defaultCreateSessionFunction`)
|
|
54
|
+
- **`Session`** — `maybeSelfRetire` (`userData` is now `readonly`)
|
|
55
|
+
- **`RequestList`** — all `_`-prefixed helpers (`addFetchedRequests`, `addPersistedRequests`, `addRequest`, `addRequestsFromSources`, `ensureInProgress`, `ensureIsInitialized`, `ensureUniqueKeyValid`, `fetchRequestsFromUrl`, `getPersistedState`, `loadStateAndPersistedRequests`, `persistRequests`, `restoreState`)
|
|
56
|
+
- **`RequestQueue`** — `proxyConfiguration`, `requestCache`, `requestSeenCache`, `queuePausedForMigration`, `inProgressRequestBatchCount`, `expectedRequestProcessingSecs`, `httpClient`, `events`, and the helpers `cacheRequest`, `fetchRequestsFromUrl`, `addFetchedRequests` (`id`, `name`, `backend`, `log` are now `readonly`)
|
|
57
|
+
- **`ProxyConfiguration`** — `nextCustomUrlIndex`, `proxyUrls`, `newUrlFunction`, and the helpers `handleProxyUrlsList`, `callNewUrlFunction`, `throwCannotCombineCustomMethods`, `throwNoOptionsProvided` (the internal `log` field and `usedProxyUrls` map are removed; `isManInTheMiddle` is now `readonly`)
|
|
58
|
+
- **`Statistics`** — `saveRetryCountForRequest` (was `saveRetryCountForJob`), `teardown`, `keyValueStore` (`errorTracker`, `errorTrackerRetry` are now `readonly`, and `state` / `requestRetryHistogram` are getters)
|
|
59
|
+
- **`SystemStatus`** — `isSystemIdle`
|
|
60
|
+
- **`Router`** — the constructor is now `private`; use the static `Router.create()` factory
|
|
61
|
+
- **`BaseHttpClient`** — `log` (subclasses receive it via the constructor `logger` option instead of reading `this.log`)
|
|
62
|
+
- **`JSDOMCrawler`** — `runScripts`, `hideInternalConsole`, `virtualConsole`
|
|
63
|
+
- **`AdaptivePlaywrightCrawler`** — `commitResult`, `allowStorageAccess`, `enqueueLinks`
|
|
64
|
+
- **`RenderingTypePredictor`** — `calculateFeatureVector`, `retrain`
|
|
65
|
+
- **`BrowserCrawler`** — `navigationTimeoutMillis`, `preNavigationHooks`, `postNavigationHooks`, `saveResponseCookies` (now `private readonly`; configure them through the constructor options as before), and the helpers `isRequestBlocked`, `applyCookies` (was `_applyCookies`), `handleNavigationTimeout` (was `_handleNavigationTimeout`), `throwIfProxyError` (was `_throwIfProxyError`)
|
|
66
|
+
- **`BrowserLauncher`** — the helpers `getChromeExecutablePath`, `getTypicalChromeExecutablePath`, `validateProxyUrlProtocol` (were `_`-prefixed). `getDefaultHeadlessOption` (was `_getDefaultHeadlessOption`) stays `protected` — it is an override point (`PuppeteerLauncher` overrides it) — but lost its underscore prefix
|
|
67
|
+
- **`RobotsTxtFile.load` and `Sitemap.parse`** — internal static factory helpers, now `private` (use the public `RobotsTxtFile.from` / `Sitemap.load` / `Sitemap.fromXmlString` entry points)
|
|
68
|
+
- Various internal fields on `BrowserController` (`id`, `browserPlugin`) and `BrowserPlugin` (`name`, `library`, `launchOptions`, `proxyUrl`, `userDataDir`, `browserPerProxy`, `ignoreProxyCertificate`) are now `readonly` (the `log` field on both is off the public surface entirely — see [`BrowserPool` internals are private](./browser-management.md#browserpool-internals-are-private))
|
|
69
|
+
|
|
70
|
+
`BasicCrawler.running` remains public as a read-only getter indicating whether `run()` is in progress. Existing reads still work; assignments no longer do. The same goes for `hasFinishedBefore`: it is a public read-only getter now, and can no longer be assigned.
|
|
71
|
+
|
|
72
|
+
## Declarations that are now `@internal`
|
|
73
|
+
|
|
74
|
+
These are still present at runtime, but they are excluded from the documented surface and can change without a major version bump: `Session.getState()`, `SessionOptions.log` and `RestrictedCrawlingContext.id`.
|
|
75
|
+
|
|
76
|
+
`BLOCKED_STATUS_CODES` is now typed `readonly number[]`. Copy it (`[...BLOCKED_STATUS_CODES]`) if you were mutating it.
|
|
77
|
+
|
|
78
|
+
## `HttpCrawler.isRequestBlocked` is now private
|
|
79
|
+
|
|
80
|
+
Block detection is configured through `retryOnBlocked` and `blockedStatusCodes`; to add your own checks, throw a `SessionError` from a `postNavigationHook`.
|
|
81
|
+
|
|
82
|
+
## The protected `getMessageFromError()` returns `string`
|
|
83
|
+
|
|
84
|
+
`BasicCrawler.getMessageFromError()` previously widened its return type to `string | TimeoutError | undefined`. Overrides must now return a `string`, and callers can drop any `as string` casts.
|
|
85
|
+
|
|
86
|
+
## The `RequestQueue` constructor no longer takes a `Configuration`
|
|
87
|
+
|
|
88
|
+
The internal `RequestQueue` constructor dropped its second `config: Configuration` parameter (it also stopped exposing a `protected config` field). You should not be constructing `RequestQueue` directly anyway — use `RequestQueue.open()`, which resolves configuration for you.
|
|
89
|
+
|
|
90
|
+
## Crawler generic parameters and handler types changed
|
|
91
|
+
|
|
92
|
+
To support the new `ContextPipeline` / `extendContext` composition, the crawler classes gained additional generic type parameters. `BasicCrawler<Context>` is now `BasicCrawler<Context, ContextExtension, ExtendedContext>`, and the same pattern was propagated to `HttpCrawler`, `CheerioCrawler`, `JSDOMCrawler`, `LinkeDOMCrawler`, `PuppeteerCrawler`, `PlaywrightCrawler`, `StagehandCrawler`, and their `*Options` interfaces. This only affects you if you **explicitly annotated** crawler generics or **subclassed** a crawler while narrowing its `Context` — in that case the compiler now expects the extra parameters (and a matching `contextPipelineBuilder`). Most users, who let the types be inferred, are unaffected.
|
|
93
|
+
|
|
94
|
+
The exported handler types were reshaped accordingly. `ErrorHandler` and `RequestHandler` no longer wrap their context in `LoadedContext<...>`; `ErrorHandler` now takes two type parameters (`ErrorHandler<BaseContext, ExtendedContext>`), receiving `inputs: BaseContext & Partial<ExtendedContext>`. The `LoadedContext` type is internal and no longer part of the public API; `RestrictedCrawlingContext` stays exported from `@crawlee/basic`. If you annotated handlers with `LoadedContext` directly, update the references; if you only used the crawler options' `requestHandler` / `errorHandler` / `failedRequestHandler` callbacks with inferred parameter types, nothing changes.
|
|
95
|
+
|
|
96
|
+
## `Request` is split into `Request` and `CrawlingRequest`
|
|
97
|
+
|
|
98
|
+
`Request` in `@crawlee/core` is now just the stored record: URL, method, headers, payload, `userData`, `label` and the processing state a request queue keeps (`id`, `retryCount`, `errorMessages`, `handledAt`, `loadedUrl`). Everything a crawler reads off a request — `skipNavigation`, `crawlDepth`, `sessionId`, `maxRetries`, `state`, `pushErrorMessage()` — lives on `CrawlingRequest` in `@crawlee/basic`, which is what `request` is in every request handler and hook. `RequestState` moved along with it, so import it from `@crawlee/basic` (or `crawlee`), not `@crawlee/core`. Handler code is unaffected; the change only shows if you construct requests yourself or read them straight from a request manager:
|
|
99
|
+
|
|
100
|
+
- The options are unchanged: `new Request({ url, skipNavigation: true, maxRetries: 2 })` and `queue.addRequest({ url, sessionId })` still record the settings, they just are not readable as properties on the core class. Where you need them, `CrawlingRequest.fromSchema(request)` rebuilds the crawler view.
|
|
101
|
+
- `RequestOptions` no longer accepts `id` or `handledAt`, and the constructor ignores `retryCount`, `errorMessages` and `loadedUrl`. A request coming back from a storage is rebuilt with `Request.fromSchema(record)`, which is also what `RequestQueue` does internally.
|
|
102
|
+
- `RequestOptions.skippedReason` and `Request.skippedReason` are removed. They were an internal side-channel for reporting `maxCrawlDepth` skips out of a `transformRequestFunction`; the depth check no longer runs inside the transform, so nothing writes them.
|
|
103
|
+
- `crawlingContext.request` is never the object your request manager handed out — the crawler rebuilds it as a `CrawlingRequest`. With a `RequestQueue` that was already true (requests are rebuilt from the stored record on every fetch), and in v4 `RequestList` and `SitemapRequestLoader` feed the crawler through a queue too; the change is only observable with a custom `IRequestManager` whose `fetchNextRequest()` returned its own instances. The object passed back to `reclaimRequest()` / `markRequestAsHandled()` is the crawler's copy, so match on `uniqueKey` (or `id`), not by identity.
|
|
104
|
+
|
|
105
|
+
## Navigation hook types are now generic
|
|
106
|
+
|
|
107
|
+
`PlaywrightHook`, `PuppeteerHook` and `StagehandHook` are now type aliases (previously interfaces) generic over the request's `userData` type. A hook that types its context — via the generic (e.g. `PlaywrightHook<MyUserData>`) or an explicit context annotation — is now assignable to the `preNavigationHooks` / `postNavigationHooks` options of an untyped crawler. If you extended one of these interfaces, use an intersection type instead.
|
|
108
|
+
|
|
109
|
+
## Removed navigation hook type aliases
|
|
110
|
+
|
|
111
|
+
The `HttpHook`, `CheerioHook`, `JSDOMHook`, `LinkeDOMHook` and `FileDownloadHook` type aliases were removed. None of them could actually type a `preNavigationHooks` or `postNavigationHooks` entry: both options are typed over the *pre-navigation* crawling context, while these aliases closed over the fully parsed one — so a function annotated with them required the pre-navigation context to already supply `$`, `body` or `window`, and assignment was rejected. (`FileDownload` has no hook options at all.)
|
|
112
|
+
|
|
113
|
+
Let the hook be inferred from the options object, or annotate its parameter with the crawler's own context type:
|
|
114
|
+
|
|
115
|
+
```diff
|
|
116
|
+
-const hook: CheerioHook = async (ctx) => { /* ... */ };
|
|
117
|
+
+const hook = async (ctx: CheerioCrawlingContext) => { /* ... */ };
|
|
118
|
+
|
|
119
|
+
new CheerioCrawler({ preNavigationHooks: [hook] });
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
To type a standalone hook against the pre-navigation context, use `InternalHttpHook<CrawlingContext>`.
|
|
123
|
+
|
|
124
|
+
## `RecoverableState` reshaped
|
|
125
|
+
|
|
126
|
+
`serialize` and `deserialize` now take and return values rather than strings (so v3 records will not load) and each also accept a [Standard Schema](https://standardschema.dev) — a zod codec works as `deserialize` directly — `reset()` is synchronous, no longer clears the persisted record (the new `resetStore()` does) and doubles as a way to establish the state without awaiting `initialize()`, `persistStateKvsName` and `persistStateKvsId` collapsed into a single `keyValueStore` option taking a store (or a pending `KeyValueStore.open()`), `defaultState` also accepts a factory (which you need for a state `structuredClone` cannot rebuild, as the deep copy no longer goes through `serialize`/`deserialize`), and there is a new `persistenceTimeoutMillis` option. `teardown()` is no longer terminal — `initialize()` can be called again to open another persistence window — and a write that fails during a periodic `PERSIST_STATE` or during `teardown()` is warned about rather than thrown. A direct `persistState()` still throws.
|
|
127
|
+
|
|
128
|
+
## The `log` property is typed as `CrawleeLogger`
|
|
129
|
+
|
|
130
|
+
The `log` property exposed throughout the public API (on the crawling context, the crawler, `RequestQueue`, etc.) is now typed as the `CrawleeLogger` interface (from `@crawlee/types`) rather than the concrete `Log` class from `@apify/log`. If you consume it structurally — calling `log.info(...)`, `log.debug(...)`, `log.child(...)` — nothing changes. You only need to act if you explicitly annotated a variable or parameter with the `Log` type from `@apify/log` and assigned `context.log` to it; type it as `CrawleeLogger` instead.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: removed-symbols
|
|
3
|
+
title: 'Upgrading to v4: removed symbols'
|
|
4
|
+
sidebar_label: Removed symbols
|
|
5
|
+
sidebar_position: 10
|
|
6
|
+
slug: /upgrading/upgrading-to-v4/removed-symbols
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
The full list of removed exports and members, for ctrl-F purposes. Where a replacement exists, it is noted inline. This page is part of the [Upgrading to v4](./upgrading-v4.md) guide.
|
|
10
|
+
|
|
11
|
+
## Removed symbols
|
|
12
|
+
|
|
13
|
+
- `BasicCrawler._cleanupContext` (protected) - this is now handled by the `ContextPipeline`
|
|
14
|
+
- `BasicCrawler.isRequestBlocked` (protected)
|
|
15
|
+
- `BasicCrawler.events` (protected) - use the `serviceLocator` export of `@crawlee/core` instead (`serviceLocator.getEventManager()`); the crawler scopes it to its own services while its methods run
|
|
16
|
+
- `BrowserRequestHandler` and `BrowserErrorHandler` types in `@crawlee/browser`
|
|
17
|
+
- `BrowserCrawler.userProvidedRequestHandler` (protected)
|
|
18
|
+
- `BrowserCrawler.requestHandlerTimeoutInnerMillis` (protected)
|
|
19
|
+
- `BrowserCrawler._enhanceCrawlingContextWithPageInfo` (protected)
|
|
20
|
+
- `BrowserCrawler._handleNavigation` (protected)
|
|
21
|
+
- `HttpCrawler.userRequestHandlerTimeoutMillis` (protected)
|
|
22
|
+
- `HttpCrawler._handleNavigation` (protected)
|
|
23
|
+
- `HttpCrawler._applyCookies` (protected) - cookie merging is now handled by `BaseHttpClient`
|
|
24
|
+
- `HttpCrawler._parseHTML` (protected)
|
|
25
|
+
- `HttpCrawler.use` and the `CrawlerExtension` class (experimental) - the `ContextPipeline` should be used for extending the crawler
|
|
26
|
+
- `BasicCrawler._tagUserHandlerError` (protected) - internal error-tagging helper, no longer part of the crawler surface
|
|
27
|
+
- `BasicCrawler.handledRequestsCount` setter (`@deprecated`) - the throw-on-assign guard is gone; the getter is now internal-only and the count is derived from `this.statistics`
|
|
28
|
+
- `PlaywrightPlugin._containerProxyServer` (public) - was only populated with `experimentalContainers`, and is removed together with that option
|
|
29
|
+
- `Snapshotter._snapshotMemory`, `Snapshotter._memoryOverloadWarning`, `Snapshotter._snapshotEventLoop`, `Snapshotter._snapshotCpu`, `Snapshotter._snapshotClient`, `Snapshotter._pruneSnapshots` (all `@deprecated` protected stubs) - snapshotting is now handled by the individual load signals, and the `Snapshotter` itself is internal to `ConcurrencySystem`; there is no longer a public API for reading raw resource snapshots
|
|
30
|
+
- `FileDownloadOptions.streamHandler` - streaming should now be handled directly in the `requestHandler` instead
|
|
31
|
+
- `playwrightUtils.registerUtilsToContext` and `puppeteerUtils.registerUtilsToContext` - this is now added to the context via `ContextPipeline` composition
|
|
32
|
+
- `context.blockResources` and `context.cacheResponses`, and the `puppeteerUtils.blockResources` / `puppeteerUtils.cacheResponses` functions behind them — both had a severe performance cost in recent Puppeteer versions and were already deprecated. Use `puppeteerUtils.blockRequests(page, options)`, which blocks URL patterns over CDP without disabling the browser cache. If you were caching responses, rely on the in-browser cache instead.
|
|
33
|
+
- `context.closeCookieModals`, `playwrightUtils.closeCookieModals` and `puppeteerUtils.closeCookieModals` — removed along with the optional `idcac-playwright` peer dependency (see [Crawling context no longer includes `closeCookieModals`](./upgrading-v4.md#crawling-context-no-longer-includes-closecookiemodals) and the [cookie modals guide](https://crawlee.dev/js/docs/next/guides/cookie-modals))
|
|
34
|
+
- `Configuration.systemInfoV2` / `CRAWLEE_SYSTEM_INFO_V2` environment variable — the v2 behavior is now the default (see [Available resource detection](./utils-and-types.md#available-resource-detection))
|
|
35
|
+
- `KeyValueStore.getInput()` and `Configuration.inputKey` / `CRAWLEE_INPUT_KEY` — reading the run input moved to the Apify SDK (see [`KeyValueStore.getInput()` and `Configuration.inputKey` moved to the Apify SDK](./upgrading-v4.md#keyvaluestoregetinput-and-configurationinputkey-moved-to-the-apify-sdk))
|
|
36
|
+
- `Configuration.defaultDatasetId` / `defaultKeyValueStoreId` / `defaultRequestQueueId` and their `CRAWLEE_DEFAULT_*_ID` environment variables — the default storage is addressed by a reserved alias, not by a configurable ID. Open a storage by name if you need a specific one.
|
|
37
|
+
- `checkAndSerialize` and `chunkBySize` functions (from `@crawlee/core`) — internal helpers of `Dataset.pushData()` (JSON-serializability and size checks, batching); there is no public replacement
|
|
38
|
+
- `BASIC_CRAWLER_TIMEOUT_BUFFER_SECS` constant (from `@crawlee/basic`) — was an internal timeout buffer, no longer exported
|
|
39
|
+
- `HttpResponse`, `StreamingHttpResponse`, `ResponseTypes`, `BaseHttpResponseData`, and `GotScrapingHttpClient` (from `@crawlee/core`) — the HTTP client surface moved to `@crawlee/http-client` / `@crawlee/got-scraping-client` (see [HTTP client packages and `BaseHttpClient` reshaped](./http-clients.md#http-client-packages-and-basehttpclient-reshaped))
|
|
40
|
+
- `StreamHandlerContext` type (from `@crawlee/http`); `FileDownloadOptions` stays but only adds `ignoreTlsErrors` on top of `BasicCrawlerOptions` — see [`FileDownload` now extends `BasicCrawler`](./upgrading-v4.md#filedownload-now-extends-basiccrawler-and-takes-a-slimmer-filedownloadoptions)
|
|
41
|
+
- `PlainResponse` type (from `@crawlee/http`) — it wrapped the `got-scraping` response and is gone along with the rest of the old HTTP response surface (see [`CrawlingContext.response` is now of type `Response`](./upgrading-v4.md#crawlingcontextresponse-is-now-of-type-response))
|
|
42
|
+
- `checkStorageAccess`, `withCheckedStorageAccess` and the `RequestHandlerResult` type — superseded by the storage transaction mechanism; use `withDirectStorageAccess()` and `StorageTransactionView` (see [Storage writes in request handlers are transactional](./upgrading-v4.md#storage-writes-in-request-handlers-are-transactional))
|
|
43
|
+
- `CreateContextOptions` type (from `@crawlee/basic`) — a leftover of the pre-`ContextPipeline` context-creation design, unused by the library itself; context construction is now driven by `ContextPipeline`
|
|
44
|
+
- `ResponseLike` interface (from `@crawlee/core`) — a vestige of the pre-`fetch` HTTP implementation; `getCookiesFromResponse()`, which took it in v3, now takes a native `Response`
|
|
45
|
+
- The standalone `enqueueLinks()` function (from `@crawlee/core`) — use `context.enqueueLinks()` inside a request handler, or `context.addRequests()` / `crawler.addRequests()` for URLs you already have
|
|
46
|
+
- `UrlPatternObject` (from `@crawlee/core`) — the *compiled* form of a URL pattern, produced internally by the `enqueueLinks()` machinery. Use `UrlPatternInput` (new in v4) / `GlobInput` / `RegExpInput` for the patterns you pass in, and let the return type of the pattern helpers be inferred
|
|
47
|
+
- `createCpuLoadSignal()`, `createEventLoopLoadSignal()`, `createClientLoadSignal()` and the `ClientLoadSignal` / `ClientLoadSignalOptions` / `ClientSnapshot` types (from `@crawlee/core`) — construct `CpuLoadSignal`, `EventLoopLoadSignal` or `StorageBackendLoadSignal` instead (see [Load-signal options restructured](./autoscaling.md#load-signal-options-restructured))
|
|
48
|
+
- `StorageClient.setStatusMessage()` — status messages are broadcast as an `EventType.STATUS_MESSAGE` event (see [`StorageBackend` interface simplified](./storage-backends.md#storagebackend-interface-simplified))
|
|
49
|
+
- `chunk()`, `weightedAvg()`, `snakeCaseToCamelCase()`, `snapshotPageWithIframes()`, `entries()` and `keys()` (from `@crawlee/utils`) — see [Removed and relocated `@crawlee/utils` exports](./utils-and-types.md#removed-and-relocated-crawleeutils-exports)
|
|
50
|
+
- `PERSIST_STATE_KEY` (from `@crawlee/core`) — to change where a session pool persists its state, pass `persistStateKey` to `SessionPool`
|
|
51
|
+
- `MAX_POOL_SIZE` constant (from `@crawlee/core`) — was the internal default for `SessionPoolOptions.maxPoolSize` (1000); inline the literal if you were reading it
|
|
52
|
+
- `WithRequired` type (from `@crawlee/core`) — a bare TypeScript utility that was never crawlee vocabulary; `LoadedRequest` no longer goes through it, so declare your own if you were using it
|
|
53
|
+
- `ErrorSnapshotter` and its `SnapshotResult` return type (from `@crawlee/core`) — an implementation detail of `ErrorTracker`. Error snapshotting is opt-in through `new Statistics({ saveErrorSnapshots: true })` (or `new ErrorTracker({ saveErrorSnapshots: true })`)
|
|
54
|
+
- `ErrorTracker.errorSnapshotter` and `ErrorTracker.captureSnapshot()` — both private now. Snapshotting is driven from `addAsync()` on the first occurrence of each distinct error; the captured URLs surface as `firstErrorScreenshotUrl` / `firstErrorHtmlUrl` on the corresponding node of `errorTracker.result`, as before
|
|
55
|
+
- `MinimumSpeedStream` and `ByteCounterStream` (from `@crawlee/http`) — these `Transform` factories existed only to be piped inside `FileDownloadOptions.streamHandler`, which v4 removed. Compose your own `Transform` around `context.response.body` in the `requestHandler` instead; see the [file download with streams example](https://crawlee.dev/js/docs/examples/file-download-stream)
|
|
56
|
+
- `HttpHook`, `FileDownloadHook`, `CheerioHook`, `JSDOMHook` and `LinkeDOMHook` types — see [Removed navigation hook type aliases](./internals.md#removed-navigation-hook-type-aliases)
|
|
57
|
+
- The `puppeteerClickElements` namespace (from `@crawlee/puppeteer`) — `clickElements`, `clickElementsAndInterceptNavigationRequests` and `isTargetRelevant` were internal helpers. Use `puppeteerUtils.enqueueLinksByClickingElements()`, or `context.enqueueLinksByClickingElements()` inside a request handler; the `EnqueueLinksByClickingElementsOptions` type is still exported directly from `@crawlee/puppeteer`
|
|
58
|
+
- The `puppeteerRequestInterception` namespace (from `@crawlee/puppeteer`) — it only duplicated `puppeteerUtils.addInterceptRequestHandler` / `puppeteerUtils.removeInterceptRequestHandler`, which are unchanged. The `InterceptHandler` type is still exported directly from `@crawlee/puppeteer`
|
|
59
|
+
- The top-level type exports `BlockRequestsOptions`, `InjectFileOptions`, `InfiniteScrollOptions`, `SaveSnapshotOptions`, `CompiledScriptParams` and `CompiledScriptFunction` (from `@crawlee/puppeteer`) — the types themselves are unchanged and remain reachable through the namespace, e.g. `import { puppeteerUtils } from 'crawlee'; let options: puppeteerUtils.SaveSnapshotOptions;`. This matches `@crawlee/playwright`, which never exported them at the top level. `PuppeteerDirectNavigationOptions` is unaffected
|
|
60
|
+
|
|
61
|
+
### The protected `BasicCrawler.crawlingContexts` map is removed
|
|
62
|
+
|
|
63
|
+
The property was not used by the library itself and re-implementing the functionality in user code is fairly straightforward.
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: request-loaders
|
|
3
|
+
title: 'Upgrading to v4: request loaders and managers'
|
|
4
|
+
sidebar_label: Request loaders and managers
|
|
5
|
+
sidebar_position: 6
|
|
6
|
+
slug: /upgrading/upgrading-to-v4/request-loaders
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
Applies when you use `RequestList` or `SitemapRequestList`, pass `requestList` / `requestQueue` to a crawler, or implement the request loader and manager interfaces yourself. This page is part of the [Upgrading to v4](./upgrading-v4.md) guide.
|
|
10
|
+
|
|
11
|
+
## Request loaders and managers
|
|
12
|
+
|
|
13
|
+
The request loader/manager interfaces have been reworked. See the new [Request loaders](https://crawlee.dev/js/docs/next/guides/request-loaders) guide for the full picture.
|
|
14
|
+
|
|
15
|
+
### `RequestQueue.addRequestsBatched` no longer retries rejected requests
|
|
16
|
+
|
|
17
|
+
Requests that the storage backend reports as unprocessed are now warned about and skipped after the first attempt, instead of being retried a bounded number of times. What a backend reports as unprocessed is a semantic rejection (typically malformed request data) that re-sending cannot fix — retrying transient failures is the storage backend's own responsibility.
|
|
18
|
+
|
|
19
|
+
### `maxNewRequests` no longer implies `waitForAllRequestsToBeAdded`
|
|
20
|
+
|
|
21
|
+
`RequestQueue.addRequestsBatched` used to wait for every batch (and drain the whole input) whenever `maxNewRequests` was set, so it could report `requestsOverLimit`. Draining could block forever on an async producer, so the input is now left unconsumed past the budget, and `requestsOverLimit` is only populated when you also pass `waitForAllRequestsToBeAdded: true` (otherwise it is `undefined`). `crawler.addRequests()` still reports skipped requests as before.
|
|
22
|
+
|
|
23
|
+
### `IRequestList` renamed to `IRequestLoader`
|
|
24
|
+
|
|
25
|
+
The `IRequestList` interface has been renamed to `IRequestLoader` and is now the read-only base interface implemented by `RequestList` and `SitemapRequestLoader`. The writable `IRequestManager` interface now **extends** `IRequestLoader` with the request-adding and reclaiming surface (`addRequest`, `addRequestsBatched`, `reclaimRequest`, optional `purge`). There is no `IRequestList` alias — update your imports and type references to `IRequestLoader` (or `IRequestManager` if you need the write surface).
|
|
26
|
+
|
|
27
|
+
### Loader interface surface changes
|
|
28
|
+
|
|
29
|
+
The harmonized loader interface differs from the old `IRequestList` in a few ways:
|
|
30
|
+
|
|
31
|
+
| Before (v3) | After (v4) |
|
|
32
|
+
|---|---|
|
|
33
|
+
| `length(): number` | `getTotalCount(): Promise<number>` (renamed and now async) |
|
|
34
|
+
| _(n/a)_ | `getPendingCount(): Promise<number>` (new) |
|
|
35
|
+
| `handledCount(): number` | `getHandledCount(): Promise<number>` (renamed and now async) |
|
|
36
|
+
| `markRequestHandled(request)` | `markRequestAsHandled(request)` (renamed) |
|
|
37
|
+
| `isEmpty(): Promise<boolean>` and `isFinished(): Promise<boolean>` | `checkReadiness(): Promise<RequestSourceStatus>` ([details](#isempty--isfinished-replaced-by-checkreadiness)) |
|
|
38
|
+
| `reclaimRequest()` on the interface | Removed from the read-only loaders entirely; reclaiming is a write operation that lives only on `IRequestManager` (e.g. `RequestQueue`, `RequestManagerTandem`) |
|
|
39
|
+
| `inProgress: Set<string>` on the interface | Removed from the interface |
|
|
40
|
+
| `persistState(): Promise<void>` (required) | Removed from the interface; loaders that have state persist it themselves on the `persistState` event, and `RequestList`/`SitemapRequestLoader` still expose the method as a class member |
|
|
41
|
+
| _(n/a)_ | `toTandem?(requestManager?)` (new) |
|
|
42
|
+
|
|
43
|
+
`RequestList.length()` and `RequestList.handledCount()` (and their `SitemapRequestLoader` counterparts) were renamed to `getTotalCount()` and `getHandledCount()` and are now `async` — `await` them. The same goes for `RequestQueue`: its `getTotalCount()` and `getPendingCount()` are now `async`, and `handledCount()` was renamed to `getHandledCount()`.
|
|
44
|
+
|
|
45
|
+
`markRequestHandled()` was renamed to `markRequestAsHandled()` across the loader and manager interfaces (`RequestList`, `SitemapRequestLoader`, `RequestQueue`, `RequestManagerTandem`) to match the storage backend method of the same name. Rename any calls accordingly.
|
|
46
|
+
|
|
47
|
+
**Before:**
|
|
48
|
+
```typescript
|
|
49
|
+
const total = requestList.length();
|
|
50
|
+
const handled = requestList.handledCount();
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
**After:**
|
|
54
|
+
```typescript
|
|
55
|
+
const total = await requestList.getTotalCount();
|
|
56
|
+
const handled = await requestList.getHandledCount();
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### `IRequestManager` gained `recordPacingSignal()`
|
|
60
|
+
|
|
61
|
+
v3 could not tell a request source that a domain wants to be left alone: a 429 only retired the session, and a robots.txt `Crawl-delay` was not enforced at all. One member now carries all of it:
|
|
62
|
+
|
|
63
|
+
```typescript
|
|
64
|
+
recordPacingSignal(signal: PacingSignal): boolean;
|
|
65
|
+
|
|
66
|
+
type PacingSignal =
|
|
67
|
+
// the source turned a request away because we were going too fast
|
|
68
|
+
| { reason: 'rateLimited'; url: string; waitMs?: number; scope?: PacingScope }
|
|
69
|
+
// it declared a standing floor on how often it may be requested
|
|
70
|
+
| { reason: 'minInterval'; url: string; intervalMs: number; scope: PacingScope }
|
|
71
|
+
// the operator asked for a floor under every domain, `sameDomainDelaySecs` being one
|
|
72
|
+
| { reason: 'minIntervalEverywhere'; intervalMs: number; scope: PacingScope };
|
|
73
|
+
|
|
74
|
+
// suggests the two Crawlee itself uses, accepts any string
|
|
75
|
+
type PacingScope = LiteralUnion<'hostname' | 'registrableDomain', string>;
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
The crawler reports a 429 (with `Retry-After` if the response carried one), a robots.txt `Crawl-delay`, and its own `sameDomainDelaySecs`. Nothing in the payload names the mechanism, so a manager never learns where a signal came from, and `true` means it took responsibility — which is how the crawler knows to treat a rate limit as a paced retry rather than a blocked response. Delays are in milliseconds.
|
|
79
|
+
|
|
80
|
+
If you implement the interface:
|
|
81
|
+
|
|
82
|
+
- Return `false` when you do not pace, and forward the value when you wrap a manager that might. The method is required so that reporting is never a question of support, and a pacer nested in a composition still has to hear about it.
|
|
83
|
+
- Apply a signal at a **wider** `scope` than you were given if you must — a per-host floor still holds when the whole site is paced by it — never a narrower one, and throw on a scope you cannot honour instead of under-applying it. `ThrottlingRequestManager` groups by `throttleBy`, so it widens `'hostname'` signals and throws on anything wider or on a vocabulary it does not speak.
|
|
84
|
+
- `minIntervalEverywhere` covers every domain you dispatch to, which is why it is the variant with no `url`. Take it only if you pace all of them; throw if you pace some.
|
|
85
|
+
|
|
86
|
+
### `isEmpty()` / `isFinished()` replaced by `checkReadiness()`
|
|
87
|
+
|
|
88
|
+
The two predicates v3 put on `IRequestList` and `IRequestManager` (and on `RequestList`, `RequestQueue` and `RequestProvider`) are replaced by a single `checkReadiness()` call, on `IRequestLoader`, `IRequestManager` and every implementation:
|
|
89
|
+
|
|
90
|
+
```typescript
|
|
91
|
+
type RequestSourceStatus =
|
|
92
|
+
| { status: 'ready' } // a fetch is expected to hand something over (v3: `!isEmpty()`)
|
|
93
|
+
| { status: 'waiting'; readyAt?: number } // nothing now, not done (v3: `isEmpty() && !isFinished()`)
|
|
94
|
+
| { status: 'stalled'; reason: string } // holding requests it cannot make progress on
|
|
95
|
+
| { status: 'finished' }; // nothing left at all (v3: `isFinished()`)
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
```diff
|
|
99
|
+
-if (!(await manager.isEmpty())) { /* fetch */ }
|
|
100
|
+
+if ((await manager.checkReadiness()).status === 'ready') { /* fetch */ }
|
|
101
|
+
|
|
102
|
+
-if (await manager.isFinished()) { /* stop */ }
|
|
103
|
+
+if ((await manager.checkReadiness()).status === 'finished') { /* stop */ }
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
One probe instead of two, which a task loop runs several times a second, plus two answers the booleans could not express: `waiting` can name when it expects work again (`readyAt`) instead of leaving the caller to poll, and `stalled` reports requests a source cannot make progress on, which the crawler turns into a `PersistentRateLimitError`.
|
|
107
|
+
|
|
108
|
+
If you implemented either interface, return `ready` without evaluating anything further — it is the most common answer and the only one a caller can act on immediately. Reading from two sources, the precedence is `ready` > `waiting` > `stalled` > `finished`, and a combined `waiting` carries the earlier `readyAt`.
|
|
109
|
+
|
|
110
|
+
**Storage backends keep the two booleans** — see [`StorageBackend` interface simplified](./storage-backends.md#storagebackend-interface-simplified).
|
|
111
|
+
|
|
112
|
+
### Combining a list and a queue: `toTandem()`
|
|
113
|
+
|
|
114
|
+
`RequestList` and `SitemapRequestLoader` now expose a `toTandem()` helper that pairs the read-only loader with a writable request manager (the default `RequestQueue` if none is passed), producing a `RequestManagerTandem` you can hand to a crawler via the `requestManager` option:
|
|
115
|
+
|
|
116
|
+
```typescript
|
|
117
|
+
import { CheerioCrawler, RequestList } from 'crawlee';
|
|
118
|
+
|
|
119
|
+
const requestList = await RequestList.open('my-list', ['https://example.com']);
|
|
120
|
+
|
|
121
|
+
const crawler = new CheerioCrawler({
|
|
122
|
+
requestManager: await requestList.toTandem(),
|
|
123
|
+
requestHandler: async ({ enqueueLinks }) => {
|
|
124
|
+
await enqueueLinks();
|
|
125
|
+
},
|
|
126
|
+
});
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### `SitemapRequestList` renamed to `SitemapRequestLoader`
|
|
130
|
+
|
|
131
|
+
The `SitemapRequestList` class (and its `SitemapRequestListOptions` type) have been renamed to `SitemapRequestLoader` and `SitemapRequestLoaderOptions` to match the loader terminology. Update your imports and type references accordingly:
|
|
132
|
+
|
|
133
|
+
```typescript
|
|
134
|
+
// Before
|
|
135
|
+
import { SitemapRequestList } from 'crawlee';
|
|
136
|
+
const loader = await SitemapRequestList.open({ sitemapUrls: ['https://example.com/sitemap.xml'] });
|
|
137
|
+
|
|
138
|
+
// After
|
|
139
|
+
import { SitemapRequestLoader } from 'crawlee';
|
|
140
|
+
const loader = await SitemapRequestLoader.open({ sitemapUrls: ['https://example.com/sitemap.xml'] });
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
The default `KeyValueStore` key used to persist the loader's state was also renamed from `SITEMAP_REQUEST_LIST_STATE` to `CRAWLEE_SITEMAP_REQUEST_LOADER_STATE`. State persisted under the old key by a v3 run will **not** be picked up after upgrading; resuming a v3 crawl on v4 is not supported, so finish or discard in-flight sitemap crawls before upgrading.
|
|
144
|
+
|
|
145
|
+
### Crawler `requestList` / `requestQueue` options deprecated in favor of `requestManager`
|
|
146
|
+
|
|
147
|
+
The crawler now reads its requests from a single `requestManager` (any `IRequestManager`, including a `RequestQueue`). The `requestList` and `requestQueue` constructor options are **deprecated** but still accepted as sugar:
|
|
148
|
+
|
|
149
|
+
- `requestQueue` alone → used directly as the manager.
|
|
150
|
+
- `requestList` + `requestQueue` → combined into a `RequestManagerTandem` automatically.
|
|
151
|
+
- `requestList` alone → combined with a lazily-opened default queue into a tandem.
|
|
152
|
+
|
|
153
|
+
```typescript
|
|
154
|
+
// Before
|
|
155
|
+
const crawler = new CheerioCrawler({ requestList, requestQueue });
|
|
156
|
+
|
|
157
|
+
// After
|
|
158
|
+
const crawler = new CheerioCrawler({ requestManager: new RequestManagerTandem(requestList, requestQueue) });
|
|
159
|
+
// or, equivalently
|
|
160
|
+
const crawler = new CheerioCrawler({ requestManager: await requestList.toTandem(requestQueue) });
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
A lone `requestList` now runs through a tandem over an auto-opened queue (rather than a read-only adapter). This means retries and `maxRequestsPerCrawl` accounting for that path now follow queue semantics.
|
|
164
|
+
|
|
165
|
+
### HTTP 429 can now back off per domain instead of retiring the session
|
|
166
|
+
|
|
167
|
+
`blockedStatusCodes` still defaults to `[401, 403, 429]`, so out of the box a 429 retires the session and retries immediately, as in v3. New is a one-time warning per domain when a 429 arrives and no request manager paces that domain; it points at `sameDomainDelaySecs` or a `ThrottlingRequestManager` and changes nothing else. New in v4 is the opt-in `ThrottlingRequestManager`, which handles rate limits at the scheduling layer instead:
|
|
168
|
+
|
|
169
|
+
```typescript
|
|
170
|
+
const crawler = new CheerioCrawler({
|
|
171
|
+
requestManager: new ThrottlingRequestManager({
|
|
172
|
+
domains: ['api.example.com'],
|
|
173
|
+
}),
|
|
174
|
+
requestHandler,
|
|
175
|
+
});
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
For the domains you list, a 429 is treated as a rate limit before `blockedStatusCodes` is consulted at all — it honours `Retry-After` (or backs off exponentially), holds only that domain's requests back, and leaves both the session and the request's retry budget untouched. Removing 429 from `blockedStatusCodes` therefore only affects domains the manager does not cover; you do not need to touch it to adopt throttling. Because those retries are free, a domain that never stops rate-limiting would keep the crawl alive indefinitely — so one that goes `maxDomainStallSecs` (15 minutes by default) without letting a single request through shuts the crawl down with a `PersistentRateLimitError`, leaving its requests queued for a later run — unless `keepAlive` is set, where outliving such a domain is the point.
|
|
179
|
+
|
|
180
|
+
It is also what enforces robots.txt `Crawl-delay` directives — with `respectRobotsTxtFile` enabled and no throttling manager covering the domain, the directive is ignored and the crawler warns about it. See the [request loaders guide](https://crawlee.dev/js/docs/next/guides/request-loaders#per-domain-throttling).
|
|
181
|
+
|
|
182
|
+
### `BasicCrawler.requestList` and `BasicCrawler.requestQueue` fields removed
|
|
183
|
+
|
|
184
|
+
The public `requestList` and `requestQueue` instance fields are gone. The crawler exposes a single read-only `protected requestManager` getter instead. Access the active manager via the new async `getRequestManager()` method.
|
|
185
|
+
|
|
186
|
+
### `BasicCrawler.requestManager` is read-only
|
|
187
|
+
|
|
188
|
+
`requestManager` is now a getter over a native `#requestManager` field, so a subclass can read it but can no longer assign to it. The crawler owns the manager's lifecycle — it resolves the `requestManager` / `requestList` / `requestQueue` options, opens a default queue when none was given, and wraps the result in a `ThrottlingRequestManager` when `sameDomainDelaySecs` is set — and assigning over it from a subclass skipped those steps.
|
|
189
|
+
|
|
190
|
+
Inject your own manager through the constructor option instead, and read the resolved one with `getRequestManager()`:
|
|
191
|
+
|
|
192
|
+
**Before:**
|
|
193
|
+
```typescript
|
|
194
|
+
class MyCrawler extends BasicCrawler {
|
|
195
|
+
protected override async _init() {
|
|
196
|
+
await super._init();
|
|
197
|
+
this.requestManager = await MyRequestQueue.open();
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
**After:**
|
|
203
|
+
```typescript
|
|
204
|
+
const crawler = new MyCrawler({ requestManager: await MyRequestQueue.open() });
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
Being a native `#` field, it is also no longer visible to `Object.keys()`, object spread or `JSON.stringify()`.
|
|
208
|
+
|
|
209
|
+
### `getRequestQueue()` deprecated in favor of `getRequestManager()`
|
|
210
|
+
|
|
211
|
+
`BasicCrawler.getRequestQueue()` is deprecated. It still works as an alias, but now returns an `IRequestManager` that is no longer guaranteed to be a `RequestQueue` (it may be a `RequestManagerTandem`). Use `getRequestManager()` instead.
|
|
212
|
+
|
|
213
|
+
**Before:**
|
|
214
|
+
```typescript
|
|
215
|
+
const queue = await crawler.getRequestQueue();
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
**After:**
|
|
219
|
+
```typescript
|
|
220
|
+
const manager = await crawler.getRequestManager();
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
### Standalone `enqueueLinks()` removed; `enqueueLinksByClickingElements` takes `requestManager`
|
|
224
|
+
|
|
225
|
+
The standalone `enqueueLinks()` function is gone. Call `context.enqueueLinks()` inside a request handler, or add known URLs with `context.addRequests()` / `crawler.addRequests()`.
|
|
226
|
+
|
|
227
|
+
The click-elements enqueue helpers (`enqueueLinksByClickingElements` in `@crawlee/puppeteer` and `@crawlee/playwright`) now take a `requestManager` option instead of `requestQueue`:
|
|
228
|
+
|
|
229
|
+
**Before:**
|
|
230
|
+
```typescript
|
|
231
|
+
await enqueueLinksByClickingElements({ page, selector, requestQueue });
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
**After:**
|
|
235
|
+
```typescript
|
|
236
|
+
await enqueueLinksByClickingElements({ page, selector, requestManager });
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
### Removed `UrlList` type alias
|
|
240
|
+
|
|
241
|
+
`UrlList` is gone; the signatures that used it now spell the type out inline (`(string | null)[]`). No behavioral change — replace the alias with the expansion if you referenced it.
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: sessions-and-proxies
|
|
3
|
+
title: 'Upgrading to v4: sessions and proxies'
|
|
4
|
+
sidebar_label: Sessions and proxies
|
|
5
|
+
sidebar_position: 2
|
|
6
|
+
slug: /upgrading/upgrading-to-v4/sessions-and-proxies
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
Applies when you construct `SessionPool` or `Session` instances directly, implement your own pool, or configure proxies beyond a static URL list. This page is part of the [Upgrading to v4](./upgrading-v4.md) guide.
|
|
10
|
+
|
|
11
|
+
## Custom `SessionPool` implementations via the `ISessionPool` interface
|
|
12
|
+
|
|
13
|
+
Crawlers now accept any object implementing the new `ISessionPool` interface as their `sessionPool` option, not just instances of the built-in `SessionPool`. The contract is intentionally tiny — a single method, `getSession(sessionId?)`, that hands out a session for a request. Lifecycle (reset, teardown) is the responsibility of whoever owns the pool: a custom pool you construct yourself is never owned by the crawler, so the crawler never tears it down. This makes it straightforward to plug in a remote, shared, or otherwise customized session-management strategy without subclassing `SessionPool` or copying its internals.
|
|
14
|
+
|
|
15
|
+
`ISessionPool` and `ISession` live in `@crawlee/types`; they are not re-exported from `@crawlee/core` (see [`@crawlee/types` symbols are no longer re-exported](./utils-and-types.md#crawleetypes-symbols-are-no-longer-re-exported)).
|
|
16
|
+
|
|
17
|
+
```typescript
|
|
18
|
+
import { BasicCrawler, Session } from '@crawlee/basic';
|
|
19
|
+
import type { ISession, ISessionPool } from '@crawlee/types';
|
|
20
|
+
|
|
21
|
+
class MySessionPool implements ISessionPool {
|
|
22
|
+
private readonly sessions = new Map<string, ISession>();
|
|
23
|
+
|
|
24
|
+
async getSession(sessionId?: string): Promise<ISession | undefined> {
|
|
25
|
+
if (sessionId) {
|
|
26
|
+
const existing = this.sessions.get(sessionId);
|
|
27
|
+
return existing?.isUsable() ? existing : undefined;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const usable = [...this.sessions.values()].find((session) => session.isUsable());
|
|
31
|
+
if (usable) return usable;
|
|
32
|
+
|
|
33
|
+
const fresh = new Session();
|
|
34
|
+
this.sessions.set(fresh.id, fresh);
|
|
35
|
+
return fresh;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const crawler = new BasicCrawler({
|
|
40
|
+
sessionPool: new MySessionPool(),
|
|
41
|
+
requestHandler: async ({ session }) => {
|
|
42
|
+
// `session` is whatever your pool returned, typed as ISession
|
|
43
|
+
},
|
|
44
|
+
});
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The crawler depends only on the `ISession` interface — `id`, `cookieJar`, `proxyInfo`, `fingerprint`, and the `isUsable()` / `isBlocked()` / `markGood()` / `markBad()` / `retire()` methods — so a custom pool may hand out its own session implementation instead of instances of the built-in `Session` class. `Session` implements `ISession`, so returning `Session` instances (as above) is the shortest path; `crawlingContext.session` is typed as `ISession` either way.
|
|
48
|
+
|
|
49
|
+
Returning `undefined` means the pool has no usable session for the request. The crawler turns that into a `MissingSessionError` and retries the request like any other failure.
|
|
50
|
+
|
|
51
|
+
The `crawler.sessionPool` property is now **read-only** (a getter). It was previously a writable field, so any code that reassigned it after construction (`crawler.sessionPool = myPool`) no longer works — pass your pool via the `sessionPool` constructor option instead.
|
|
52
|
+
|
|
53
|
+
## `createSessionFunction` signature has changed
|
|
54
|
+
|
|
55
|
+
The pool-wide `sessionOptions` are now merged with per-call overrides before `createSessionFunction` is invoked, and the leading `sessionPool` argument is gone — it was only useful to pass to `new Session({ sessionPool })`, and `Session` no longer keeps a back-reference to the pool. The new signature is `(options?: { sessionOptions?: SessionOptions }) => Session | Promise<Session>`.
|
|
56
|
+
|
|
57
|
+
**Before:**
|
|
58
|
+
```typescript
|
|
59
|
+
new SessionPool({
|
|
60
|
+
sessionOptions: { maxUsageCount: 5 },
|
|
61
|
+
createSessionFunction: async (pool, opts) =>
|
|
62
|
+
new Session({
|
|
63
|
+
...pool.sessionOptions, // had to be spread manually for pool defaults to apply
|
|
64
|
+
...opts?.sessionOptions,
|
|
65
|
+
sessionPool: pool,
|
|
66
|
+
}),
|
|
67
|
+
});
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
**After:**
|
|
71
|
+
```typescript
|
|
72
|
+
new SessionPool({
|
|
73
|
+
sessionOptions: { maxUsageCount: 5 },
|
|
74
|
+
createSessionFunction: async (opts) =>
|
|
75
|
+
new Session({
|
|
76
|
+
...opts?.sessionOptions, // already merged with pool-wide defaults
|
|
77
|
+
}),
|
|
78
|
+
});
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## `Session` no longer requires a `sessionPool` reference
|
|
82
|
+
|
|
83
|
+
`Session` no longer holds a back-reference to its `SessionPool` and no longer emits a `sessionRetired` event when retired. The `sessionPool` constructor option is gone, `SessionPool` is no longer an `EventEmitter`, and the `EVENT_SESSION_RETIRED` constant is no longer exported. Custom `createSessionFunction` implementations that constructed `Session` instances manually should drop the `sessionPool` argument.
|
|
84
|
+
|
|
85
|
+
**Before:**
|
|
86
|
+
```typescript
|
|
87
|
+
new SessionPool({
|
|
88
|
+
createSessionFunction: async (pool, opts) =>
|
|
89
|
+
new Session({ ...opts?.sessionOptions, sessionPool: pool }),
|
|
90
|
+
});
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
**After:**
|
|
94
|
+
```typescript
|
|
95
|
+
new SessionPool({
|
|
96
|
+
createSessionFunction: async (opts) =>
|
|
97
|
+
new Session({ ...opts?.sessionOptions }),
|
|
98
|
+
});
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
If you previously subscribed to `sessionRetired` on the pool to clean up resources tied to a session, perform the cleanup at the end of your request handler (or via a context-pipeline cleanup hook) by checking `session.isUsable()` instead. `Session.retire()` is now a terminal state — once retired, `isUsable()` returns `false` permanently and cannot be undone by a subsequent `markGood()`.
|
|
102
|
+
|
|
103
|
+
## `tieredProxyUrls` is removed from `ProxyConfiguration`
|
|
104
|
+
|
|
105
|
+
The `tieredProxyUrls` option has been removed, together with the `proxyTier` field on `ProxyInfo` and the `proxyTier` plumbing in `BrowserPool`. In v4 the `Session` is the main rotation unit — a session already carries its own proxy, cookies and error score, so the pool rotates the whole fingerprint when a session gets retired on a block.
|
|
106
|
+
|
|
107
|
+
If you used tiers to escalate from a cheap proxy pool to a pricier one on blocks, you can achieve the same behavior by pre-populating a `SessionPool` with named sessions — one per proxy tier — and flipping `request.sessionId` in an `errorHandler` to reassign the retry to the next tier. Do not pass `proxyConfiguration` to the crawler: whenever a `sessionPool` is supplied, the crawler ignores `proxyConfiguration` with a warning and every pooled session keeps the `proxyInfo` it was created with. Configure proxies on the pool instead, through `addSession({ proxyInfo })` or a custom `createSessionFunction`.
|
|
108
|
+
|
|
109
|
+
```typescript
|
|
110
|
+
import { BasicCrawler, SessionPool } from '@crawlee/basic';
|
|
111
|
+
|
|
112
|
+
const proxyInfoFromUrl = (proxyUrl: string) => {
|
|
113
|
+
const { username, password, hostname, port } = new URL(proxyUrl);
|
|
114
|
+
return {
|
|
115
|
+
url: proxyUrl,
|
|
116
|
+
username: decodeURIComponent(username),
|
|
117
|
+
password: decodeURIComponent(password),
|
|
118
|
+
hostname,
|
|
119
|
+
port,
|
|
120
|
+
};
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
const sessionPool = new SessionPool();
|
|
124
|
+
await sessionPool.addSession({ id: 'basic', proxyInfo: proxyInfoFromUrl('http://cheap-proxy.com') });
|
|
125
|
+
await sessionPool.addSession({ id: 'premium', proxyInfo: proxyInfoFromUrl('http://expensive-proxy.com') });
|
|
126
|
+
|
|
127
|
+
const crawler = new BasicCrawler({
|
|
128
|
+
sessionPool,
|
|
129
|
+
requestHandler: async ({ request, sendRequest }) => {
|
|
130
|
+
const response = await sendRequest({ url: request.url });
|
|
131
|
+
// `sendRequest` resolves on any status, so throw on a block to reach `errorHandler`
|
|
132
|
+
if ([401, 403, 429].includes(response.status)) {
|
|
133
|
+
throw new Error(`Blocked with status ${response.status}`);
|
|
134
|
+
}
|
|
135
|
+
},
|
|
136
|
+
errorHandler: async ({ request }) => {
|
|
137
|
+
request.sessionId = 'premium';
|
|
138
|
+
},
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
await crawler.run([{ url: 'https://example.com', sessionId: 'basic' }]);
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
More complex routing (more tiers, weighted draws, sticky assignment, cooldowns) can be expressed with additional named sessions and custom `errorHandler` logic.
|
|
145
|
+
|
|
146
|
+
### `ProxyConfiguration.newUrl` / `newProxyInfo` signatures changed
|
|
147
|
+
|
|
148
|
+
Because proxy tiers are gone, the leading `sessionId` positional argument was dropped from `ProxyConfiguration.newUrl()` and `ProxyConfiguration.newProxyInfo()`. `newUrl()` now takes no arguments, and `newProxyInfo()` takes only an optional, previously created `ProxyInfo` (e.g. one restored with a persisted session) instead of `(sessionId?, options?)`. Custom `IProxyConfiguration` implementations should return that `ProxyInfo` (refreshed if it depends on the environment) rather than a new one, otherwise the crawler replaces the session's proxy. The `ProxyConfigurationFunction` callback (the `newUrlFunction` option) was likewise simplified — it no longer receives any arguments, neither a `sessionId` nor a `{ request }` object. The proxy is resolved once per session, so to route specific requests through specific proxies, pin them to named sessions (see [Pinning a request to a specific session](https://crawlee.dev/js/docs/next/guides/session-management#pinning-a-request-to-a-specific-session)). The `TieredProxy` interface has been removed.
|
|
149
|
+
|
|
150
|
+
**Before:**
|
|
151
|
+
```typescript
|
|
152
|
+
const proxyConfiguration = new ProxyConfiguration({
|
|
153
|
+
newUrlFunction: (sessionId, options) => pickProxyFor(sessionId),
|
|
154
|
+
});
|
|
155
|
+
const url = await proxyConfiguration.newUrl(sessionId);
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
**After:**
|
|
159
|
+
```typescript
|
|
160
|
+
const proxyConfiguration = new ProxyConfiguration({
|
|
161
|
+
newUrlFunction: () => pickProxy(),
|
|
162
|
+
});
|
|
163
|
+
const url = await proxyConfiguration.newUrl();
|
|
164
|
+
```
|