@crawlee/browser-pool 4.0.0-beta.7 → 4.0.0-beta.71
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 +67 -7
- package/abstract-classes/browser-controller.d.ts.map +1 -1
- package/abstract-classes/browser-controller.js +6 -9
- package/abstract-classes/browser-controller.js.map +1 -1
- package/abstract-classes/browser-plugin.d.ts +37 -2
- package/abstract-classes/browser-plugin.d.ts.map +1 -1
- package/abstract-classes/browser-plugin.js +65 -6
- package/abstract-classes/browser-plugin.js.map +1 -1
- package/anonymize-proxy.d.ts +5 -1
- package/anonymize-proxy.d.ts.map +1 -1
- package/anonymize-proxy.js +9 -4
- package/anonymize-proxy.js.map +1 -1
- package/browser-pool.d.ts +88 -13
- package/browser-pool.d.ts.map +1 -1
- package/browser-pool.js +139 -25
- package/browser-pool.js.map +1 -1
- package/fingerprinting/hooks.d.ts.map +1 -1
- package/fingerprinting/hooks.js +24 -8
- package/fingerprinting/hooks.js.map +1 -1
- package/index.d.ts +14 -6
- package/index.d.ts.map +1 -1
- package/index.js +5 -2
- package/index.js.map +1 -1
- package/launch-context.d.ts +19 -2
- package/launch-context.d.ts.map +1 -1
- package/launch-context.js +11 -3
- package/launch-context.js.map +1 -1
- package/package.json +7 -8
- package/playwright/playwright-browser.d.ts.map +1 -1
- package/playwright/playwright-browser.js.map +1 -1
- package/playwright/playwright-controller.d.ts.map +1 -1
- package/playwright/playwright-controller.js +20 -9
- package/playwright/playwright-controller.js.map +1 -1
- package/playwright/playwright-plugin.d.ts +6 -0
- package/playwright/playwright-plugin.d.ts.map +1 -1
- package/playwright/playwright-plugin.js +27 -3
- package/playwright/playwright-plugin.js.map +1 -1
- package/puppeteer/puppeteer-controller.d.ts.map +1 -1
- package/puppeteer/puppeteer-controller.js +11 -8
- package/puppeteer/puppeteer-controller.js.map +1 -1
- package/puppeteer/puppeteer-plugin.d.ts +3 -0
- package/puppeteer/puppeteer-plugin.d.ts.map +1 -1
- package/puppeteer/puppeteer-plugin.js +81 -43
- package/puppeteer/puppeteer-plugin.js.map +1 -1
- package/remote-browser-pool.d.ts +173 -0
- package/remote-browser-pool.d.ts.map +1 -0
- package/remote-browser-pool.js +192 -0
- package/remote-browser-pool.js.map +1 -0
- package/remote-browser-provider.d.ts +84 -0
- package/remote-browser-provider.d.ts.map +1 -0
- package/remote-browser-provider.js +68 -0
- package/remote-browser-provider.js.map +1 -0
- package/utils.d.ts +7 -0
- package/utils.d.ts.map +1 -1
- package/utils.js +19 -0
- package/utils.js.map +1 -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/tsconfig.build.tsbuildinfo +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);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"puppeteer-plugin.js","sourceRoot":"","sources":["../../src/puppeteer/puppeteer-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAM5C,OAAO,EAAE,aAAa,EAAE,MAAM,uCAAuC,CAAC;AACtE,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"puppeteer-plugin.js","sourceRoot":"","sources":["../../src/puppeteer/puppeteer-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAM5C,OAAO,EAAE,aAAa,EAAE,MAAM,uCAAuC,CAAC;AACtE,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAG5D,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AAEnC,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAEhE,MAAM,gBAAgB,GAAG,iBAAiB,CAAC;AAE3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AmB,CAAC,IAAI,CAAC,CAAC;IACzC,CAAC;IAES,KAAK,CAAC,wBAAwB,CACpC,cAKC;QAED;;;;;;;;;;;;;;;;;;;;;;;;UAwBE;IACN,CAAC;IAES,uBAAuB,CAC7B,cAKC;QAED,OAAO,IAAI,CAAC;IAChB,CAAC;CACJ"}
|
|
@@ -0,0 +1,173 @@
|
|
|
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
|
+
* @internal
|
|
37
|
+
*/
|
|
38
|
+
export interface RemoteConnection {
|
|
39
|
+
/** Resolves the endpoint for a single browser launch. The `token` identifies the session for release. */
|
|
40
|
+
resolve(options?: {
|
|
41
|
+
proxyUrl?: string;
|
|
42
|
+
}): Promise<{
|
|
43
|
+
url: string;
|
|
44
|
+
token: number;
|
|
45
|
+
}>;
|
|
46
|
+
/** Releases the remote session for `token`. Idempotent — safe to call from both `close()` and `kill()`. */
|
|
47
|
+
release(token: number): Promise<void>;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Per-plugin remote connection parameters, passed to {@link BrowserPlugin.useRemoteConnection}.
|
|
51
|
+
* The endpoint is supplied per-launch via {@link RemoteConnection}; these are the static connect()
|
|
52
|
+
* parameters (protocol, headers, timeouts, …).
|
|
53
|
+
*/
|
|
54
|
+
export interface RemoteConnectionParameters {
|
|
55
|
+
/**
|
|
56
|
+
* Playwright only: which protocol to connect with. `'cdp'` uses `connectOverCDP()` (the default),
|
|
57
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
58
|
+
* `'playwright'` uses `connect()` (Playwright's own WebSocket protocol). Ignored by Puppeteer.
|
|
59
|
+
*/
|
|
60
|
+
protocol?: 'cdp' | 'playwright';
|
|
61
|
+
/** Extra options forwarded to the library `connect()` / `connectOverCDP()` call (endpoint excluded). */
|
|
62
|
+
connectOptions?: Record<string, unknown>;
|
|
63
|
+
}
|
|
64
|
+
export interface RemoteBrowserPoolOptions {
|
|
65
|
+
/**
|
|
66
|
+
* The browser plugin(s) used to connect to the remote service — e.g. `new PlaywrightPlugin(playwright.chromium)`
|
|
67
|
+
* or `new PuppeteerPlugin(puppeteer)`. The pool configures them for remote connection; do not set a local
|
|
68
|
+
* `launchOptions` on them.
|
|
69
|
+
*/
|
|
70
|
+
browserPlugins: BrowserPlugin[];
|
|
71
|
+
/**
|
|
72
|
+
* The remote browser endpoint: a static URL, a function returning one per launch, or a
|
|
73
|
+
* {@link RemoteBrowserProvider} instance encapsulating a session create/release lifecycle.
|
|
74
|
+
*/
|
|
75
|
+
endpoint: RemoteBrowserEndpoint | RemoteBrowserProvider<any>;
|
|
76
|
+
/**
|
|
77
|
+
* Cleanup callback invoked when a browser closes, crashes, or the pool is destroyed. Receives the
|
|
78
|
+
* `context` returned by a function endpoint. Errors are caught and logged. Ignored when `endpoint`
|
|
79
|
+
* is a {@link RemoteBrowserProvider} (its own `release()` is used instead).
|
|
80
|
+
*/
|
|
81
|
+
release?: (info: {
|
|
82
|
+
endpoint: string;
|
|
83
|
+
context?: Record<string, unknown>;
|
|
84
|
+
}) => unknown;
|
|
85
|
+
/**
|
|
86
|
+
* Maximum number of remote browsers open at once. When reached, {@link RemoteBrowserPool.newPage|newPage}
|
|
87
|
+
* waits for a browser to close before connecting a new one. Set it to your service's concurrent-session limit
|
|
88
|
+
* to avoid `429` errors. Defaults to the {@link RemoteBrowserProvider.maxOpenBrowsers|provider's value}, or
|
|
89
|
+
* `Infinity`.
|
|
90
|
+
*/
|
|
91
|
+
maxOpenBrowsers?: number;
|
|
92
|
+
/** Static connect() parameters (Playwright protocol selection, headers, timeouts, …). */
|
|
93
|
+
connection?: RemoteConnectionParameters;
|
|
94
|
+
/** Extra {@link BrowserPool} options (lifecycle hooks, page limits, fingerprinting, …). */
|
|
95
|
+
browserPoolOptions?: Omit<BrowserPoolOptions, 'browserPlugins'> & BrowserPoolHooks<any, any, any>;
|
|
96
|
+
/** Fallback poll interval (ms) while waiting for a free browser slot. The wait is event-driven; this only bounds it. @default 500 */
|
|
97
|
+
slotPollIntervalMillis?: number;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* The remote-connection configuration a browser crawler accepts on its `remoteBrowser` option. It is the
|
|
101
|
+
* {@link RemoteBrowserPoolOptions} a user supplies *minus* the parts the crawler provides itself — the
|
|
102
|
+
* `browserPlugins` (the crawler builds the correct one for its browser) and `browserPoolOptions` (taken from
|
|
103
|
+
* the crawler's own `browserPoolOptions`). This is what makes the crawler path both terse and mismatch-proof.
|
|
104
|
+
*/
|
|
105
|
+
export type CrawlerRemoteBrowserOptions = Omit<RemoteBrowserPoolOptions, 'browserPlugins' | 'browserPoolOptions'>;
|
|
106
|
+
/**
|
|
107
|
+
* An {@link IBrowserPool} implementation for remote browser services.
|
|
108
|
+
*
|
|
109
|
+
* Unlike configuring a remote browser through a crawler's `launchContext`, this pool is the single owner
|
|
110
|
+
* of all remote-session concerns:
|
|
111
|
+
* - **endpoint resolution** — static URL, per-launch function, or {@link RemoteBrowserProvider};
|
|
112
|
+
* - **release lifecycle** — `release()` fires exactly once per session on close/crash/teardown (no leaks,
|
|
113
|
+
* no double-release);
|
|
114
|
+
* - **concurrency** — {@link RemoteBrowserPoolOptions.maxOpenBrowsers|maxOpenBrowsers} is enforced inside
|
|
115
|
+
* {@link RemoteBrowserPool.newPage|newPage}, which waits for a free slot rather than overshooting.
|
|
116
|
+
*
|
|
117
|
+
* The wrapped {@link BrowserPool} and its plugin only perform the library-specific `connect()` call.
|
|
118
|
+
*
|
|
119
|
+
* Pass an instance as the crawler's `browserPool` option:
|
|
120
|
+
*
|
|
121
|
+
* ```typescript
|
|
122
|
+
* import { PlaywrightPlugin, RemoteBrowserPool } from '@crawlee/browser-pool';
|
|
123
|
+
* import { PlaywrightCrawler } from 'crawlee';
|
|
124
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
125
|
+
* import playwright from 'playwright';
|
|
126
|
+
*
|
|
127
|
+
* const browserPool = new RemoteBrowserPool({
|
|
128
|
+
* browserPlugins: [new PlaywrightPlugin(playwright.chromium)],
|
|
129
|
+
* endpoint: 'wss://production-sfo.browserless.io?token=xxx',
|
|
130
|
+
* maxOpenBrowsers: 2,
|
|
131
|
+
* });
|
|
132
|
+
*
|
|
133
|
+
* const crawler = new PlaywrightCrawler({ browserPool });
|
|
134
|
+
* ```
|
|
135
|
+
*
|
|
136
|
+
* @category Browser management
|
|
137
|
+
*/
|
|
138
|
+
export declare class RemoteBrowserPool<Page = unknown> implements IBrowserPool<Page> {
|
|
139
|
+
/** The wrapped pool that performs the remote connections and serves pages. */
|
|
140
|
+
readonly browserPool: BrowserPool;
|
|
141
|
+
/** The wrapped pool viewed through the {@link IBrowserPool} contract (the bare type widens pages to `never`). */
|
|
142
|
+
private readonly pool;
|
|
143
|
+
private readonly registry;
|
|
144
|
+
private readonly slotPollIntervalMillis;
|
|
145
|
+
private readonly log;
|
|
146
|
+
/** Shared by all `newPage` callers waiting for a free slot, so they don't each register their own listeners. */
|
|
147
|
+
private _capacityChange?;
|
|
148
|
+
constructor(options: RemoteBrowserPoolOptions);
|
|
149
|
+
/** Maximum number of remote browsers that may be open at the same time. */
|
|
150
|
+
get maxOpenBrowsers(): number;
|
|
151
|
+
set maxOpenBrowsers(value: number);
|
|
152
|
+
/**
|
|
153
|
+
* Opens a new page, waiting first until {@link RemoteBrowserPoolOptions.maxOpenBrowsers|maxOpenBrowsers}
|
|
154
|
+
* allows it (either a new browser slot is free, or an active browser still has page capacity).
|
|
155
|
+
*/
|
|
156
|
+
newPage(options?: NewPageOptions): Promise<Page>;
|
|
157
|
+
closePage(page: Page, options?: {
|
|
158
|
+
error?: Error;
|
|
159
|
+
}): Promise<void>;
|
|
160
|
+
extractPageState(page: Page): Promise<PageState>;
|
|
161
|
+
injectPageState(page: Page, state: PageState): Promise<void>;
|
|
162
|
+
/** Closes all browsers, releases any still-open remote sessions, and tears down the wrapped pool. */
|
|
163
|
+
destroy(): Promise<void>;
|
|
164
|
+
/** Resolves once the wrapped pool can serve another page without exceeding `maxOpenBrowsers`. */
|
|
165
|
+
private _waitForFreeSlot;
|
|
166
|
+
/**
|
|
167
|
+
* Resolves on the next browser-retired / page-closed event, or after `slotPollIntervalMillis`. All
|
|
168
|
+
* concurrently-waiting `newPage` calls share a single promise (and a single pair of event listeners)
|
|
169
|
+
* per tick, so a fleet of saturated callers doesn't fan out into N listener pairs on the pool.
|
|
170
|
+
*/
|
|
171
|
+
private _nextCapacityChange;
|
|
172
|
+
}
|
|
173
|
+
//# sourceMappingURL=remote-browser-pool.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"remote-browser-pool.d.ts","sourceRoot":"","sources":["../src/remote-browser-pool.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAG9E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,KAAK,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAE9E,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAErE;;;GAGG;AACH,MAAM,WAAW,sBAAsB;IACnC,8CAA8C;IAC9C,GAAG,EAAE,MAAM,CAAC;IACZ,iFAAiF;IACjF,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACrC;AAED;;;;;;GAMG;AACH,MAAM,MAAM,qBAAqB,GAC3B,MAAM,GACN,CAAC,CAAC,OAAO,CAAC,EAAE;IAAE,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAE,KAAK,MAAM,GAAG,sBAAsB,GAAG,OAAO,CAAC,MAAM,GAAG,sBAAsB,CAAC,CAAC,CAAC;AAExH;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,gBAAgB;IAC7B,yGAAyG;IACzG,OAAO,CAAC,O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;;;GA8BG;AACH,qBAAa,iBAAiB,CAAC,IAAI,GAAG,OAAO,CAAE,YAAW,YAAY,CAAC,IAAI,CAAC;IACxE,8EAA8E;IAC9E,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC;IAElC,oHAAoH;IACpH,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAqB;IAE1C,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAwB;IACjD,OAAO,CAAC,QAAQ,CAAC,sBAAsB,CAAS;IAChD,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAgB;IAEpC,gHAAgH;IAChH,OAAO,CAAC,eAAe,CAAC,CAAgB;gBAE5B,OAAO,EAAE,wBAAwB;IAgD7C,2EAA2E;IAC3E,IAAI,eAAe,IAAI,MAAM,CAE5B;IAED,IAAI,eAAe,CAAC,KAAK,EAAE,MAAM,EAEhC;IAED;;;OAGG;IACG,OAAO,CAAC,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAKhD,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,KAAK,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAIjE,gBAAgB,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,SAAS,CAAC;IAIhD,eAAe,CAAC,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC;IAIlE,qGAAqG;IAC/F,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAM9B,iGAAiG;YACnF,gBAAgB;IAM9B;;;;OAIG;IACH,OAAO,CAAC,mBAAmB;CAkB9B"}
|
|
@@ -0,0 +1,192 @@
|
|
|
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
|
+
endpoint;
|
|
11
|
+
onRelease;
|
|
12
|
+
log;
|
|
13
|
+
sessions = new Map();
|
|
14
|
+
nextToken = 0;
|
|
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
|
+
}
|
|
192
|
+
//# sourceMappingURL=remote-browser-pool.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"remote-browser-pool.js","sourceRoot":"","sources":["../src/remote-browser-pool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,cAA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