Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MWPW-154969 Log LCP and key user attributes #2686

Merged
merged 3 commits into from
Aug 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 95 additions & 0 deletions libs/utils/logWebVitals.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
const LANA_CLIENT_ID = 'pageperf';

let lanaSent;

function sendToLana(lanaData) {
if (lanaSent) return;
const ua = window.navigator.userAgent;

Object.assign(lanaData, {
chromeVer: ua.match(/Chrome\/(\d+\.\d+\.\d+\.\d+)/)?.[1] || '',
country: sessionStorage.getItem('akamai') || '',
// eslint-disable-next-line compat/compat
downlink: window.navigator?.connection?.downlink || '',
loggedIn: window.adobeIMS?.isSignedInUser() || false,
os: (ua.match(/Windows/) && 'win')
|| (ua.match(/Mac/) && 'mac')
|| (ua.match(/Android/) && 'android')
|| (ua.match(/Linux/) && 'linux')
|| '',
mokimo marked this conversation as resolved.
Show resolved Hide resolved
windowHeight: window.innerHeight,
windowWidth: window.innerWidth,
url: `${window.location.host}${window.location.pathname}`,
});

lanaData.cls ||= 0;
const lanaDataStr = Object.entries(lanaData)
.sort(([a], [b]) => a.localeCompare(b))
.map(([key, value]) => `${key}=${value}`)
.join(',');

window.lana.log(lanaDataStr, {
clientId: LANA_CLIENT_ID,
sampleRate: 100,
});

lanaSent = true;
}

function observeCLS(lanaData) {
let cls = 0;
/* c8 ignore start */
new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
if (!entry.hadRecentInput) cls += entry.value;
}
lanaData.cls = cls.toPrecision(4);
}).observe({ type: 'layout-shift', buffered: true });
}

function getElementInfo(el) {
const elSrc = el.src || el.currentSrc || el.href || el.poster;
if (elSrc) {
try {
const srcUrl = new URL(elSrc);
return srcUrl.origin === window.location.origin ? srcUrl.pathname : srcUrl.href;
} catch {
// fall through
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason for not logging the error in here?

}
}
const elHtml = el.outerHTML.replaceAll(',', '');
if (elHtml.length <= 100) return elHtml;
return `${el.outerHTML.substring(0, 100)}...`;
}

function observeLCP(lanaData, delay) {
new PerformanceObserver((list) => {
const entries = list.getEntries();
const lastEntry = entries[entries.length - 1]; // Use the latest LCP candidate
lanaData.lcp = parseInt(lastEntry.startTime, 10);
const lcpEl = lastEntry.element;
lanaData.lcpElType = lcpEl.nodeName.toLowerCase();
lanaData.lcpEl = getElementInfo(lcpEl);

setTimeout(() => {
sendToLana(lanaData);
}, parseInt(delay, 10));
}).observe({ type: 'largest-contentful-paint', buffered: true });
/* c8 ignore stop */
}

function logMepExperiments(lanaData, mep) {
mep?.experiments?.forEach((exp, idx) => {
// only log manifests that affect the page
if (exp.selectedVariantName === 'default') return;
lanaData[`manifest${idx + 1}path`] = exp.manifestPath;
lanaData[`manifest${idx + 1}selected`] = exp.selectedVariantName;
});
}

export default function webVitals(mep, { delay = 1000 } = {}) {
const lanaData = {};
logMepExperiments(lanaData, mep);
observeCLS(lanaData);
observeLCP(lanaData, delay);
}
14 changes: 14 additions & 0 deletions libs/utils/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -998,6 +998,18 @@ export function scrollToHashedElement(hash) {
});
}

function logPagePerf() {
if (getMetadata('pageperf') !== 'on') return;
const isChrome = () => {
const nav = window.navigator;
return nav.userAgent.includes('Chrome') && nav.vendor.includes('Google');
};
const sampleRate = parseInt(getMetadata('pageperf-rate'), 10) || 50;
if (!isChrome() || Math.random() * 100 > sampleRate) return;
import('./logWebVitals.js')
.then((mod) => mod.default(getConfig().mep, getMetadata('pageperf-delay') || 1000));
}

export async function loadDeferred(area, blocks, config) {
const event = new Event(MILO_EVENTS.DEFERRED);
area.dispatchEvent(event);
Expand Down Expand Up @@ -1025,6 +1037,8 @@ export async function loadDeferred(area, blocks, config) {
sampleRUM.observe(blocks);
sampleRUM.observe(area.querySelectorAll('picture > img'));
});

logPagePerf();
}

function initSidekick() {
Expand Down
53 changes: 53 additions & 0 deletions test/utils/logWebVitals.test.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

51 changes: 51 additions & 0 deletions test/utils/logWebVitalsUtils.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/* eslint-disable no-use-before-define */
import { expect } from '@esm-bundle/chai';
import { readFile } from '@web/test-runner-commands';
import { getConfig, loadDeferred } from '../../libs/utils/utils.js';

document.head.innerHTML = `
<meta name="pageperf" content="on">';
<meta name="pageperf-rate" content="100">';
<meta name="pageperf-delay" content="0">';
`;

document.body.innerHTML = await readFile({ path: './mocks/body.html' });

describe('Log Web Vitals', () => {
it('Logs data to lana', (done) => {
window.lana = {
log: (logStr, logOpts) => {
const vitals = logStr.split(',').reduce((acc, pair) => {
const [key, value] = pair.split('=');
acc[key] = value;
return acc;
}, {});

expect(vitals).to.have.property('chromeVer');
const cls = parseFloat(vitals.cls);
expect(cls).to.be.within(0, 1);
expect(vitals).to.have.property('country');
const downlink = parseFloat(vitals.downlink);
expect(downlink).to.be.within(0, 10);
expect(parseInt(vitals.lcp, 10)).to.be.greaterThan(1);
expect(vitals.lcpEl).to.be.equal('/test/utils/mocks/media_.png');
expect(vitals.lcpElType).to.be.equal('img');
expect(vitals.loggedIn).to.equal('false');
expect(vitals.os).to.be.oneOf(['mac', 'win', 'android', 'linux', '']);
expect(vitals.url).to.equal('localhost:2000/');
expect(parseInt(vitals.windowHeight, 10)).to.be.greaterThan(200);
expect(parseInt(vitals.windowWidth, 10)).to.be.greaterThan(200);

expect(logOpts.clientId).to.equal('pageperf');
expect(logOpts.sampleRate).to.equal(100);

done();
},
};
loadDeferred(document, undefined, getConfig());
}).timeout(5000);
});

// Sample log string:
// eslint-disable-next-line max-len
// chromeVer=127.0.6533.17,cls=0.1842,country=,downlink=10,lcp=82,loggedIn=false,manifest3path=/cc-shared/fragments/promos/2024/americas/cci-all-apps-q3/cci-all-apps-q3.json,manifest3selected=all,manifest4path=/cc-shared/fragments/tests/2024/q2/ace0875/ace0875.json,manifest4selected=target-var-marqueelink,os=mac,url=localhost:2000/,windowHeight=600,windowWidth=800');