-
Notifications
You must be signed in to change notification settings - Fork 684
/
puppeteer-provider.ts
706 lines (613 loc) · 19.7 KB
/
puppeteer-provider.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
import net from 'net';
import _ from 'lodash';
import { NodeVM } from 'vm2';
import { AsyncArray } from './async-array';
import { BrowserlessServer } from './browserless';
import * as chromeHelper from './chrome-helper';
import { PLAYWRIGHT_ROUTE } from './constants';
import { isVersionCompatible } from './playwright-provider';
import { Queue } from './queue';
import {
IChromeServiceConfiguration,
ILaunchOptions,
IBrowser,
IRunHTTP,
IDone,
IJob,
IHTTPRequest,
} from './types.d';
import * as utils from './utils';
const sysdebug = utils.getDebug('system');
const jobdebug = utils.getDebug('job');
const jobdetaildebug = utils.getDebug('jobdetail');
export class PuppeteerProvider {
private readonly server: BrowserlessServer;
private config: IChromeServiceConfiguration;
private chromeSwarm: AsyncArray<IBrowser>;
private queue: Queue;
constructor(
config: IChromeServiceConfiguration,
server: BrowserlessServer,
queue: Queue,
) {
this.config = config;
this.server = server;
this.queue = queue;
this.chromeSwarm = new AsyncArray();
}
get keepChromeInstance() {
return (
this.config.keepAlive &&
this.config.prebootChrome &&
this.chromeSwarm.length < this.queue.concurrencySize
);
}
public setSwarm(swarm: IBrowser[] | void) {
this.chromeSwarm = new AsyncArray();
if (!swarm) return;
swarm.forEach((browser) => {
this.chromeSwarm.push(browser);
});
}
public async startChromeInstances() {
if (this.config.prebootChrome) {
const initialInstances =
this.config.prebootQuantity || this.config.maxConcurrentSessions;
sysdebug(
`Starting chrome swarm: ${initialInstances} chrome instances starting`,
);
if (initialInstances > 10) {
process.setMaxListeners(this.config.maxConcurrentSessions + 3);
}
const launching = [...Array(initialInstances)].map(() =>
this.launchChrome(chromeHelper.defaultLaunchArgs, true),
);
const swarm = await Promise.all(launching);
this.setSwarm(swarm);
return swarm;
}
this.setSwarm();
return Promise.resolve();
}
public proxyWebRequestToPort({
req,
res,
port,
}: {
req: any;
res: any;
port: string;
}) {
const target = `http://127.0.0.1:${port}`;
this.server.proxy.web(req, res, { target }, (err) => {
sysdebug('Error proxying static debugger asset request', err.message);
});
}
public proxyWsRequestToPort({
req,
socket,
head,
port,
}: {
req: any;
socket: any;
head: any;
port: string;
}) {
const target = `ws://127.0.0.1:${port}`;
// Strip tokens/query-params since they break chrome
req.url = req.parsed.pathname || '';
this.server.proxy.ws(req, socket, head, { target });
}
public async runHTTP({
code,
context,
req,
res,
before,
after,
detached = false,
headless,
flags,
ignoreDefaultArgs = false,
builtin = this.config.functionBuiltIns,
external = this.config.functionExternals,
envVars = this.config.functionEnvVars,
}: IRunHTTP) {
const jobId = utils.id();
const trackingId = req.query.trackingId;
jobdebug(
`${jobId}: ${req.url}: Inbound HTTP request. Context: ${JSON.stringify(
context,
)}`,
);
if (!this.queue.hasCapacity) {
jobdebug(
`${jobId}: Too many concurrent and queued requests, rejecting with 429.`,
);
return this.server.rejectReq({
req,
res,
code: 429,
message: `Too Many Requests`,
metricType: 'rejected',
hook: this.server.capacityFullHook,
});
}
if (await this.queue.overloaded()) {
jobdebug(`${jobId}: Server under heavy load, rejecting with 503.`);
return this.server.rejectReq({
req,
res,
code: 503,
message: `Server under load`,
metricType: 'unhealthy',
hook: this.server.sessionCheckFailHook,
});
}
const vm = new NodeVM({
require: {
builtin,
external,
root: './node_modules',
},
env: _.pick(process.env, envVars),
});
const handler: (args: any) => Promise<any> = vm.run(
code,
`browserless-function-${jobId}.js`,
);
const earlyClose = () => {
if (detached) {
return;
}
jobdebug(
`${job.id}: Function terminated prior to execution removing from queue`,
);
this.removeJob(job);
};
const job: IJob = Object.assign(
(done: IDone) => {
const doneOnce = _.once((err?: Error) => {
if (job.browser) {
job.browser.removeListener('disconnected', doneOnce);
job.browser._browserProcess.removeListener('exit', doneOnce);
}
done(err);
});
const debug = (message: string) => jobdebug(`${job.id}: ${message}`);
debug(`Getting browser.`);
const urlOpts = chromeHelper.convertUrlParamsToLaunchOpts(req);
const launchOpts = {
...urlOpts,
args: [...(urlOpts.args || []), ...(flags || [])],
headless:
typeof headless !== 'undefined' ? headless : urlOpts.headless,
ignoreDefaultArgs,
};
this.getChrome(launchOpts)
.then(async (browser) => {
jobdetaildebug(`${job.id}: Executing function.`);
if (detached) {
jobdebug(`${jobId}: Function is detached, resolving request.`);
res.json({ id: jobId, trackingId });
}
const page = await this.newPage(browser);
let beforeArgs = {};
page.on('error', (error: Error) => {
debug(`Error on page: ${error.message}`);
if (!res.headersSent) {
res.status(400).send(error.message);
}
doneOnce(error);
});
if (before) {
debug(`Running before hook`);
beforeArgs = await before({ page, browser, debug, jobId, code });
debug(`Before hook done!`);
}
job.browser = browser;
req.removeListener('close', earlyClose);
browser.once('disconnected', doneOnce);
browser._browserProcess.once('exit', doneOnce);
req.once('close', () => {
if (detached) {
return;
}
debug(`Request terminated during execution, closing`);
doneOnce();
});
return Promise.resolve(
handler({
...beforeArgs,
browser,
context,
page,
timeout: this.config.connectionTimeout,
}),
).then(async ({ data, type = 'text/plain', headers = {} } = {}) => {
// If there's a specified "after" hook allow that to run
if (after) {
return after({
...beforeArgs,
browser,
code,
debug,
done: doneOnce,
jobId,
page,
req,
res,
});
}
debug(`Function complete, cleaning up.`);
// If we've already responded (detached/error) we're done
if (res.headersSent) {
return doneOnce();
}
res.type(type);
if (headers) {
Object.keys(headers).forEach((key) => {
const hasValue =
Object.prototype.hasOwnProperty.call(headers, key) &&
headers[key] !== null &&
headers[key] !== undefined &&
headers[key] !== '';
if (hasValue) {
res.setHeader(key, headers[key]);
}
});
}
if (Buffer.isBuffer(data)) {
res.end(data, 'binary');
} else if (type.includes('json')) {
res.json(data);
} else {
res.send(data);
}
return doneOnce();
});
})
.catch((error) => {
if (!res.headersSent) {
res.status(400).send(error.message);
}
debug(`Function errored, stopping Chrome: ${error.stack}`);
doneOnce(error);
});
},
{
browser: null,
close: () => this.cleanUpJob(job),
id: jobId,
onTimeout: () => {
if (!res.headersSent) {
jobdebug(`${job.id}: Function has timed-out, sending 408.`);
return res.status(408).send('browserless function has timed-out');
}
jobdebug(
`${job.id}: Function has timed-out but headers already sent...`,
);
},
req,
start: Date.now(),
},
);
req.once('close', earlyClose);
this.addJob(job);
}
public async runWebSocket(
req: IHTTPRequest,
socket: net.Socket,
head: Buffer,
) {
const jobId = utils.id();
const parsedUrl = req.parsed;
const route = parsedUrl.pathname || '/';
jobdebug(`${jobId}: ${req.url}: Inbound WebSocket request.`);
// Causes issues with browsers running puppeteer to connect
delete req.headers.origin;
// Catch actual running pages and route them appropriately
if (
route.includes('/devtools/page') &&
!route.includes(utils.jsonProtocolPrefix)
) {
const session = await chromeHelper.findSessionForPageUrl(route);
if (session && session.port) {
const { port } = session;
return this.proxyWsRequestToPort({ req, socket, head, port });
}
return this.server.rejectSocket({
header: `HTTP/1.1 404 Not Found`,
message: `Couldn't load session for ${route}`,
req,
socket,
});
}
if (route.includes('/devtools/browser')) {
const session = await chromeHelper.findSessionForBrowserUrl(route);
if (session && session.port) {
// refresh timeout if necessary
if (req.parsed.query && req.parsed.query.keepalive) {
const browser = await chromeHelper.getBrowserBySession(session)!;
if (browser) {
browser._keepaliveTimeout &&
clearTimeout(browser._keepaliveTimeout);
jobdebug(
`Refreshing keep-alive flag, closing in ${req.parsed.query.keepalive}ms`,
);
browser._keepaliveTimeout = global.setTimeout(
() => this.stopChromeProcess(browser),
Number(req.parsed.query.keepalive) || this.config.connectionTimeout,
);
}
}
const { port } = session;
return this.proxyWsRequestToPort({ req, socket, head, port });
}
return this.server.rejectSocket({
header: `HTTP/1.1 404 Not Found`,
message: `Couldn't load session for ${route}`,
req,
socket,
});
}
if (!this.queue.hasCapacity) {
jobdebug(
`${jobId}: Too many concurrent and queued requests, rejecting with 429.`,
);
return this.server.rejectSocket({
header: `HTTP/1.1 429 Too Many Requests`,
message: `Too Many Requests`,
metricType: 'rejected',
hook: this.server.capacityFullHook,
req,
socket,
});
}
if (await this.queue.overloaded()) {
jobdebug(`${jobId}: Server under heavy load, rejecting with 503.`);
return this.server.rejectSocket({
header: `HTTP/1.1 503 Server under load`,
message: `Server under heavy load, try again later`,
hook: this.server.sessionCheckFailHook,
metricType: 'unhealthy',
req,
socket,
});
}
const opts = chromeHelper.convertUrlParamsToLaunchOpts(req);
// If debug code is submitted, sandbox it in
// its own process to prevent infinite/runaway scripts
const handler = (done: IDone) => {
const launchPromise = this.getChrome(opts);
if (
opts.playwright &&
opts.playwrightVersion &&
!isVersionCompatible(opts.playwrightVersion)
) {
jobdebug(
`Version '${opts.playwrightVersion}' is not supported. Using default version.`,
);
}
if (opts.playwright) {
jobdebug(
`${job.id}: Versioning playwright to '${opts.playwrightVersion}'`,
);
}
jobdebug(`${job.id}: Getting browser.`);
const doneOnce = _.once((err) => {
if (job.browser) {
job.browser.removeListener('disconnected', doneOnce);
job.browser._browserProcess.removeListener('exit', doneOnce);
}
done(err);
});
launchPromise
.then(async (browser) => {
jobdebug(`${job.id}: Starting session.`);
const browserWsEndpoint = browser._wsEndpoint;
job.browser = browser;
// Cleanup prior listener + listen for socket and browser close
// events just in case something doesn't trigger
socket.removeListener('close', earlyClose);
socket.once('close', doneOnce);
browser.once('disconnected', doneOnce);
browser._browserProcess.once('exit', doneOnce);
if (route.includes(PLAYWRIGHT_ROUTE) && browser._browserServer) {
const playwrightRoute = browser._browserServer.wsEndpoint();
jobdebug(
`${job.id}: Proxying request to /playwright route: ${playwrightRoute}.`,
);
req.url = '';
return playwrightRoute;
}
if (!route.includes('/devtools/page')) {
jobdebug(
`${job.id}: Proxying request to /devtools/browser route: ${browserWsEndpoint}.`,
);
req.url = route;
return browserWsEndpoint;
}
const page: any = await browser.newPage();
const port = browser._parsed.port;
const pageLocation = `/devtools/page/${page._target._targetId}`;
req.url = pageLocation;
return `ws://127.0.0.1:${port}`;
})
.then((target) =>
this.server.proxy.ws(req, socket, head, {
target,
changeOrigin: true,
}),
)
.catch((error) => {
jobdebug(
error,
`${job.id}: Issue launching Chrome or proxying traffic, failing request`,
);
doneOnce(error);
socket.end();
});
};
const jobProps = {
browser: null,
close: () => this.cleanUpJob(job),
id: jobId,
onTimeout: () => {
jobdebug(`${job.id}: Job has timed-out, closing the WebSocket.`);
socket.end();
},
req,
start: Date.now(),
};
const job: IJob = Object.assign(handler, jobProps);
const earlyClose = () => {
jobdebug(
`${job.id}: Websocket closed early, removing from queue and closing.`,
);
this.removeJob(job);
};
socket.once('close', earlyClose);
this.addJob(job);
}
public async kill() {
sysdebug(`Kill received, forcing queue and swarm to shutdown`);
await Promise.all([
...this.queue.map(async (job: IJob) => job.close && job.close()),
...this.chromeSwarm.map(async (browser) =>
chromeHelper.closeBrowser(browser),
),
this.queue.removeAllListeners(),
]);
sysdebug(`Kill complete.`);
}
public async close() {
sysdebug(`Closing queue and swarm gracefully`);
if (this.queue.length) {
sysdebug('Jobs are running, waiting for completion.');
await new Promise((resolve) => {
this.queue.on('end', () => {
sysdebug(`All jobs complete, proceeding with close`);
resolve(null);
});
});
}
if (this.chromeSwarm.length) {
sysdebug('Instances of chrome in swarm, closing');
await Promise.all(
this.chromeSwarm.map(async (browser) =>
chromeHelper.closeBrowser(browser),
),
);
}
return Promise.resolve();
}
private removeJob(job: IJob) {
jobdebug(`${job.id}: Removing job from queue and cleaning up.`);
job.close && job.close();
this.queue.remove(job);
}
private addJob(job: IJob) {
jobdebug(`${job.id}: Adding new job to queue.`);
this.queue.add(job);
}
private async cleanUpJob(job: IJob) {
const { browser } = job;
jobdebug(`${job.id}: Cleaning up job`);
if (!browser) {
jobdebug(`${job.id}: No browser to cleanup, exiting`);
return;
}
const closeChrome = async () => {
jobdebug(`${job.id}: Browser not needed, closing`);
this.stopChromeProcess(browser);
jobdebug(`${job.id}: Browser cleanup complete.`);
};
if (this.keepChromeInstance) {
const timeAlive = Date.now() - browser._startTime;
jobdebug(`${job.id}: Browser has been alive for ${timeAlive}ms`);
if (timeAlive <= this.config.chromeRefreshTime) {
jobdebug(`${job.id}: Pushing browser back into swarm, clearing pages`);
const [blank, ...pages] = await browser.pages();
pages.forEach((page) => page.close());
blank && blank.goto('about:blank');
jobdebug(`${job.id}: Cleanup done, pushing into swarm.`);
return this.chromeSwarm.push(browser);
}
}
// If it's marked as "keepalive", set a timer to kill it, and if we
// see it again reset that timer, otherwise proceed with closing.
if (browser._keepalive) {
browser._keepaliveTimeout && clearTimeout(browser._keepaliveTimeout);
jobdebug(
`${job.id}: Browser marked as keep-alive, closing in ${browser._keepalive}ms`,
);
browser._keepaliveTimeout = global.setTimeout(
closeChrome,
browser._keepalive,
);
return;
}
closeChrome();
}
private async stopChromeProcess(browser: IBrowser) {
chromeHelper.closeBrowser(browser);
if (this.config.prebootChrome && browser._prebooted) {
sysdebug(`Adding back Chrome swarm`);
const newBrowser = await this.launchChrome(
chromeHelper.defaultLaunchArgs,
true,
);
return this.chromeSwarm.push(newBrowser);
}
}
private async getChrome(opts: ILaunchOptions): Promise<IBrowser> {
const canUseChromeSwarm =
this.config.prebootChrome &&
utils.canPreboot(opts, chromeHelper.defaultLaunchArgs);
sysdebug(
canUseChromeSwarm
? `Waiting pre-booted chrome instance`
: 'Generating fresh chrome browser',
);
const browser = canUseChromeSwarm
? await this.chromeSwarm.get()
: await this.launchChrome(opts, false);
sysdebug(`Got chrome instance`);
browser._trackingId = opts.trackingId || null;
browser._keepalive = opts.keepalive || null;
browser._blockAds = opts.blockAds;
browser._pauseOnConnect = opts.pauseOnConnect;
return browser;
}
private async launchChrome(
opts: ILaunchOptions,
isPreboot = false,
retries = 1,
): Promise<IBrowser> {
const start = Date.now();
return chromeHelper
.launchChrome(opts, isPreboot)
.then((chrome) => {
sysdebug(`Chrome launched ${Date.now() - start}ms`);
return chrome;
})
.catch((error) => {
if (retries > 0) {
const nextRetries = retries - 1;
sysdebug(error, `Issue launching Chrome, retrying ${retries} times.`);
return this.launchChrome(opts, isPreboot, nextRetries);
}
sysdebug(error, `Issue launching Chrome, retries exhausted.`);
throw error;
});
}
private async newPage(browser: IBrowser) {
if (this.config.functionEnableIncognitoMode) {
const browserContext = await browser.createIncognitoBrowserContext();
return await browserContext.newPage();
}
return browser.newPage();
}
}