Files
speedboard/runner.js

86 lines
2.8 KiB
JavaScript
Raw Normal View History

import { spawn } from 'child_process';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { existsSync } from 'fs';
const __dirname = dirname(fileURLToPath(import.meta.url));
const LOCAL_BIN = join(__dirname, '..', 'sitespeed.io', 'bin', 'sitespeed.js');
// Shell-escape a single argument (single-quote wrapping)
function q(arg) {
return `'${String(arg).replace(/'/g, "'\\''")}'`;
}
export function runTest(job, onLine) {
return new Promise((resolve, reject) => {
const outputFolder = join(__dirname, 'reports', job.id);
const isDocker = !!process.env.IN_DOCKER;
const sitespeedArgs = [
job.url,
'--browser', job.browser,
'-n', String(job.runs),
'--outputFolder', outputFolder,
'--json',
'--sustainable.enable',
'--axe.enable',
'--coach',
];
if (job.mobile) sitespeedArgs.push('--mobile');
if (isDocker) {
sitespeedArgs.push('--browsertime.chrome.args', 'no-sandbox');
sitespeedArgs.push('--browsertime.chrome.args', 'disable-dev-shm-usage');
sitespeedArgs.push('--browsertime.chrome.args', 'disable-gpu');
}
const env = { ...process.env, DISPLAY: process.env.DISPLAY || ':99' };
let child;
if (isDocker) {
// In Docker, sitespeed.io is on PATH but execSync can't see it from Node's
// limited environment. Use 'sh -c' so the full shell PATH is used.
const shellCmd = ['sitespeed.io', ...sitespeedArgs].map(q).join(' ');
onLine(`[runner] sh -c ${shellCmd.slice(0, 120)}...`);
onLine(`[runner] DISPLAY=${env.DISPLAY}`);
child = spawn('sh', ['-c', shellCmd], { cwd: __dirname, env });
} else {
if (!existsSync(LOCAL_BIN)) {
return reject(new Error(
`Local sitespeed.io not found at ${LOCAL_BIN}\n` +
`Run: cd /home/malin/c0ding/sitespeed.io && npm install`
));
}
onLine(`[runner] node ${LOCAL_BIN.slice(-40)}...`);
child = spawn('node', [LOCAL_BIN, ...sitespeedArgs], { cwd: __dirname, env });
}
const allLines = [];
child.stdout.on('data', (data) => {
const lines = data.toString().split('\n').filter(Boolean);
for (const line of lines) { allLines.push(line); onLine(line); }
});
child.stderr.on('data', (data) => {
const lines = data.toString().split('\n').filter(Boolean);
for (const line of lines) { allLines.push('[stderr] ' + line); onLine('[stderr] ' + line); }
});
child.on('close', (code) => {
if (code === 0) {
resolve(outputFolder);
} else {
const tail = allLines.slice(-20).join('\n');
reject(new Error(`sitespeed.io exited with code ${code}\n${tail}`));
}
});
child.on('error', (err) => {
reject(new Error(`Failed to spawn process: ${err.message}`));
});
});
}