@crawlee/cli 4.0.0-beta.321 → 4.0.0-beta.323

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.
@@ -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 `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
+ ```
@@ -0,0 +1,56 @@
1
+ ---
2
+ id: statistics
3
+ title: 'Upgrading to v4: crawler statistics'
4
+ sidebar_label: Crawler statistics
5
+ sidebar_position: 4
6
+ slug: /upgrading/upgrading-to-v4/statistics
7
+ ---
8
+
9
+ Applies when you passed `statisticsOptions` to a crawler, subclassed `Statistics`, or passed type arguments to `BrowserCrawler`/`BrowserCrawlerOptions`. This page is part of the [Upgrading to v4](./upgrading-v4.md) guide.
10
+
11
+ ## `statisticsOptions` is replaced by a `statistics` instance
12
+
13
+ The `statisticsOptions` option has been removed from the crawler constructor. Instead of passing options for the crawler to build its `Statistics` from, construct a `Statistics` instance yourself and pass it via the new `statistics` option — the same inject-or-default idiom as `sessionPool` and `browserPool`.
14
+
15
+ ```typescript
16
+ import { BasicCrawler, Statistics } from '@crawlee/basic';
17
+
18
+ const crawler = new BasicCrawler({
19
+ // The old parameter won't work anymore
20
+ // statisticsOptions: { saveErrorSnapshots: true },
21
+ statistics: new Statistics({ saveErrorSnapshots: true }),
22
+ });
23
+ ```
24
+
25
+ Omit the option and the crawler builds its own default, exactly as before. A supplied instance is treated as borrowed: the crawler records into it and drives its capture lifecycle for the run, but never `reset()`s it between `run()` calls — so a preconfigured instance keeps whatever state it was handed.
26
+
27
+ The option accepts the built-in `Statistics` or any object implementing the new `IStatistics` interface, so a fully custom statistics backend can be plugged in without subclassing. The crawler exposes it as `crawler.statistics` (renamed from `crawler.stats`) typed as `IStatistics`.
28
+
29
+ ## The request-recording methods are renamed
30
+
31
+ A crawler processes requests, not jobs, so the three methods for recording them dropped the borrowed vocabulary. Signatures are unchanged, so a custom implementation only needs renaming:
32
+
33
+ - `startJob()` -> `recordRequestStart()`
34
+ - `finishJob()` -> `recordRequestSuccess()`
35
+ - `failJob()` -> `recordRequestFailure()`
36
+
37
+ `IStatistics` also requires a fourth method that v3 did not have, `discardRequestRecord(id)`.
38
+
39
+ ## The `Statistics` persistence lifecycle is stricter
40
+
41
+ `persistState()` and `resetStore()` no longer take `PersistenceOptions` — persistence is enabled or disabled once, in the constructor. `resetStore()` throws while the instance is capturing, where the next `PERSIST_STATE` event would write the record straight back; call it before `startCapturing()` or after `stopCapturing()`. And `reset()` only resets the counters — it no longer stops an ongoing capture, which `stopCapturing()` does.
42
+
43
+ A persisted record is also validated on load now. One that does not match the expected shape is discarded whole, with a warning, and the statistics start from scratch — where v3 would copy the malformed values into the live state and let them corrupt every later increment. Custom fields are scoped the same way: when `stateExtension.deserialize` throws, only those fields restart and the built-in counters are kept.
44
+
45
+ ## Subclassing `Statistics` to track extra fields is replaced by the `stateExtension` option
46
+
47
+ `persistStateKey` and `_maybeLoadStatistics()` were `protected` and are now private (`toJSON()` stays public). Declare extra fields via the new `stateExtension` option instead — `{ defaultState, deserialize, serialize }`, the same trio `RecoverableState` takes, scoped to the custom fields. See the [Custom statistics fields](https://crawlee.dev/js/docs/next/guides/custom-statistics) guide.
48
+
49
+ The persisted record is now validated strictly, and keys that are neither built-in nor declared in `stateExtension` are dropped rather than written back. `calculate()` is still public and still an override point.
50
+
51
+ The custom field types reach `crawler.statistics.state` through a new trailing `StatisticStateExtension` type parameter on the crawler classes and their options. It defaults to `{}`, so existing type arguments keep working — except on `BrowserCrawler`, where it was inserted after `Routes`, ahead of the trailing `GoToOptions` parameter. Adjust any explicit type arguments you passed there.
52
+
53
+ `AdaptivePlaywrightCrawler` now uses this mechanism for its own extra fields, with two consequences:
54
+
55
+ - `httpOnlyRequestHandlerRuns`, `browserRequestHandlerRuns` and `renderingTypeMispredictions` were typed as optional and are now always present. Reading them no longer needs a `?? 0`.
56
+ - The `statistics` option accepts any `IStatistics<AdaptivePlaywrightCrawlerStatisticState>`. Build one by extending the exported `adaptivePlaywrightCrawlerStatisticState`.
@@ -0,0 +1,170 @@
1
+ ---
2
+ id: storage-backends
3
+ title: 'Upgrading to v4: storage backends'
4
+ sidebar_label: Storage backends
5
+ sidebar_position: 7
6
+ slug: /upgrading/upgrading-to-v4/storage-backends
7
+ ---
8
+
9
+ Applies when you implement your own storage backend, or reach below the `Dataset`, `KeyValueStore` and `RequestQueue` frontends. This page is part of the [Upgrading to v4](./upgrading-v4.md) guide.
10
+
11
+ ## `StorageBackend` interface simplified
12
+
13
+ The `StorageBackend` interface (from `@crawlee/types`, formerly named `StorageClient`) has been redesigned and simplified. A new storage backend now needs **4 classes** instead of the previous 7.
14
+
15
+ ### What changed
16
+
17
+ The three **collection client** interfaces have been removed:
18
+
19
+ - `DatasetCollectionClient`
20
+ - `KeyValueStoreCollectionClient`
21
+ - `RequestQueueCollectionClient`
22
+
23
+ Along with their associated types (`DatasetCollectionData`, `DatasetCollectionClientOptions`, and the `Dataset` interface from `@crawlee/types`).
24
+
25
+ The `StorageBackend` interface changed from synchronous sub-client getters to **async factory methods**:
26
+
27
+ | Before (v3) | After (v4) |
28
+ |---|---|
29
+ | `client.dataset(id)` | `backend.createDatasetBackend({ id?, name? })` |
30
+ | `client.datasets().getOrCreate(name)` | _(absorbed into `createDatasetBackend`)_ |
31
+ | `client.keyValueStore(id)` | `backend.createKeyValueStoreBackend({ id?, name? })` |
32
+ | `client.keyValueStores().getOrCreate(name)` | _(absorbed into `createKeyValueStoreBackend`)_ |
33
+ | `client.requestQueue(id, opts)` | `backend.createRequestQueueBackend({ id?, name? })` |
34
+ | `client.requestQueues().getOrCreate(name)` | _(absorbed into `createRequestQueueBackend`)_ |
35
+
36
+ The sub-backend interfaces (`DatasetBackend`, `KeyValueStoreBackend`, `RequestQueueBackend`, formerly `DatasetClient` / `KeyValueStoreClient` / `RequestQueueClient`) have been simplified:
37
+
38
+ | Before (v3) | After (v4) |
39
+ |---|---|
40
+ | `get()` | `getMetadata()` |
41
+ | `update()` | Removed |
42
+ | `delete()` | `drop()` |
43
+ | _(n/a)_ | `purge()` (new — clears data, keeps storage) |
44
+
45
+ **`DatasetBackend`:**
46
+
47
+ | Before (v3) | After (v4) |
48
+ |---|---|
49
+ | `pushItems(items: Data \| Data[] \| string \| string[])` | `pushData(items: Data[])` |
50
+ | `listItems(options?)` (dual iterable) | `getData(options?)` (returns a single `PaginatedList` page) |
51
+ | `listEntries(options?)` | Removed (handled by `Dataset` frontend) |
52
+ | `downloadItems()` | Removed |
53
+
54
+ **`KeyValueStoreBackend`:**
55
+
56
+ | Before (v3) | After (v4) |
57
+ |---|---|
58
+ | `getRecord(key, options?)` | `getValue(key)` |
59
+ | `setRecord(record, options?)` | `setValue(record)` |
60
+ | `deleteRecord(key)` | `deleteValue(key)` |
61
+ | `getRecordPublicUrl(key)` | `getPublicUrl(key)` |
62
+ | `listKeys(options?)` → `KeyValueStoreClientListData` | `listKeys(options?)` → `KeyValueStoreListKeysResult` (a single self-describing page) |
63
+ | `keys()`, `values()`, `entries()` | Removed (handled by `KeyValueStore` frontend) |
64
+
65
+ **`RequestQueueBackend`:**
66
+
67
+ The request queue backend's surface was reshaped. The frontend-owned distributed-locking protocol (`listAndLockHead` → `prolongRequestLock` → `deleteRequestLock`) was removed. Queue-head and consistency bookkeeping are now internal concerns of the backend implementation.
68
+
69
+ | Before (v3) | After (v4) |
70
+ |---|---|
71
+ | `addRequest(request, opts?)` | `addBatchOfRequests([request], opts?)` |
72
+ | `batchAddRequests(requests, opts?)` | `addBatchOfRequests(requests, opts?)` |
73
+ | `getRequest(id)` | `getRequest(uniqueKey)` |
74
+ | `updateRequest(request, opts?)` | `markRequestAsHandled(request)` / `reclaimRequest(request, opts?)` |
75
+ | `listHead(opts?)` | `fetchNextRequest()` (returns a single request, marks it in progress) |
76
+ | `listAndLockHead(opts)` | Removed (locking is internal to the client) |
77
+ | `prolongRequestLock(id, opts)` | `extendRequestProcessingTime(requestId, extensionSecs)` (optional — per-request lock extension for locking backends; wired to `context.extendTimeout`) |
78
+ | `deleteRequestLock(id, opts?)` | Removed |
79
+ | `deleteRequest(id)` | Removed |
80
+ | _(n/a)_ | `isEmpty()` (new — `true` when no pending requests are left to fetch) |
81
+ | _(n/a)_ | `isFinished()` (new — `true` when no pending **and** no in-progress requests remain) |
82
+
83
+ The lifecycle is now: `fetchNextRequest()` hands out a pending request and marks it in progress; once processed, call `markRequestAsHandled(request)`; on failure call `reclaimRequest(request, { forefront? })` to return it to the queue.
84
+
85
+ Methods that may have "nothing" to return now consistently resolve to `undefined` rather than `null`. `fetchNextRequest()` resolves to `undefined` when there is nothing to fetch, and `markRequestAsHandled()` / `reclaimRequest()` resolve to `undefined` when the request is not something the backend is currently processing (a no-op, not an error). This matches the `undefined` already returned by `getRequest()`, `KeyValueStoreBackend.getValue()`, and `getPublicUrl()`, so the whole backend family uses a single "absent" sentinel. If you implemented a custom backend that returned `null` from these methods, return `undefined` instead.
86
+
87
+ `RequestQueueBackend.isEmpty()` and `RequestQueueBackend.isFinished()` answer two different questions:
88
+
89
+ - `isEmpty()` is the weak check — `true` when the next `fetchNextRequest()` would return `undefined`, i.e. there is nothing left to fetch right now. Requests that are currently in progress (fetched but not yet handled or reclaimed) are **not** counted, because they are not fetchable. This is what drives the crawler's task scheduling.
90
+ - `isFinished()` is the strong check — `true` only when there are no pending requests **and** no requests currently in progress (including those locked by other clients sharing the queue). This is what determines whether crawling is actually done. An in-progress request keeps the queue *empty but not finished*, which is what stops a crawler from shutting down while a request is still being processed.
91
+
92
+ The loader and manager frontends do **not** draw that distinction — `IRequestLoader` and `IRequestManager` answer both questions with one [`checkReadiness()`](./request-loaders.md#isempty--isfinished-replaced-by-checkreadiness) call. The split lives at the backend boundary because that is the layer where the two questions really are two separate storage lookups; a frontend that split them too would either probe twice per scheduling decision or lose the distinction, whereas a backend that answers one at a time costs its caller nothing.
93
+
94
+ The separate `RequestQueueV1`/`RequestQueueV2` classes (and the `RequestProvider` base class) have been removed. They no longer differ in behavior — request coordination is now internal to the storage backend — so they are merged into a single `RequestQueue` class. Replace any `RequestQueueV1`, `RequestQueueV2`, or `RequestProvider` imports with `RequestQueue`.
95
+
96
+ The `requestLocking` crawler experiment has been removed, along with the `experiments` crawler option and the `CrawlerExperiments` type that contained it. Request locking has been the default since v3.10 and there is no longer an alternative implementation to opt out to, so the flag did nothing. Delete any `experiments: { requestLocking: ... }` from your crawler options:
97
+
98
+ ```diff
99
+ const crawler = new CheerioCrawler({
100
+ async requestHandler({ $, request }) {
101
+ // ...
102
+ },
103
+ - experiments: {
104
+ - requestLocking: true,
105
+ - },
106
+ });
107
+ ```
108
+
109
+ The `RequestQueue.requestLockSecs` property has been removed. Because request locking is now internal to the storage backend, the lock duration is no longer configured on the queue. When you run a crawler, it automatically tells the queue how long it expects to hold a request (based on `requestHandlerTimeoutMillis`), so a long-running request handler will not have its request handed out a second time — you usually don't need to configure anything.
110
+
111
+ If you use a `RequestQueue` outside of a crawler and your processing may exceed the 3-minute default lock, call `setExpectedRequestProcessingTime(processingTimeSecs)` on the queue to raise it:
112
+
113
+ ```typescript
114
+ import { RequestQueue } from 'crawlee';
115
+
116
+ const queue = await RequestQueue.open();
117
+ await queue.setExpectedRequestProcessingTime(600);
118
+ ```
119
+
120
+ The `RequestQueue.internalTimeoutMillis` property and the associated "stuck queue" self-recovery have been removed. In v3 the `RequestQueue` frontend kept its own copy of the queue head and in-progress set, which could drift out of sync with the backing storage (an eventual-consistency hazard on the Apify platform); `isFinished()` watched for inactivity exceeding `internalTimeoutMillis` and reset that frontend state to recover. In v4 the frontend no longer holds any such bookkeeping — the storage backend is the single source of truth — so there is nothing for a reset to fix, and stuck request locks now self-heal on expiry. Any consistency-recovery logic that is genuinely specific to the Apify platform's distributed storage belongs in the Apify SDK's client implementation instead, and is tracked in [apify/crawlee#3328](https://github.com/apify/crawlee/issues/3328).
121
+
122
+ **Apify-specific fields removed from storage metadata.** The metadata returned by `getMetadata()` (`DatasetInfo`, `KeyValueStoreInfo`, `RequestQueueInfo`) has been trimmed to what is meaningful for any storage backend. The following platform-specific fields were dropped: `actId`, `actRunId`, `userId`, and — on `RequestQueueInfo` — `expireAt` and `hadMultipleClients`. The per-storage `stats` field (and its `DatasetStats` / `KeyValueStoreStats` / `RequestQueueStats` types) was removed as well. If you consumed any of these, read them from the Apify API client directly; a custom `StorageBackend` should simply stop returning them.
123
+
124
+ **Removed types** from `@crawlee/types`: `DatasetClientUpdateOptions`, `KeyValueStoreClientUpdateOptions`, `KeyValueStoreRecordOptions`, `KeyValueStoreClientListData`, `KeyValueStoreClientGetRecordOptions`, `QueueHead`, `RequestQueueHeadItem`, `ListOptions`, `ListAndLockOptions`, `ListAndLockHeadResult`, `ProlongRequestLockOptions`, `ProlongRequestLockResult`, `DeleteRequestLockOptions`, `DatasetStats`, `KeyValueStoreStats`, `RequestQueueStats`. `KeyValueStoreClientListOptions` was renamed to `KeyValueStoreListKeysOptions`.
125
+
126
+ The high-level storage classes (`Dataset`, `KeyValueStore`, `RequestQueue`) are now thin wrappers over a single sub-backend, which they receive directly in the constructor options. The constructor takes `{ metadata, backend }`, where `backend` is the sub-backend and `metadata` is the resolved storage info (as returned by the backend's `getMetadata()`) that the storage derives its `id` and `name` from — instead of receiving separate `id` / `name` arguments (or a `StorageBackend` and calling its methods). In practice you never call these constructors yourself; use `Dataset.open()` / `KeyValueStore.open()` / `RequestQueue.open()`, which resolve the metadata and open the backend for you.
127
+
128
+ `RequestQueue` no longer accepts (or stores) `clientKey` / `timeoutSecs`. These are request-locking concerns that are now internal to the storage backend implementation (see [apify/crawlee#3328](https://github.com/apify/crawlee/issues/3328)); the `create*Backend` methods take a plain `StorageIdentifier` (`{ id?, name?, alias? }`).
129
+
130
+ ### `RecordOptions` simplified
131
+
132
+ `timeoutSecs` and `doNotRetryTimeouts` were removed from `RecordOptions` (used by `KeyValueStore.setValue`). Only `contentType` remains.
133
+
134
+ ### `maybeStringify` is removed
135
+
136
+ The `maybeStringify` helper exported from `@crawlee/core` has been removed. Value (de)serialization now lives entirely in the `KeyValueStore` frontend: writing serializes the value (and infers its content type), reading parses it back, and the storage backend is a plain byte transport. If you imported `maybeStringify` directly, use the `serializeValue` / `parseValue` functions exported from `@crawlee/core` instead.
137
+
138
+ ### `KeyValueStoreIteratorOptions` simplified
139
+
140
+ `exclusiveStartKey` and `collection` were removed. Only `prefix` remains.
141
+
142
+ ### `Dataset.listItems` replaced by `Dataset.getData` and `Dataset.values`
143
+
144
+ `Dataset.listItems()` is replaced by two methods:
145
+ - `Dataset.getData(options?)` — returns a single `PaginatedList<Data>` page.
146
+ - `Dataset.values(options?)` — dual iterable: `for await...of` iterates all items; `await` returns all items as `Data[]`.
147
+
148
+ `Dataset.entries()` works the same way as `values()` but yields `[index, Data]` tuples. `KeyValueStore.keys()`, `.values()`, `.entries()` follow the same dual-iterable pattern.
149
+
150
+ ### Removed `list()` method
151
+
152
+ The `list()` method on collection clients (e.g. `client.datasets().list()`) has no replacement. If you were using it to enumerate all storages, you will need to use the Apify API client directly.
153
+
154
+ ### Migration guide
155
+
156
+ If you implemented a custom `StorageBackend`, you need to:
157
+
158
+ 1. Remove your `*CollectionClient` classes.
159
+ 2. Replace the six getter methods (`dataset`, `datasets`, `keyValueStore`, `keyValueStores`, `requestQueue`, `requestQueues`) with three async factory methods (`createDatasetBackend`, `createKeyValueStoreBackend`, `createRequestQueueBackend`). Each factory should handle both opening an existing storage and creating a new one.
160
+ 3. Apply the sub-backend renames listed above (`get` → `getMetadata`, `delete` → `drop`, etc.) and implement the new `purge()` method.
161
+
162
+ ## Storage internals are no longer part of the public API
163
+
164
+ `DatasetOptions`, `KeyValueStoreOptions` and `RequestQueueOptions` are internal. They only described the arguments of the storage constructors, which were already internal — always open storages through the static `open()` methods.
165
+
166
+ ## `Dataset` field visibility now matches its siblings
167
+
168
+ - `Dataset.client` is now `Dataset.backend`, matching `KeyValueStore.backend` and `RequestQueue.backend`. Prefer the `Dataset` methods (`pushData`, `getData`, `getInfo`, `drop`, ...) over reaching for the backend.
169
+ - `Dataset.id` and `Dataset.name` are `readonly`, matching `KeyValueStore` and `RequestQueue`.
170
+ - `Dataset.log` has been removed. It was never read by Crawlee and `KeyValueStore` never had it; use your own logger, or `crawler.log` inside a request handler.