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

Minirum - Hard dependency on Helix 5 #452

Closed
wants to merge 2 commits into from
Closed
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
10 changes: 7 additions & 3 deletions plugins/experimentation/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -650,9 +650,13 @@ function adjustedRumSamplingRate(checkpoint, options, context) {
}

export async function loadEager(document, options, context) {
context.sampleRUM.always.on('audiences', adjustedRumSamplingRate('audiences', options, context));
context.sampleRUM.always.on('campaign', adjustedRumSamplingRate('campaign', options, context));
context.sampleRUM.always.on('experiment', adjustedRumSamplingRate('experiment', options, context));
document.addEventListener('rum', (event) => {
const checkpoint = event.detail ? event.detail.checkpoint || '' : '';
if(['audiences', 'campaign', 'experiment'].includes(checkpoint)) {
adjustedRumSamplingRate(checkpoint, options, context);
}
});

let res = await runCampaign(document, options, context);
if (!res) {
res = await runExperiment(document, options, context);
Expand Down
138 changes: 24 additions & 114 deletions scripts/lib-franklin.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable max-classes-per-file */
/*
* Copyright 2022 Adobe. All rights reserved.
* Copyright 2023 Adobe. All rights reserved.
* This file is licensed to you 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
Expand All @@ -11,113 +11,36 @@
* governing permissions and limitations under the License.
*/

/**
* log RUM if part of the sample.
* @param {string} checkpoint identifies the checkpoint in funnel
* @param {Object} data additional data for RUM sample
*/
export function sampleRUM(checkpoint, data = {}) {
sampleRUM.defer = sampleRUM.defer || [];
const defer = (fnname) => {
sampleRUM[fnname] = sampleRUM[fnname] || ((...args) => sampleRUM.defer.push({ fnname, args }));
};
sampleRUM.drain = sampleRUM.drain
|| ((dfnname, fn) => {
sampleRUM[dfnname] = fn;
sampleRUM.defer
.filter(({ fnname }) => dfnname === fnname)
.forEach(({ fnname, args }) => sampleRUM[fnname](...args));
});
sampleRUM.always = sampleRUM.always || [];
sampleRUM.always.on = (chkpnt, fn) => {
sampleRUM.always[chkpnt] = fn;
};
sampleRUM.on = (chkpnt, fn) => {
sampleRUM.cases[chkpnt] = fn;
};
defer('observe');
defer('cwv');
export function sampleRUM(checkpoint, data) {
// eslint-disable-next-line max-len
const timeShift = () => (window.performance ? window.performance.now() : Date.now() - window.hlx.rum.firstReadTime);
const SESSION_STORAGE_KEY = 'aem-rum';
try {
window.hlx = window.hlx || {};
if (!window.hlx.rum) {
const usp = new URLSearchParams(window.location.search);
const weight = usp.get('rum') === 'on' ? 1 : 100; // with parameter, weight is 1. Defaults to 100.
const id = Array.from({ length: 75 }, (_, i) => String.fromCharCode(48 + i))
.filter((a) => /\d|[A-Z]/i.test(a))
.filter(() => Math.random() * 75 > 70)
.join('');
const random = Math.random();
const isSelected = random * weight < 1;
const firstReadTime = Date.now();
const urlSanitizers = {
full: () => window.location.href,
origin: () => window.location.origin,
path: () => window.location.href.replace(/\?.*$/, ''),
};
// eslint-disable-next-line max-len
const rumStorage = sessionStorage.getItem(SESSION_STORAGE_KEY) ? JSON.parse(sessionStorage.getItem(SESSION_STORAGE_KEY)) : {};
rumStorage.pages = (rumStorage.pages ?? 0) + (Math.floor(Math.random() * 20) - 10) + 1;
sessionStorage.setItem(SESSION_STORAGE_KEY, JSON.stringify(rumStorage));
sampleRUM.baseURL = sampleRUM.baseURL || new URL(window.RUM_BASE == null ? 'https://rum.hlx.page' : window.RUM_BASE, window.location);
const weight = new URLSearchParams(window.location.search).get('rum') === 'on' ? 1 : 100;
const id = Array.from({ length: 75 }, (_, i) => String.fromCharCode(48 + i)).filter((a) => /\d|[A-Z]/i.test(a)).filter(() => Math.random() * 75 > 70).join('');
const isSelected = (Math.random() * weight < 1);
// eslint-disable-next-line object-curly-newline, max-len
window.hlx.rum = {
weight,
id,
random,
isSelected,
firstReadTime,
sampleRUM,
sanitizeURL: urlSanitizers[window.hlx.RUM_MASK_URL || 'path'],
};
}
const { weight, id, firstReadTime } = window.hlx.rum;
if (window.hlx && window.hlx.rum && window.hlx.rum.isSelected) {
const knownProperties = [
'weight',
'id',
'referer',
'checkpoint',
't',
'source',
'target',
'cwv',
'CLS',
'FID',
'LCP',
'INP',
];
const sendPing = (pdata = data) => {
// eslint-disable-next-line object-curly-newline, max-len, no-use-before-define
const body = JSON.stringify(
{
weight,
id,
referer: window.hlx.rum.sanitizeURL(),
checkpoint,
t: Date.now() - firstReadTime,
...data,
},
knownProperties,
);
const url = `https://rum.hlx.page/.rum/${weight}`;
// eslint-disable-next-line no-unused-expressions
window.hlx.rum = { weight, id, isSelected, firstReadTime: window.performance ? window.performance.timeOrigin : Date.now(), sampleRUM, queue: [], collector: (...args) => window.hlx.rum.queue.push(args) };
if (isSelected) {
// eslint-disable-next-line object-curly-newline, max-len
const body = JSON.stringify({ weight, id, referer: window.location.href, checkpoint: 'top', t: timeShift(), target: document.visibilityState });
const url = new URL(`.rum/${weight}`, sampleRUM.baseURL).href;
navigator.sendBeacon(url, body);
// eslint-disable-next-line no-console
console.debug(`ping:${checkpoint}`, pdata);
};
sampleRUM.cases = sampleRUM.cases || {
cwv: () => sampleRUM.cwv(data) || true,
lazy: () => {
// use classic script to avoid CORS issues
const script = document.createElement('script');
script.src = 'https://rum.hlx.page/.rum/@adobe/helix-rum-enhancer@^1/src/index.js';
document.head.appendChild(script);
return true;
},
};
sendPing(data);
if (sampleRUM.cases[checkpoint]) {
sampleRUM.cases[checkpoint]();
// eslint-disable-next-line max-statements-per-line, brace-style
window.addEventListener('load', () => { sampleRUM('load'); import(new URL('.rum/@adobe/helix-rum-enhancer@^2/src/index.js', sampleRUM.baseURL)); });
}
}
if (sampleRUM.always[checkpoint]) {
sampleRUM.always[checkpoint](data);
if (window.hlx.rum && window.hlx.rum.isSelected && checkpoint) {
window.hlx.rum.collector(checkpoint, data, timeShift());
}
document.dispatchEvent(new CustomEvent('rum', { detail: { checkpoint, data } }));
} catch (error) {
// something went wrong
}
Expand Down Expand Up @@ -924,20 +847,7 @@ export function setup() {
*/
export function init() {
setup();
sampleRUM('top');

window.addEventListener('load', () => sampleRUM('load'));

window.addEventListener('unhandledrejection', (event) => {
sampleRUM('error', {
source: event.reason.sourceURL,
target: event.reason.line,
});
});

window.addEventListener('error', (event) => {
sampleRUM('error', { source: event.filename, target: event.lineno });
});
sampleRUM();
}

init();
6 changes: 4 additions & 2 deletions tests/scripts/lib-franklin.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,15 +85,17 @@ describe('Core Helix features', () => {
// sends checkpoint beacon
await scripts.sampleRUM('test', { foo: 'bar' });
expect(sendBeacon.called).to.be.true;
expect(window.hlx.rum.queue.length).to.equal(1);
sendBeacon.resetHistory();

// sends cwv beacon
// queues cwv beacon
await scripts.sampleRUM('cwv', { foo: 'bar' });
expect(sendBeacon.called).to.be.true;
expect(window.hlx.rum.queue.length).to.equal(2);

// test error handling
sendBeacon.throws();
await scripts.sampleRUM('error', { foo: 'bar' });
expect(window.hlx.rum.queue.length).to.equal(3);

sendBeacon.restore();
});
Expand Down
Loading