@crawlee/browser-pool 4.0.0-beta.11 → 4.0.0-beta.111
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 +17 -13
- package/abstract-classes/browser-controller.d.ts +70 -13
- package/abstract-classes/browser-controller.js +18 -20
- package/abstract-classes/browser-plugin.d.ts +48 -15
- package/abstract-classes/browser-plugin.js +69 -11
- package/anonymize-proxy.d.ts +5 -2
- package/anonymize-proxy.js +9 -5
- package/browser-pool.d.ts +100 -28
- package/browser-pool.js +188 -61
- package/container-proxy-server.d.ts +0 -1
- package/container-proxy-server.js +0 -1
- package/events.d.ts +0 -1
- package/events.js +0 -1
- package/fingerprinting/hooks.d.ts +0 -1
- package/fingerprinting/hooks.js +26 -10
- package/fingerprinting/types.d.ts +0 -1
- package/fingerprinting/types.js +0 -1
- package/fingerprinting/utils.d.ts +0 -1
- package/fingerprinting/utils.js +0 -1
- package/index.d.ts +14 -7
- package/index.js +5 -3
- package/launch-context.d.ts +20 -5
- package/launch-context.js +21 -10
- package/package.json +8 -9
- package/playwright/playwright-browser.d.ts +2 -6
- package/playwright/playwright-browser.js +16 -17
- package/playwright/playwright-controller.d.ts +0 -1
- package/playwright/playwright-controller.js +20 -10
- package/playwright/playwright-plugin.d.ts +10 -7
- package/playwright/playwright-plugin.js +40 -16
- package/proxy-server.d.ts +0 -1
- package/proxy-server.js +0 -1
- package/puppeteer/puppeteer-controller.d.ts +0 -1
- package/puppeteer/puppeteer-controller.js +16 -9
- package/puppeteer/puppeteer-plugin.d.ts +5 -3
- package/puppeteer/puppeteer-plugin.js +83 -46
- package/remote-browser-pool.d.ts +164 -0
- package/remote-browser-pool.js +191 -0
- package/remote-browser-provider.d.ts +83 -0
- package/remote-browser-provider.js +67 -0
- package/utils.d.ts +7 -1
- package/utils.js +19 -1
- package/abstract-classes/browser-controller.d.ts.map +0 -1
- package/abstract-classes/browser-controller.js.map +0 -1
- package/abstract-classes/browser-plugin.d.ts.map +0 -1
- package/abstract-classes/browser-plugin.js.map +0 -1
- package/anonymize-proxy.d.ts.map +0 -1
- package/anonymize-proxy.js.map +0 -1
- package/browser-pool.d.ts.map +0 -1
- package/browser-pool.js.map +0 -1
- package/container-proxy-server.d.ts.map +0 -1
- package/container-proxy-server.js.map +0 -1
- package/events.d.ts.map +0 -1
- package/events.js.map +0 -1
- package/fingerprinting/hooks.d.ts.map +0 -1
- package/fingerprinting/hooks.js.map +0 -1
- package/fingerprinting/types.d.ts.map +0 -1
- package/fingerprinting/types.js.map +0 -1
- package/fingerprinting/utils.d.ts.map +0 -1
- package/fingerprinting/utils.js.map +0 -1
- package/index.d.ts.map +0 -1
- package/index.js.map +0 -1
- package/launch-context.d.ts.map +0 -1
- package/launch-context.js.map +0 -1
- package/logger.d.ts +0 -3
- package/logger.d.ts.map +0 -1
- package/logger.js +0 -5
- package/logger.js.map +0 -1
- package/playwright/playwright-browser.d.ts.map +0 -1
- package/playwright/playwright-browser.js.map +0 -1
- package/playwright/playwright-controller.d.ts.map +0 -1
- package/playwright/playwright-controller.js.map +0 -1
- package/playwright/playwright-plugin.d.ts.map +0 -1
- package/playwright/playwright-plugin.js.map +0 -1
- package/proxy-server.d.ts.map +0 -1
- package/proxy-server.js.map +0 -1
- package/puppeteer/puppeteer-controller.d.ts.map +0 -1
- package/puppeteer/puppeteer-controller.js.map +0 -1
- package/puppeteer/puppeteer-plugin.d.ts.map +0 -1
- package/puppeteer/puppeteer-plugin.js.map +0 -1
- package/tsconfig.build.tsbuildinfo +0 -1
- package/utils.d.ts.map +0 -1
- package/utils.js.map +0 -1
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
import { readFile } from 'node:fs/promises';
|
|
2
2
|
import { BrowserPlugin } from '../abstract-classes/browser-plugin.js';
|
|
3
3
|
import { anonymizeProxySugar } from '../anonymize-proxy.js';
|
|
4
|
-
import { log } from '../logger.js';
|
|
5
4
|
import { noop } from '../utils.js';
|
|
6
5
|
import { PuppeteerController } from './puppeteer-controller.js';
|
|
7
6
|
const PROXY_SERVER_ARG = '--proxy-server=';
|
|
8
7
|
export class PuppeteerPlugin extends BrowserPlugin {
|
|
8
|
+
/** Pages share cookies/storage on the remote browser (Puppeteer defaults to non-incognito). */
|
|
9
|
+
useRemoteConnection(connection, parameters = {}) {
|
|
10
|
+
super.useRemoteConnection(connection, parameters);
|
|
11
|
+
if (!this.useIncognitoPages) {
|
|
12
|
+
this.log.info('Remote Puppeteer connection — pages will share cookies and storage on the remote ' +
|
|
13
|
+
'browser instance (useIncognitoPages defaults to false).');
|
|
14
|
+
}
|
|
15
|
+
}
|
|
9
16
|
async _launch(launchContext) {
|
|
10
17
|
let oldPuppeteerVersion = false;
|
|
11
18
|
try {
|
|
@@ -17,58 +24,80 @@ export class PuppeteerPlugin extends BrowserPlugin {
|
|
|
17
24
|
catch {
|
|
18
25
|
// ignore
|
|
19
26
|
}
|
|
20
|
-
const {
|
|
21
|
-
launchOptions.userDataDir = launchOptions.userDataDir ?? userDataDir;
|
|
22
|
-
if (launchOptions.headless === false) {
|
|
23
|
-
if (Array.isArray(launchOptions.args)) {
|
|
24
|
-
launchOptions.args.push('--disable-site-isolation-trials');
|
|
25
|
-
}
|
|
26
|
-
else {
|
|
27
|
-
launchOptions.args = ['--disable-site-isolation-trials'];
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
if (launchOptions.headless === true && oldPuppeteerVersion) {
|
|
31
|
-
launchOptions.headless = 'new';
|
|
32
|
-
}
|
|
27
|
+
const { useIncognitoPages, proxyUrl, ignoreProxyCertificate } = launchContext;
|
|
33
28
|
let browser;
|
|
34
|
-
{
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
29
|
+
if (this.remoteConnection) {
|
|
30
|
+
browser = await this.connectToRemoteBrowser(launchContext, async (url) => {
|
|
31
|
+
const connectOptions = this.remoteConnectionParameters?.connectOptions ?? {};
|
|
32
|
+
this.log.info('Connecting to remote browser via connect (CDP).');
|
|
33
|
+
return this.library.connect({ ...connectOptions, browserWSEndpoint: url });
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
const { launchOptions, userDataDir, experimentalContainers } = launchContext;
|
|
38
|
+
if (experimentalContainers) {
|
|
39
|
+
throw new Error('Experimental containers are only available with Playwright');
|
|
40
|
+
}
|
|
41
|
+
launchOptions.userDataDir = launchOptions.userDataDir ?? userDataDir;
|
|
42
|
+
if (launchOptions.headless === false) {
|
|
38
43
|
if (Array.isArray(launchOptions.args)) {
|
|
39
|
-
launchOptions.args.push(
|
|
44
|
+
launchOptions.args.push('--disable-site-isolation-trials');
|
|
40
45
|
}
|
|
41
46
|
else {
|
|
42
|
-
launchOptions.args = [
|
|
47
|
+
launchOptions.args = ['--disable-site-isolation-trials'];
|
|
43
48
|
}
|
|
44
49
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
if (anonymizedProxyUrl) {
|
|
48
|
-
browser.on('disconnected', async () => {
|
|
49
|
-
await close();
|
|
50
|
-
});
|
|
51
|
-
}
|
|
50
|
+
if (launchOptions.headless === true && oldPuppeteerVersion) {
|
|
51
|
+
launchOptions.headless = 'new';
|
|
52
52
|
}
|
|
53
|
-
|
|
54
|
-
await
|
|
55
|
-
|
|
53
|
+
{
|
|
54
|
+
const [anonymizedProxyUrl, close] = await anonymizeProxySugar(proxyUrl, undefined, undefined, {
|
|
55
|
+
ignoreProxyCertificate: launchContext.ignoreProxyCertificate,
|
|
56
|
+
});
|
|
57
|
+
if (proxyUrl) {
|
|
58
|
+
const proxyArg = `${PROXY_SERVER_ARG}${anonymizedProxyUrl ?? proxyUrl}`;
|
|
59
|
+
if (Array.isArray(launchOptions.args)) {
|
|
60
|
+
launchOptions.args.push(proxyArg);
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
launchOptions.args = [proxyArg];
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
try {
|
|
67
|
+
browser = await this.library.launch(launchOptions);
|
|
68
|
+
if (anonymizedProxyUrl) {
|
|
69
|
+
browser.on('disconnected', async () => {
|
|
70
|
+
await close();
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
await close();
|
|
76
|
+
this.throwAugmentedLaunchError(error, launchContext.launchOptions?.executablePath, '`apify/actor-node-puppeteer-chrome`', "Try installing a browser, if it's missing, by running `npx @puppeteer/browsers install chromium --path [path]` and pointing `executablePath` to the downloaded executable (https://pptr.dev/browsers-api)");
|
|
77
|
+
}
|
|
56
78
|
}
|
|
57
79
|
}
|
|
58
|
-
|
|
80
|
+
const targetCreatedHandler = async (target) => {
|
|
59
81
|
try {
|
|
60
82
|
const page = await target.page();
|
|
61
83
|
if (page) {
|
|
62
84
|
page.on('error', (error) => {
|
|
63
|
-
log.exception(error, 'Page crashed.');
|
|
85
|
+
this.log.exception(error, 'Page crashed.');
|
|
64
86
|
page.close().catch(noop);
|
|
65
87
|
});
|
|
66
88
|
}
|
|
67
89
|
}
|
|
68
90
|
catch (error) {
|
|
69
|
-
log.exception(error, 'Failed to retrieve page from target.');
|
|
91
|
+
this.log.exception(error, 'Failed to retrieve page from target.');
|
|
70
92
|
}
|
|
71
|
-
}
|
|
93
|
+
};
|
|
94
|
+
browser.on('targetcreated', targetCreatedHandler);
|
|
95
|
+
// Clean up the listener when a remote browser disconnects to prevent leaks
|
|
96
|
+
if (this.remoteConnection) {
|
|
97
|
+
browser.once('disconnected', () => {
|
|
98
|
+
browser.off('targetcreated', targetCreatedHandler);
|
|
99
|
+
});
|
|
100
|
+
}
|
|
72
101
|
const boundMethods = [
|
|
73
102
|
'newPage',
|
|
74
103
|
'close',
|
|
@@ -78,6 +107,7 @@ export class PuppeteerPlugin extends BrowserPlugin {
|
|
|
78
107
|
'version',
|
|
79
108
|
'on',
|
|
80
109
|
'process',
|
|
110
|
+
'pages',
|
|
81
111
|
].reduce((map, method) => {
|
|
82
112
|
map[method] = browser[method]?.bind(browser);
|
|
83
113
|
return map;
|
|
@@ -89,22 +119,30 @@ export class PuppeteerPlugin extends BrowserPlugin {
|
|
|
89
119
|
return async (...args) => {
|
|
90
120
|
let page;
|
|
91
121
|
if (useIncognitoPages) {
|
|
92
|
-
|
|
122
|
+
// Skip proxy setup for remote connections — proxy is managed by the remote service.
|
|
123
|
+
const effectiveProxyUrl = this.remoteConnection ? undefined : proxyUrl;
|
|
124
|
+
const [anonymizedProxyUrl, close] = effectiveProxyUrl
|
|
125
|
+
? await anonymizeProxySugar(effectiveProxyUrl, undefined, undefined, {
|
|
126
|
+
ignoreProxyCertificate,
|
|
127
|
+
})
|
|
128
|
+
: [undefined, noop];
|
|
129
|
+
const proxyServer = anonymizedProxyUrl ?? effectiveProxyUrl;
|
|
130
|
+
const contextOptions = proxyServer ? { proxyServer } : {};
|
|
131
|
+
const context = (await browser[method](contextOptions));
|
|
93
132
|
try {
|
|
94
|
-
const context = (await browser[method]({
|
|
95
|
-
proxyServer: anonymizedProxyUrl ?? proxyUrl,
|
|
96
|
-
}));
|
|
97
133
|
page = await context.newPage(...args);
|
|
98
|
-
if (anonymizedProxyUrl) {
|
|
99
|
-
page.on('close', async () => {
|
|
100
|
-
await close();
|
|
101
|
-
});
|
|
102
|
-
}
|
|
103
134
|
}
|
|
104
135
|
catch (error) {
|
|
136
|
+
await context.close().catch(noop);
|
|
105
137
|
await close();
|
|
106
138
|
throw error;
|
|
107
139
|
}
|
|
140
|
+
page.once('close', async () => {
|
|
141
|
+
if (anonymizedProxyUrl) {
|
|
142
|
+
await close();
|
|
143
|
+
}
|
|
144
|
+
await context.close().catch(noop);
|
|
145
|
+
});
|
|
108
146
|
}
|
|
109
147
|
else {
|
|
110
148
|
page = await boundMethods.newPage(...args);
|
|
@@ -139,7 +177,7 @@ export class PuppeteerPlugin extends BrowserPlugin {
|
|
|
139
177
|
createController() {
|
|
140
178
|
return new PuppeteerController(this);
|
|
141
179
|
}
|
|
142
|
-
async
|
|
180
|
+
async addProxyToLaunchOptions(_launchContext) {
|
|
143
181
|
/*
|
|
144
182
|
// DO NOT USE YET! DOING SO DISABLES CACHE WHICH IS 50% PERFORMANCE HIT!
|
|
145
183
|
launchContext.launchOptions ??= {};
|
|
@@ -166,8 +204,7 @@ export class PuppeteerPlugin extends BrowserPlugin {
|
|
|
166
204
|
}
|
|
167
205
|
*/
|
|
168
206
|
}
|
|
169
|
-
|
|
207
|
+
isChromiumBasedBrowser(_launchContext) {
|
|
170
208
|
return true;
|
|
171
209
|
}
|
|
172
210
|
}
|
|
173
|
-
//# sourceMappingURL=puppeteer-plugin.js.map
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import type { IBrowserPool, NewPageOptions, PageState } from '@crawlee/types';
|
|
2
|
+
import type { BrowserPlugin } from './abstract-classes/browser-plugin.js';
|
|
3
|
+
import { BrowserPool } from './browser-pool.js';
|
|
4
|
+
import type { BrowserPoolHooks, BrowserPoolOptions } from './browser-pool.js';
|
|
5
|
+
import { RemoteBrowserProvider } from './remote-browser-provider.js';
|
|
6
|
+
/**
|
|
7
|
+
* The result of resolving a remote browser endpoint: the URL to connect to plus an optional opaque
|
|
8
|
+
* `context` object that is handed back to `release`.
|
|
9
|
+
*/
|
|
10
|
+
export interface ResolvedRemoteEndpoint {
|
|
11
|
+
/** The browser endpoint URL to connect to. */
|
|
12
|
+
url: string;
|
|
13
|
+
/** Opaque metadata passed back to `release()` — e.g. session IDs, API tokens. */
|
|
14
|
+
context?: Record<string, unknown>;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* A remote browser endpoint: either a static URL string, or a function called once per browser launch
|
|
18
|
+
* that returns a URL (optionally with a `context` for `release`).
|
|
19
|
+
*
|
|
20
|
+
* The function receives the `proxyUrl` resolved by Crawlee's proxy configuration for the launch, so it
|
|
21
|
+
* can forward it to the remote service's proxy API.
|
|
22
|
+
*/
|
|
23
|
+
export type RemoteBrowserEndpoint = string | ((options?: {
|
|
24
|
+
proxyUrl?: string;
|
|
25
|
+
}) => string | ResolvedRemoteEndpoint | Promise<string | ResolvedRemoteEndpoint>);
|
|
26
|
+
/**
|
|
27
|
+
* The bridge a {@link RemoteBrowserPool} injects into a {@link BrowserPlugin} so the plugin can
|
|
28
|
+
* connect to a remote browser without owning any remote-session policy.
|
|
29
|
+
*
|
|
30
|
+
* The plugin only knows how to make the library-specific `connect()` call; everything else — resolving
|
|
31
|
+
* the endpoint, calling the user's `release()`, and guaranteeing release fires at most once — lives in
|
|
32
|
+
* the pool. The plugin calls {@link RemoteConnection.resolve|resolve} before connecting, stores the
|
|
33
|
+
* returned `token` on its launch context, and the controller later calls
|
|
34
|
+
* {@link RemoteConnection.release|release} with that token when the browser closes.
|
|
35
|
+
*/
|
|
36
|
+
export interface RemoteConnection {
|
|
37
|
+
/** Resolves the endpoint for a single browser launch. The `token` identifies the session for release. */
|
|
38
|
+
resolve(options?: {
|
|
39
|
+
proxyUrl?: string;
|
|
40
|
+
}): Promise<{
|
|
41
|
+
url: string;
|
|
42
|
+
token: number;
|
|
43
|
+
}>;
|
|
44
|
+
/** Releases the remote session for `token`. Idempotent — safe to call from both `close()` and `kill()`. */
|
|
45
|
+
release(token: number): Promise<void>;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Per-plugin remote connection parameters, passed to {@link BrowserPlugin.useRemoteConnection}.
|
|
49
|
+
* The endpoint is supplied per-launch via {@link RemoteConnection}; these are the static connect()
|
|
50
|
+
* parameters (protocol, headers, timeouts, …).
|
|
51
|
+
*/
|
|
52
|
+
export interface RemoteConnectionParameters {
|
|
53
|
+
/**
|
|
54
|
+
* Playwright only: which protocol to connect with. `'cdp'` uses `connectOverCDP()` (the default),
|
|
55
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
56
|
+
* `'playwright'` uses `connect()` (Playwright's own WebSocket protocol). Ignored by Puppeteer.
|
|
57
|
+
*/
|
|
58
|
+
protocol?: 'cdp' | 'playwright';
|
|
59
|
+
/** Extra options forwarded to the library `connect()` / `connectOverCDP()` call (endpoint excluded). */
|
|
60
|
+
connectOptions?: Record<string, unknown>;
|
|
61
|
+
}
|
|
62
|
+
export interface RemoteBrowserPoolOptions {
|
|
63
|
+
/**
|
|
64
|
+
* The browser plugin(s) used to connect to the remote service — e.g. `new PlaywrightPlugin(playwright.chromium)`
|
|
65
|
+
* or `new PuppeteerPlugin(puppeteer)`. The pool configures them for remote connection; do not set a local
|
|
66
|
+
* `launchOptions` on them.
|
|
67
|
+
*/
|
|
68
|
+
browserPlugins: BrowserPlugin[];
|
|
69
|
+
/**
|
|
70
|
+
* The remote browser endpoint: a static URL, a function returning one per launch, or a
|
|
71
|
+
* {@link RemoteBrowserProvider} instance encapsulating a session create/release lifecycle.
|
|
72
|
+
*/
|
|
73
|
+
endpoint: RemoteBrowserEndpoint | RemoteBrowserProvider<any>;
|
|
74
|
+
/**
|
|
75
|
+
* Cleanup callback invoked when a browser closes, crashes, or the pool is destroyed. Receives the
|
|
76
|
+
* `context` returned by a function endpoint. Errors are caught and logged. Ignored when `endpoint`
|
|
77
|
+
* is a {@link RemoteBrowserProvider} (its own `release()` is used instead).
|
|
78
|
+
*/
|
|
79
|
+
release?: (info: {
|
|
80
|
+
endpoint: string;
|
|
81
|
+
context?: Record<string, unknown>;
|
|
82
|
+
}) => unknown;
|
|
83
|
+
/**
|
|
84
|
+
* Maximum number of remote browsers open at once. When reached, {@link RemoteBrowserPool.newPage|newPage}
|
|
85
|
+
* waits for a browser to close before connecting a new one. Set it to your service's concurrent-session limit
|
|
86
|
+
* to avoid `429` errors. Defaults to the {@link RemoteBrowserProvider.maxOpenBrowsers|provider's value}, or
|
|
87
|
+
* `Infinity`.
|
|
88
|
+
*/
|
|
89
|
+
maxOpenBrowsers?: number;
|
|
90
|
+
/** Static connect() parameters (Playwright protocol selection, headers, timeouts, …). */
|
|
91
|
+
connection?: RemoteConnectionParameters;
|
|
92
|
+
/** Extra {@link BrowserPool} options (lifecycle hooks, page limits, fingerprinting, …). */
|
|
93
|
+
browserPoolOptions?: Omit<BrowserPoolOptions, 'browserPlugins'> & BrowserPoolHooks<any, any, any>;
|
|
94
|
+
/** Fallback poll interval (ms) while waiting for a free browser slot. The wait is event-driven; this only bounds it. @default 500 */
|
|
95
|
+
slotPollIntervalMillis?: number;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The remote-connection configuration a browser crawler accepts on its `remoteBrowser` option. It is the
|
|
99
|
+
* {@link RemoteBrowserPoolOptions} a user supplies *minus* the parts the crawler provides itself — the
|
|
100
|
+
* `browserPlugins` (the crawler builds the correct one for its browser) and `browserPoolOptions` (taken from
|
|
101
|
+
* the crawler's own `browserPoolOptions`). This is what makes the crawler path both terse and mismatch-proof.
|
|
102
|
+
*/
|
|
103
|
+
export type CrawlerRemoteBrowserOptions = Omit<RemoteBrowserPoolOptions, 'browserPlugins' | 'browserPoolOptions'>;
|
|
104
|
+
/**
|
|
105
|
+
* An {@link IBrowserPool} implementation for remote browser services.
|
|
106
|
+
*
|
|
107
|
+
* Unlike configuring a remote browser through a crawler's `launchContext`, this pool is the single owner
|
|
108
|
+
* of all remote-session concerns:
|
|
109
|
+
* - **endpoint resolution** — static URL, per-launch function, or {@link RemoteBrowserProvider};
|
|
110
|
+
* - **release lifecycle** — `release()` fires exactly once per session on close/crash/teardown (no leaks,
|
|
111
|
+
* no double-release);
|
|
112
|
+
* - **concurrency** — {@link RemoteBrowserPoolOptions.maxOpenBrowsers|maxOpenBrowsers} is enforced inside
|
|
113
|
+
* {@link RemoteBrowserPool.newPage|newPage}, which waits for a free slot rather than overshooting.
|
|
114
|
+
*
|
|
115
|
+
* The wrapped {@link BrowserPool} and its plugin only perform the library-specific `connect()` call.
|
|
116
|
+
*
|
|
117
|
+
* Pass an instance as the crawler's `browserPool` option:
|
|
118
|
+
*
|
|
119
|
+
* ```typescript
|
|
120
|
+
* import { PlaywrightPlugin, RemoteBrowserPool } from '@crawlee/browser-pool';
|
|
121
|
+
* import { PlaywrightCrawler } from 'crawlee';
|
|
122
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
123
|
+
* import playwright from 'playwright';
|
|
124
|
+
*
|
|
125
|
+
* const browserPool = new RemoteBrowserPool({
|
|
126
|
+
* browserPlugins: [new PlaywrightPlugin(playwright.chromium)],
|
|
127
|
+
* endpoint: 'wss://production-sfo.browserless.io?token=xxx',
|
|
128
|
+
* maxOpenBrowsers: 2,
|
|
129
|
+
* });
|
|
130
|
+
*
|
|
131
|
+
* const crawler = new PlaywrightCrawler({ browserPool });
|
|
132
|
+
* ```
|
|
133
|
+
*
|
|
134
|
+
* @category Browser management
|
|
135
|
+
*/
|
|
136
|
+
export declare class RemoteBrowserPool<Page = unknown> implements IBrowserPool<Page> {
|
|
137
|
+
#private;
|
|
138
|
+
/** The wrapped pool that performs the remote connections and serves pages. */
|
|
139
|
+
readonly browserPool: BrowserPool;
|
|
140
|
+
constructor(options: RemoteBrowserPoolOptions);
|
|
141
|
+
/** Maximum number of remote browsers that may be open at the same time. */
|
|
142
|
+
get maxOpenBrowsers(): number;
|
|
143
|
+
set maxOpenBrowsers(value: number);
|
|
144
|
+
/**
|
|
145
|
+
* Opens a new page, waiting first until {@link RemoteBrowserPoolOptions.maxOpenBrowsers|maxOpenBrowsers}
|
|
146
|
+
* allows it (either a new browser slot is free, or an active browser still has page capacity).
|
|
147
|
+
*/
|
|
148
|
+
newPage(options?: NewPageOptions): Promise<Page>;
|
|
149
|
+
closePage(page: Page, options?: {
|
|
150
|
+
error?: Error;
|
|
151
|
+
}): Promise<void>;
|
|
152
|
+
extractPageState(page: Page): Promise<PageState>;
|
|
153
|
+
injectPageState(page: Page, state: PageState): Promise<void>;
|
|
154
|
+
/** Closes all browsers, releases any still-open remote sessions, and tears down the wrapped pool. */
|
|
155
|
+
destroy(): Promise<void>;
|
|
156
|
+
/** Resolves once the wrapped pool can serve another page without exceeding `maxOpenBrowsers`. */
|
|
157
|
+
private waitForFreeSlot;
|
|
158
|
+
/**
|
|
159
|
+
* Resolves on the next browser-retired / page-closed event, or after `slotPollIntervalMillis`. All
|
|
160
|
+
* concurrently-waiting `newPage` calls share a single promise (and a single pair of event listeners)
|
|
161
|
+
* per tick, so a fleet of saturated callers doesn't fan out into N listener pairs on the pool.
|
|
162
|
+
*/
|
|
163
|
+
private nextCapacityChange;
|
|
164
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { serviceLocator } from '@crawlee/core';
|
|
2
|
+
import { BrowserPool } from './browser-pool.js';
|
|
3
|
+
import { RemoteBrowserProvider } from './remote-browser-provider.js';
|
|
4
|
+
/**
|
|
5
|
+
* Owns the lifecycle of remote browser sessions for a single {@link RemoteBrowserPool}: endpoint
|
|
6
|
+
* resolution, the user's `release()` callback, and a release-at-most-once guarantee. Implements
|
|
7
|
+
* {@link RemoteConnection} so it can be injected into a plugin.
|
|
8
|
+
*/
|
|
9
|
+
class RemoteSessionRegistry {
|
|
10
|
+
#sessions = new Map();
|
|
11
|
+
#nextToken = 0;
|
|
12
|
+
#endpoint;
|
|
13
|
+
#onRelease;
|
|
14
|
+
#log;
|
|
15
|
+
constructor(endpoint, onRelease, log) {
|
|
16
|
+
this.#endpoint = endpoint;
|
|
17
|
+
this.#onRelease = onRelease;
|
|
18
|
+
this.#log = log;
|
|
19
|
+
}
|
|
20
|
+
async resolve(options) {
|
|
21
|
+
const resolved = typeof this.#endpoint === 'function' ? await this.#endpoint(options) : this.#endpoint;
|
|
22
|
+
let result;
|
|
23
|
+
if (typeof resolved === 'string') {
|
|
24
|
+
if (!resolved)
|
|
25
|
+
throw new Error('Remote browser endpoint resolved to an empty string.');
|
|
26
|
+
result = { url: resolved };
|
|
27
|
+
}
|
|
28
|
+
else if (!resolved?.url) {
|
|
29
|
+
throw new Error("Remote browser endpoint() must return a URL string or an object with a non-empty 'url'.");
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
result = resolved;
|
|
33
|
+
}
|
|
34
|
+
const token = this.#nextToken++;
|
|
35
|
+
this.#sessions.set(token, { url: result.url, context: result.context, released: false });
|
|
36
|
+
return { url: result.url, token };
|
|
37
|
+
}
|
|
38
|
+
async release(token) {
|
|
39
|
+
const session = this.#sessions.get(token);
|
|
40
|
+
// Release at most once per session — guards a close()/teardown race (the `released` flag is set
|
|
41
|
+
// synchronously before the awaited onRelease, so releaseAll() can't double-fire an in-flight release).
|
|
42
|
+
if (!session || session.released)
|
|
43
|
+
return;
|
|
44
|
+
session.released = true;
|
|
45
|
+
try {
|
|
46
|
+
await this.#onRelease?.({ endpoint: session.url, context: session.context });
|
|
47
|
+
}
|
|
48
|
+
catch (err) {
|
|
49
|
+
this.#log.warning('Remote browser release() failed.', { error: err?.message });
|
|
50
|
+
}
|
|
51
|
+
finally {
|
|
52
|
+
this.#sessions.delete(token);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** Releases every session that is still open. Called on pool teardown so no remote session leaks. */
|
|
56
|
+
async releaseAll() {
|
|
57
|
+
await Promise.all([...this.#sessions.keys()].map(async (token) => this.release(token)));
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* An {@link IBrowserPool} implementation for remote browser services.
|
|
62
|
+
*
|
|
63
|
+
* Unlike configuring a remote browser through a crawler's `launchContext`, this pool is the single owner
|
|
64
|
+
* of all remote-session concerns:
|
|
65
|
+
* - **endpoint resolution** — static URL, per-launch function, or {@link RemoteBrowserProvider};
|
|
66
|
+
* - **release lifecycle** — `release()` fires exactly once per session on close/crash/teardown (no leaks,
|
|
67
|
+
* no double-release);
|
|
68
|
+
* - **concurrency** — {@link RemoteBrowserPoolOptions.maxOpenBrowsers|maxOpenBrowsers} is enforced inside
|
|
69
|
+
* {@link RemoteBrowserPool.newPage|newPage}, which waits for a free slot rather than overshooting.
|
|
70
|
+
*
|
|
71
|
+
* The wrapped {@link BrowserPool} and its plugin only perform the library-specific `connect()` call.
|
|
72
|
+
*
|
|
73
|
+
* Pass an instance as the crawler's `browserPool` option:
|
|
74
|
+
*
|
|
75
|
+
* ```typescript
|
|
76
|
+
* import { PlaywrightPlugin, RemoteBrowserPool } from '@crawlee/browser-pool';
|
|
77
|
+
* import { PlaywrightCrawler } from 'crawlee';
|
|
78
|
+
* import playwright from 'playwright';
|
|
79
|
+
*
|
|
80
|
+
* const browserPool = new RemoteBrowserPool({
|
|
81
|
+
* browserPlugins: [new PlaywrightPlugin(playwright.chromium)],
|
|
82
|
+
* endpoint: 'wss://production-sfo.browserless.io?token=xxx',
|
|
83
|
+
* maxOpenBrowsers: 2,
|
|
84
|
+
* });
|
|
85
|
+
*
|
|
86
|
+
* const crawler = new PlaywrightCrawler({ browserPool });
|
|
87
|
+
* ```
|
|
88
|
+
*
|
|
89
|
+
* @category Browser management
|
|
90
|
+
*/
|
|
91
|
+
export class RemoteBrowserPool {
|
|
92
|
+
/** The wrapped pool that performs the remote connections and serves pages. */
|
|
93
|
+
browserPool;
|
|
94
|
+
/** The wrapped pool viewed through the {@link IBrowserPool} contract (the bare type widens pages to `never`). */
|
|
95
|
+
#pool;
|
|
96
|
+
#registry;
|
|
97
|
+
#slotPollIntervalMillis;
|
|
98
|
+
#log;
|
|
99
|
+
/** Shared by all `newPage` callers waiting for a free slot, so they don't each register their own listeners. */
|
|
100
|
+
#capacityChange;
|
|
101
|
+
constructor(options) {
|
|
102
|
+
const { browserPlugins, endpoint, release, maxOpenBrowsers, connection = {}, browserPoolOptions = {}, slotPollIntervalMillis = 500, } = options;
|
|
103
|
+
this.#log = serviceLocator.getLogger().child({ prefix: 'RemoteBrowserPool' });
|
|
104
|
+
this.#slotPollIntervalMillis = slotPollIntervalMillis;
|
|
105
|
+
// A RemoteBrowserProvider carries its own endpoint, release, and maxOpenBrowsers.
|
|
106
|
+
const provider = endpoint instanceof RemoteBrowserProvider ? endpoint : undefined;
|
|
107
|
+
const resolvedEndpoint = provider
|
|
108
|
+
? (opts) => provider.connect(opts)
|
|
109
|
+
: endpoint;
|
|
110
|
+
const resolvedRelease = provider
|
|
111
|
+
? ({ context }) => provider.release(context)
|
|
112
|
+
: release;
|
|
113
|
+
const resolvedMax = maxOpenBrowsers ?? provider?.maxOpenBrowsers;
|
|
114
|
+
this.#registry = new RemoteSessionRegistry(resolvedEndpoint, resolvedRelease, this.#log);
|
|
115
|
+
// Wire every plugin for remote connection.
|
|
116
|
+
for (const plugin of browserPlugins) {
|
|
117
|
+
plugin.useRemoteConnection(this.#registry, connection);
|
|
118
|
+
}
|
|
119
|
+
this.browserPool = new BrowserPool({ ...browserPoolOptions, browserPlugins });
|
|
120
|
+
this.#pool = this.browserPool;
|
|
121
|
+
// Release a browser's remote session once it closes. The registry dedupes (close() schedules a delayed
|
|
122
|
+
// kill(), so BROWSER_CLOSED can fire twice), and destroy()'s releaseAll() backstops any that never close.
|
|
123
|
+
this.browserPool.on("browserLaunched" /* BROWSER_POOL_EVENTS.BROWSER_LAUNCHED */, (controller) => {
|
|
124
|
+
controller.once("browserClosed" /* BROWSER_CONTROLLER_EVENTS.BROWSER_CLOSED */, () => {
|
|
125
|
+
const token = controller.launchContext.remoteToken;
|
|
126
|
+
if (token !== undefined)
|
|
127
|
+
void this.#registry.release(token);
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
if (resolvedMax !== undefined) {
|
|
131
|
+
this.browserPool.maxOpenBrowsers = resolvedMax;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/** Maximum number of remote browsers that may be open at the same time. */
|
|
135
|
+
get maxOpenBrowsers() {
|
|
136
|
+
return this.browserPool.maxOpenBrowsers;
|
|
137
|
+
}
|
|
138
|
+
set maxOpenBrowsers(value) {
|
|
139
|
+
this.browserPool.maxOpenBrowsers = value;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Opens a new page, waiting first until {@link RemoteBrowserPoolOptions.maxOpenBrowsers|maxOpenBrowsers}
|
|
143
|
+
* allows it (either a new browser slot is free, or an active browser still has page capacity).
|
|
144
|
+
*/
|
|
145
|
+
async newPage(options) {
|
|
146
|
+
await this.waitForFreeSlot();
|
|
147
|
+
return this.#pool.newPage(options);
|
|
148
|
+
}
|
|
149
|
+
async closePage(page, options) {
|
|
150
|
+
return this.#pool.closePage(page, options);
|
|
151
|
+
}
|
|
152
|
+
async extractPageState(page) {
|
|
153
|
+
return this.#pool.extractPageState(page);
|
|
154
|
+
}
|
|
155
|
+
async injectPageState(page, state) {
|
|
156
|
+
return this.#pool.injectPageState(page, state);
|
|
157
|
+
}
|
|
158
|
+
/** Closes all browsers, releases any still-open remote sessions, and tears down the wrapped pool. */
|
|
159
|
+
async destroy() {
|
|
160
|
+
await this.browserPool.destroy();
|
|
161
|
+
// Backstop: release any sessions whose browser never emitted a close (e.g. dropped on teardown).
|
|
162
|
+
await this.#registry.releaseAll();
|
|
163
|
+
}
|
|
164
|
+
/** Resolves once the wrapped pool can serve another page without exceeding `maxOpenBrowsers`. */
|
|
165
|
+
async waitForFreeSlot() {
|
|
166
|
+
while (!this.browserPool.hasFreeBrowserSlot() && !this.browserPool.hasActiveBrowserWithFreeCapacity()) {
|
|
167
|
+
await this.nextCapacityChange();
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Resolves on the next browser-retired / page-closed event, or after `slotPollIntervalMillis`. All
|
|
172
|
+
* concurrently-waiting `newPage` calls share a single promise (and a single pair of event listeners)
|
|
173
|
+
* per tick, so a fleet of saturated callers doesn't fan out into N listener pairs on the pool.
|
|
174
|
+
*/
|
|
175
|
+
nextCapacityChange() {
|
|
176
|
+
this.#capacityChange ??= new Promise((resolve) => {
|
|
177
|
+
const done = () => {
|
|
178
|
+
clearTimeout(timer);
|
|
179
|
+
this.browserPool.off("browserRetired" /* BROWSER_POOL_EVENTS.BROWSER_RETIRED */, done);
|
|
180
|
+
this.browserPool.off("pageClosed" /* BROWSER_POOL_EVENTS.PAGE_CLOSED */, done);
|
|
181
|
+
this.#capacityChange = undefined;
|
|
182
|
+
resolve();
|
|
183
|
+
};
|
|
184
|
+
const timer = setTimeout(done, this.#slotPollIntervalMillis);
|
|
185
|
+
timer.unref?.();
|
|
186
|
+
this.browserPool.once("browserRetired" /* BROWSER_POOL_EVENTS.BROWSER_RETIRED */, done);
|
|
187
|
+
this.browserPool.once("pageClosed" /* BROWSER_POOL_EVENTS.PAGE_CLOSED */, done);
|
|
188
|
+
});
|
|
189
|
+
return this.#capacityChange;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Abstract base class for remote browser service providers.
|
|
3
|
+
*
|
|
4
|
+
* Implement this class to encapsulate the lifecycle of a remote browser session
|
|
5
|
+
* (creation, connection URL resolution, and cleanup). {@link RemoteBrowserPool}
|
|
6
|
+
* calls {@link connect} once per browser launch and {@link release} when the browser
|
|
7
|
+
* closes, crashes, the pool is destroyed, or the connection fails during launch.
|
|
8
|
+
*
|
|
9
|
+
* Pass the provider instance as the `endpoint` of a {@link RemoteBrowserPool}, then
|
|
10
|
+
* hand the pool to a crawler via its `browserPool` option:
|
|
11
|
+
*
|
|
12
|
+
* ```typescript
|
|
13
|
+
* const browserPool = new RemoteBrowserPool({
|
|
14
|
+
* browserPlugins: [new PlaywrightPlugin(playwright.chromium)],
|
|
15
|
+
* endpoint: new MyProvider(),
|
|
16
|
+
* });
|
|
17
|
+
*
|
|
18
|
+
* const crawler = new PlaywrightCrawler({ browserPool });
|
|
19
|
+
* ```
|
|
20
|
+
*
|
|
21
|
+
* **Example — simple static endpoint (e.g. Browserless):**
|
|
22
|
+
* ```typescript
|
|
23
|
+
* class BrowserlessProvider extends RemoteBrowserProvider {
|
|
24
|
+
* maxOpenBrowsers = 2; // respect the service's concurrent session limit
|
|
25
|
+
*
|
|
26
|
+
* async connect() {
|
|
27
|
+
* return { url: `wss://production-sfo.browserless.io?token=${token}` };
|
|
28
|
+
* }
|
|
29
|
+
* }
|
|
30
|
+
* ```
|
|
31
|
+
*
|
|
32
|
+
* **Example — session lifecycle with concurrency limit (e.g. Browserbase):**
|
|
33
|
+
* ```typescript
|
|
34
|
+
* class BrowserbaseProvider extends RemoteBrowserProvider<{ id: string }> {
|
|
35
|
+
* maxOpenBrowsers = 2; // respect the service's concurrent session limit
|
|
36
|
+
*
|
|
37
|
+
* async connect({ proxyUrl } = {}) {
|
|
38
|
+
* const session = await createSession(apiKey, projectId, {
|
|
39
|
+
* proxies: proxyUrl ? [{ type: 'external', server: proxyUrl }] : undefined,
|
|
40
|
+
* });
|
|
41
|
+
* return { url: session.connectUrl, context: { id: session.id } };
|
|
42
|
+
* }
|
|
43
|
+
*
|
|
44
|
+
* async release(context: { id: string }) {
|
|
45
|
+
* await releaseSession(apiKey, context.id);
|
|
46
|
+
* }
|
|
47
|
+
* }
|
|
48
|
+
* ```
|
|
49
|
+
*/
|
|
50
|
+
export declare abstract class RemoteBrowserProvider<TContext extends Record<string, unknown> = Record<string, unknown>> {
|
|
51
|
+
/**
|
|
52
|
+
* Maximum number of browsers that can be open at the same time.
|
|
53
|
+
* Set this to your remote service's concurrent session limit to avoid 429 errors.
|
|
54
|
+
*/
|
|
55
|
+
maxOpenBrowsers?: number;
|
|
56
|
+
/**
|
|
57
|
+
* Called once per browser launch. Return the WebSocket/CDP endpoint URL
|
|
58
|
+
* and an optional `context` object that will be passed back to {@link release}.
|
|
59
|
+
*
|
|
60
|
+
* @param options.proxyUrl - The proxy URL resolved by Crawlee's proxy configuration
|
|
61
|
+
* for this browser session. Pass it to your remote service's proxy API if supported.
|
|
62
|
+
*/
|
|
63
|
+
abstract connect(options?: {
|
|
64
|
+
proxyUrl?: string;
|
|
65
|
+
}): Promise<{
|
|
66
|
+
url: string;
|
|
67
|
+
context?: TContext;
|
|
68
|
+
}> | {
|
|
69
|
+
url: string;
|
|
70
|
+
context?: TContext;
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* Called when the browser closes, crashes, the pool is destroyed, or the
|
|
74
|
+
* connection fails right after {@link connect} succeeds.
|
|
75
|
+
* Override this to clean up remote sessions, release API resources, etc.
|
|
76
|
+
*
|
|
77
|
+
* Errors thrown here are caught and logged as warnings — they never crash the crawler.
|
|
78
|
+
* Safe to assume this is called at most once per {@link connect} call.
|
|
79
|
+
*
|
|
80
|
+
* @param _context The same `context` object returned by {@link connect}.
|
|
81
|
+
*/
|
|
82
|
+
release(_context: TContext): Promise<void>;
|
|
83
|
+
}
|