chrome-aws-lambda + lighthouse всегда приводит к ошибке: подключите ECONNREFUSED 127.0.0.1:9222

Dockerfile

FROM public.ecr.aws/lambda/nodejs:12

COPY index.js package.json /var/task/

RUN npm install --save-prod

CMD [ "index.handler" ]

package.json

{
    "name": "lighthouse2",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "author": "",
    "license": "ISC",
    "dependencies": {
        "chrome-aws-lambda": "^7.0.0",
        "puppeteer-core": "^7.0.4",
        "lighthouse": "^7.1.0"
    }
}

index.js

const chromium = require('chrome-aws-lambda');
const lighthouse = require('lighthouse');

exports.handler = async(event, context, callback) => {
    let result = null;
    let chrome = null;

    try {
        console.log('Launching puppeteer chromium');
        let chromiumOptions = {
            args: chromium.args,
            defaultViewport: chromium.defaultViewport,
            executablePath: await chromium.executablePath,
            headless: chromium.headless,
            ignoreHTTPSErrors: true
        };
        const command = await chromium.puppeteer.launch(chromiumOptions)
            .then((chrome) => {
                console.log('launch.then called');
                return {
                    chrome,
                    async start() {
                        console.log('function start called');

                        const options = {logLevel: 'info', onlyCategories: ['performance']};
                        const runnerResult = await lighthouse('https://www.example.com', options)

                        console.log('Report is done for', runnerResult.lhr.finalUrl);
                        console.log('Performance score was', runnerResult.lhr.categories.performance.score * 100);

                        await chrome.kill();
                    }
                }
            })
            .catch(err => console.error(err));

        console.log('Launched.');

        return await command.start();
    } catch (error) {
        console.log(error);
        return callback(error);
    } finally {
        if (chrome !== null) {
            await chrome.close();
        }
    }

    return callback(null, result);
};

Создайте тестовый образ Docker:

docker build -t lighthouse2 .; docker run --rm -p 9000:8080 lighthouse2

Протестируйте обработчик (в другом терминале)

curl -XPOST "http://localhost:9000/2015-03-31/functions/function/invocations" -d '{"payload":"hello world!"}'

Ожидаемый результат:

Lighthouse работает, и я могу прочитать свойства отчета.

Фактический результат:

Когда Lighthouse действительно работает, я получаю следующее, какие бы настройки я ни пробовал:

Wed, 17 Feb 2021 23:24:18 GMT status Connecting to browser
Wed, 17 Feb 2021 23:24:18 GMT CriConnection:warn Cannot create new tab; reusing open tab.
Wed, 17 Feb 2021 23:24:18 GMT status Disconnecting from browser...
Wed, 17 Feb 2021 23:24:18 GMT CriConnection:error sendRawMessage() was called without an established connection.
Wed, 17 Feb 2021 23:24:18 GMT GatherRunner disconnect:error sendRawMessage() was called without an established connection.
} port: 9222127.0.0.1',,terConnect [as oncomplete] (net.js:1144:16) {   INFO    Error: connect ECONNREFUSED 127.0.0.1:9222
2021-02-17T23:24:18.145Z        8cd07390-6550-40b7-87a5-c162fc55eedf    ERROR   Invoke Error    {"errorType":"Error","errorMessage":"connect ECONNREFUSED 127.0.0.1:9222","code":"ECONNREFUSED","errno":"ECONNREFUSED","syscall":"connect","address":"127.0.0.1","port":9
222,"stack":["Error: connect ECONNREFUSED 127.0.0.1:9222","    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16)"]

person Tyler V.    schedule 17.02.2021    source источник


Ответы (1)


Мне удалось получить результат от Lighthouse. Благодаря твоему примеру

const lighthouse = require('lighthouse');
const chromium = require('chrome-aws-lambda');
const log = require('lighthouse-logger');

exports.lambdaHandler = async (event) => {
  let browser;
  let response;
  log.setLevel("error");

  try {
    browser = await chromium.puppeteer.launch({
      args: [...chromium.args, "--remote-debugging-port=9222"],
      defaultViewport: chromium.defaultViewport,
      executablePath: await chromium.executablePath,
      headless: chromium.headless,
      ignoreHTTPSErrors: true,
    });

    const options = {
      output: "json",
      preset: 'mobile',
      onlyCategories: ["performance", "seo", "accessibility", "best-practices"],
      port: 9222,
    }

    const url = 'https://www.google.com';

    const result = await lighthouse(url, options);
    console.log(`Audited ${url} in ${result.lhr.timing.total} ms.`);

    const report = JSON.parse(result.report);
      
    response = {
      statusCode: 200,
      body: {
        'Perfomance': report['categories']['performance']['score'],
        'Accessibility': report['categories']['accessibility']['score'],
        'SEO': report['categories']['seo']['score'],
        'BestPractices': report['categories']['best-practices']['score'],
        'ErrorMessage': report['audits']['speed-index']['errorMessage']
      }
    }

  } catch (error) {
    console.error(error);

    response = {
      statusCode: 500,
      body: error
    }
  } finally {
    if (browser !== null) {
      await browser.close();
    }
  }

  return response;
};

Однако у меня проблема с оценкой производительности. В большинстве случаев оценка производительности возвращается равной нулю. И сообщение об ошибке говорит:

Chrome didn't collect any screenshots during the page load. 
Please make sure there is content visible on the page, and 
then try re-running Lighthouse. (NO_SCREENSHOTS)

Я надеюсь, что кто-то может указать, что я сделал не так или, возможно, пропустил конфигурацию

person carbotex    schedule 18.02.2021
comment
Добавление --remote-debugging-port = 9222 к флагам chrome и port: 9222 к флагам lighthouse действительно решило мою проблему. (Теперь у меня проблема с нулевой оценкой производительности.) - person Tyler V.; 18.02.2021
comment
Я обнаружил, что это работает, если вы установите вывод в HTML. Выходные данные lighthouse-run в любом случае будут содержать и то, и другое, поэтому вы можете получить данные JSON позже. - person Sven Bluege; 28.04.2021