-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbrowser.ts
94 lines (76 loc) · 2.43 KB
/
browser.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
import * as net from 'net';
import * as playwright from 'playwright';
import { getBrowserType, getLaunchOptions } from './utils';
import { BROWSER_SERVER_TIMEOUT } from './constants';
interface BrowserInstance {
[endPoint: string]: {
server: playwright.BrowserServer;
timer?: any;
browserType: string;
guid: string;
};
}
class BrowserServer {
instances: BrowserInstance = {};
async launchServer(url: string, socket: net.Socket) {
const browserType = getBrowserType(url);
console.log(`\n\nLaunching ${browserType}...`);
const server = await playwright[browserType].launchServer(
getLaunchOptions(url),
);
if (!server) return null;
const endPoint = server.wsEndpoint();
const guid = /((\w{4,12}-?)){5}/.exec(endPoint)[0];
this.instances[endPoint] = {
server,
browserType,
guid,
};
socket.on('close', async () => {
await this.kill(server);
});
console.log(`${browserType} launched (${guid}).`);
const timeout =
process.env[BROWSER_SERVER_TIMEOUT] &&
Number.parseInt(process.env[BROWSER_SERVER_TIMEOUT]);
if (timeout) {
console.log('Browser will close in ' + timeout + ' seconds.');
}
this.checkForTimeout(server, timeout);
return server;
}
getWsEndpoint(server: playwright.BrowserServer) {
return server.wsEndpoint();
}
checkForTimeout(server: playwright.BrowserServer, timeout?: number) {
if (!timeout) {
return;
}
timeout = timeout * 1000;
this.instances[server.wsEndpoint()].timer = setTimeout(() => {
console.log('Timeout reached, shuting down the browser server.');
this.kill(server);
}, timeout);
}
async kill(server: playwright.BrowserServer) {
const endPoint = server.wsEndpoint();
//if instance is undefined it means already in process of terminating
if (!this.instances[endPoint]) return;
const { browserType, guid } = this.instances[endPoint];
clearTimeout(this.instances[endPoint].timer);
console.log(`Terminating ${browserType} (${guid}) ...`);
delete this.instances[endPoint];
await server.close();
console.log(`${browserType} terminated (${guid}).`);
}
async killAll() {
const { instances } = this;
const keys = Object.keys(instances);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const info = instances[key];
await this.kill(info.server);
}
}
}
export { BrowserServer };