-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathserver.mjs
451 lines (393 loc) · 12.6 KB
/
server.mjs
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
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import del from 'del';
import fs from 'fs';
import util from 'util';
import express from 'express';
import fetch from 'node-fetch';
import firebaseAdmin from 'firebase-admin';
import puppeteer from 'puppeteer';
import {runners, DEFAULT_SCREENSHOT_VIEWPORT} from './public/tools.mjs';
import * as bitly from './public/bitly.mjs';
/* eslint-disable no-unused-vars */
import * as LHTool from './tools/lighthouse.mjs';
import * as TMSTool from './tools/tms.mjs';
import * as WPTTool from './tools/wpt.mjs';
import * as PSITool from './tools/psi.mjs';
/* eslint-enable no-unused-vars */
const CS_BUCKET = 'perf-sandbox.appspot.com';
const firebaseApp = firebaseAdmin.initializeApp({
// credential: firebaseAdmin.credential.applicationDefault(),
credential: firebaseAdmin.credential.cert(
JSON.parse(fs.readFileSync('./serviceAccount.json'))),
storageBucket: CS_BUCKET,
});
const db = firebaseApp.firestore();
db.settings({timestampsInSnapshots: true});
const app = express();
// Async route handlers are wrapped with this to catch rejected promise errors.
const catchAsyncErrors = (fn) => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
// eslint-disable-next-line
function errorHandler(err, req, res, next) {
console.error(err.message);
// if (res.headersSent) {
// return next(err);
// }
res.write(`data: "${JSON.stringify({
errors: `Error running your code. ${err}`,
})}"\n\n`);
res.status(500).end(); // send({errors: `Error running your code. ${err}`});
}
/**
* Creates an HTML page from the results and saves it to disk.
* @param {!Array<{tool: string, screenshot: !Buffer}>} results
* @return {string} HTML of page.
*/
function createHTML(results) {
const body = results.map(r => {
const tool = runners[r.tool];
const resultsLink = r.resultsUrl ? `
<p class="reportlink">
Results available at: <a href="${r.resultsUrl}" target="_blank">${r.resultsUrl}</a>
</p>` : '';
return `
<h3 class="title">${tool.name} results</h3>
<div>
<div class="desc">
About this tool: ${tool.desc}
Learn more at <a href="${tool.url}" target="_blank">${tool.url}</a>
</div>
${resultsLink}
</div>
<div class="screenshot">
<img src="data:img/png;base64,${r.screenshot.toString('base64')}">
</div>
`;
}).join('');
const html = `
<html>
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Google+Sans:300,400">
<style>
:root {
--orange: rgb(255, 108, 0);
--purple: #4768FD;
--yellow: #FCD230;
--green: #31E7B6;
--padding: 16px;
}
body {
/*background: url(https://storage.googleapis.com/io-2018.appspot.com/v1/hashtag.gif) no-repeat 100% 100%;
background-size: 25%;*/
font-family: 'Google Sans', 'Product Sans', sans-serif;
font-weight: 300;
color: #202124;
padding: 16px;
margin: 0;
}
h1, h2, h3, h4 {
font-weight: inherit;
margin: 0;
}
h1 {
color: var(--purple);
}
a {
color: var(--purple);
text-decoration: none;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
padding-bottom: var(--padding);
border-bottom: 4px solid var(--green);
}
header img {
height: 50px;
}
header .date {
margin-top: 4px;
opacity: 0.6;
}
.title {
color: var(--orange);
margin-top: calc(var(--padding) * 2);
}
.reportlink, .desc {
font-size: 14px;
opacity: 0.6;
}
.reportlink {
font-style: italic;
}
.desc {
margin-bottom: var(--padding);
margin-top: 4px;
}
.screenshot {
/*page-break-after: always;*/
}
.screenshot img {
max-width: 100%;
max-height: 90%;
border: 1px solid #eee;
}
</style>
</head>
<body>
<header>
<div>
<h1>Performance Tools Sandbox Report</h1>
<h4 class="date">${(new Date()).toLocaleDateString()}</h4>
</div>
<div>
<img src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png">
</div>
</header>
${body}
</body>
</html>
`;
return html;
}
/**
* Compiles a PDF of the tool screenshot results.
* @param {string} origin Origin of the server.
* @param {!Browser} browser
* @param {string} filename
* @return {!Promise<{buffer: !Buffer, url: string, path: string}>} Created PDF metdata.
*/
async function createPDF(origin, browser, filename) {
const page = await browser.newPage();
await page.setViewport(DEFAULT_SCREENSHOT_VIEWPORT);
await page.emulateMedia('screen');
await page.goto(`${origin}/${filename}`, {waitUntil: 'load'});
const pdfFilename = `${Date.now()}.${filename.replace('.html', '.pdf')}`;
const path = `./tmp/${pdfFilename}`;
const buffer = await page.pdf({
path,
margin: {top: '16px', right: '16px', bottom: '16px', left: '16px'},
});
await page.close();
return {
buffer,
url: `${origin}/${pdfFilename}`,
path,
filename: pdfFilename,
};
}
/**
* Uploads the PDF to Firebase cloud storage.
* @param {string} pdfURL URL of the PDF to upload to cloud storage.
* @return {string} URL of the file in cloud storage.
*/
async function uploadPDF(pdfURL) {
try {
const bucket = firebaseAdmin.storage().bucket();
// await file.makePublic();
// const [metadata] = await file.getMetadata();
// return metadata.mediaLink;
const parts = pdfURL.split('/');
const filename = parts[parts.length - 1];
// eslint-disable-next-line
const [file, response] = await bucket.upload(pdfURL, {
public: true,
gzip: true,
validation: false,
});
return `https://storage.googleapis.com/${CS_BUCKET}/${filename}`;
} catch (err) {
console.error('Error uploading PDF:', err);
}
return null;
}
/**
*
* @param {string} url
* @param {!Array<string>} tools
* @param {!Arrray<!Object>} lhr
* @return {DocumentRef}
*/
function logToFirestore(url, tools, lhr) {
const data = {
url,
tools: {
LH: tools.includes('LH'),
PSI: tools.includes('PSI'),
WPT: tools.includes('WPT'),
},
createdAt: Date.now(),
};
if (lhr) {
data.lhr = {};
Object.values(lhr.categories).forEach(cat => {
data.lhr[cat.id] = cat.score;
});
}
return db.collection('runs').doc().set(data);
}
// app.use(function forceSSL(req, res, next) {
// const fromCron = req.get('X-Appengine-Cron');
// if (!fromCron && req.hostname !== 'localhost' && req.get('X-Forwarded-Proto') === 'http') {
// return res.redirect(`https://${req.hostname}${req.url}`);
// }
// next();
// });
app.use(function addRequestHelpers(req, res, next) {
req.getCurrentUrl = () => `${req.protocol}://${req.get('host')}${req.originalUrl}`;
req.getOrigin = () => {
let protocol = 'https';
if (req.hostname === 'localhost') {
protocol = 'http';
}
return `${protocol}://${req.get('host')}`;
};
next();
});
app.use(express.static('public', {extensions: ['html', 'htm']}));
app.use(express.static('tmp'));
app.use(express.static('node_modules'));
// app.use(function cors(req, res, next) {
// res.set('Access-Control-Allow-Origin', '*');
// // res.set('Content-Type', 'application/json;charset=utf-8');
// // res.set('Cache-Control', 'public, max-age=300, s-maxage=600');
// next();
// });
app.get('/run', catchAsyncErrors(async (req, res) => {
const url = req.query.url;
const origin = req.getOrigin();
let tools = req.query.tools ? req.query.tools.split(',') : [];
tools = tools.filter(tool => Object.keys(runners).includes(tool));
const headless = req.query.headless === 'false' ? false : true;
if (!tools.length) {
throw new Error('Please provide a tool ?tools=[LH,PSI,WPT,TMS,SS].');
}
if (!url) {
throw new Error('Please provide a URL.');
}
// Clear previous run screenshots.
const paths = await del(['tmp/*']); // eslint-disable-line
// Send headers for event-stream connection.
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'X-Accel-Buffering': 'no', // Forces GAE to keep connection open for event streaming.
});
// Check if URL exists before kicking off the tools.
// Attempt to fetch the user's URL.
try {
await fetch(url);
} catch (err) {
throw err;
}
const browser = await puppeteer.launch({
headless,
// executablePath: '/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary',
// dumpio: true,
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage'],
});
// If on Mac, use DPR=2 so screenshots are gorgeous.
DEFAULT_SCREENSHOT_VIEWPORT.deviceScaleFactor = process.platform === 'darwin' ? 2 : 1;
let lhr = null;
try {
const toolsToRun = tools.map(tool => {
console.info(`Started running ${tool}...`);
return eval(`${tool}Tool`).run(browser, url).then(async results => {
console.info(`Finished running ${tool}.`);
await util.promisify(fs.writeFile)(`./tmp/${tool}.html`, results.html);
if (results.lhr) {
lhr = results.lhr;
await util.promisify(fs.writeFile)(`./tmp/${tool}.json`, JSON.stringify(results.lhr));
}
console.info('Saving screenshot...');
await util.promisify(fs.writeFile)(`./tmp/${tool}.png`, results.screenshot);
const resultsUrl = results.resultsUrl || `/${tool}.html`;
res.write(`data: "${JSON.stringify({tool, resultsUrl})}"\n\n`);
// res.flush();
return results;
});
});
const results = await Promise.all(toolsToRun);
// Save HTML page of results and create PDF from it using Puppeteer.
console.info('Creating PDF...');
await util.promisify(fs.writeFile)('./tmp/results.html', createHTML(results));
const pdf = await createPDF(origin, browser, 'results.html');
console.info('Done.');
// Log url to file.
try {
util.promisify(fs.writeFile)('runs.txt', `${url},${tools}\n`, {flag: 'a'}); // async
} catch (err) {
console.warn(err);
}
// Log run to firestore.
try {
logToFirestore(url, tools, lhr);
} catch (err) {
console.warn(err);
}
res.write(`data: "${JSON.stringify({
completed: true,
viewURL: pdf.url,
})}"\n\n`);
return res.status(200).end();
} catch (err) {
throw err;
} finally {
await browser.close();
}
// res.status(200).send('Done');
}));
app.get('/share', catchAsyncErrors(async (req, res) => {
const pdfURL = req.query.pdf;
if (!pdfURL) {
throw new Error('PDF url missing.');
}
console.info('Uploading PDF to Cloud Storage...');
const gcsURL = await uploadPDF(pdfURL);
console.info('Done.');
console.info('Shortening URL...');
const bitlyResp = await bitly.shorten(gcsURL);
console.info('Done.');
res.status(200).send({
url: gcsURL,
shortUrl: bitlyResp.url.replace('http:', 'https:'),
});
}));
app.use(errorHandler);
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}. Press Ctrl+C to quit.`);
});
// Make sure node server process stops if we get a terminating signal.
/**
* @param {string} sig Signal string.
*/
function processTerminator(sig) {
if (typeof sig === 'string') {
process.exit(1);
}
console.log('%s: Node server stopped.', Date(Date.now()));
}
[
'SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT', 'SIGBUS',
'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM',
].forEach(sig => {
process.once(sig, () => processTerminator(sig));
});