Skip to content
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
34 changes: 33 additions & 1 deletion public/node-analytics.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,35 @@
'</details>';
}

function snrDistributionHtml(trend) {
const min = -30, max = 30, step = 5;
// The two end bins hold readings outside the half-open range [min, max).
const bins = new Array((max - min) / step + 2).fill(0);
let total = 0;
for (const sample of Array.isArray(trend) ? trend : []) {
const raw = sample?.snr;
const snr = typeof raw === 'string' && /^[\d.e+-]+$/i.test(raw.trim()) ? Number(raw) : raw;
if (!Number.isFinite(snr)) continue;
const i = 1 + Math.floor(snr / step) - min / step;
bins[Math.max(0, Math.min(i, bins.length - 1))]++;
total++;
}

const peak = Math.max(...bins);
const rows = total ? bins.map((count, i) => {
const lower = min + (i - 1) * step;
let interval = lower + ' to under ' + (lower + step);
if (i === 0) interval = 'Below ' + min;
if (i === bins.length - 1) interval = max + ' and above';
return `<tr><th scope="row">${interval}</th><td><div class="na-snr-count"><span aria-hidden="true" style="width:${100 * count / peak}%"></span>${count}</div></td></tr>`;
}).join('') : '';
const summary = total ? total + (total === 1 ? ' sample' : ' samples') + ' in this window.' : 'No direct SNR samples in this window.';
return `<section class="na-snr" aria-labelledby="naSnrTitle"><h5 id="naSnrTitle">Direct SNR distribution</h5>
<p class="analytics-chart-desc">${summary} CoreScope keeps recent direct receptions per fixed observer. The chart shows up to the 500 newest retained SNR readings in the selected window.</p>
${rows ? `<table tabindex="0" aria-labelledby="naSnrTitle"><thead><tr><th scope="col">SNR interval (dB)</th><th scope="col">Samples</th></tr></thead><tbody>${rows}</tbody></table>` : ''}
</section>`;
}

function heardByHtml(data, opts) {
const pubkey = opts.pubkey;
const rows = data.heardBy || [];
Expand Down Expand Up @@ -188,6 +217,7 @@
}
return body +
'<div class="analytics-chart-desc">Same evidence as the node page’s ' + nodeLink + ' table.</div>' +
snrDistributionHtml(data.snrTrend) +
mobileGroup(data.mobileReceptions, pubkey);
}

Expand Down Expand Up @@ -332,6 +362,7 @@
container.querySelectorAll('#timeRangeBtns button').forEach(btn => {
btn.addEventListener('click', () => {
const d = Number(btn.dataset.days);
if (window.URLState) history.replaceState(null, '', URLState.updateHashParams({ days: d === 7 ? null : d }, location.hash));
loadAnalytics(container, pubkey, d);
});
});
Expand Down Expand Up @@ -511,7 +542,8 @@
return;
}
const pubkey = routeParam.slice(0, -'/analytics'.length);
loadAnalytics(container, pubkey, 7);
const saved = window.URLState && URLState.parseHash(location.hash).params.days;
loadAnalytics(container, pubkey, ['1', '7', '30', '365'].includes(saved) ? Number(saved) : 7);
}

function destroy() {
Expand Down
8 changes: 8 additions & 0 deletions public/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -3669,6 +3669,14 @@ tr[data-hops]:hover { background: rgba(59,130,246,0.1); }
.na-heard-mobile { margin-top: 10px; font-size: 13px; }
.na-heard-mobile summary { cursor: pointer; }
.na-heard-mobile-row { padding: 6px 0; }
.na-snr { margin-top: var(--space-sm); }
.na-snr h5 { margin-bottom: 4px; font-size: 13px; }
.na-snr table { width: 100%; max-width: 42rem; border-spacing: 0 2px; font-size: 12px; font-variant-numeric: tabular-nums; }
.na-snr th { text-align: left; }
.na-snr th[scope="row"] { width: 9rem; font-weight: normal; }
.na-snr th:last-child { text-align: right; }
.na-snr-count { display: grid; grid-template-columns: minmax(0, 1fr) 3ch; align-items: center; gap: .5rem; text-align: right; }
.na-snr-count span { height: .65em; background: var(--accent); }
.analytics-peer-table tr:hover td { background: var(--card-bg); }
@media (max-width: 768px) { .analytics-stats { grid-template-columns: repeat(2, 1fr); } }
@media (max-width: 480px) { .analytics-stats { grid-template-columns: 1fr; } }
Expand Down
65 changes: 63 additions & 2 deletions tests/e2e/test-node-analytics-heard-by-e2e.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,30 @@ function assert(cond, msg) {
if (!cond) throw new Error(msg || 'Assertion failed');
}

async function checkSnr(page, trend) {
const card = page.getByRole('region', { name: 'Direct SNR distribution' });
assert(await card.count() === 1, 'missing direct SNR distribution');
const readings = trend.map(sample => sample.snr).filter(Number.isFinite);
const text = await card.innerText();
assert(text.includes('500') && /retained/i.test(text), 'identify the bounded sample');
const table = card.getByRole('table', { name: 'Direct SNR distribution' });
if (!readings.length) {
assert(text.includes('No direct SNR samples in this window') && !await table.count(), 'empty sample');
return;
}
assert(text.includes(readings.length + (readings.length === 1 ? ' sample' : ' samples') + ' in this window'),
'sample count must match the response');
const edges = [-Infinity, -30, -25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30, Infinity];
const counts = await table.locator('tbody tr').evaluateAll(rows => rows.map(r => Number(r.cells[1].textContent.trim())));
assert(counts.length === edges.length - 1, 'expected fourteen fixed SNR intervals');
for (let i = 0; i < counts.length; i++) {
const expected = readings.filter(v => v >= edges[i] && v < edges[i + 1]).length;
assert(counts[i] === expected, 'interval ' + edges[i] + ' to ' + edges[i + 1] + ': expected ' + expected + ', got ' + counts[i]);
}
assert(await table.getByRole('rowheader', { name: '-5 to under 0', exact: true }).count() === 1,
'interval limits are exposed as row headers');
}

async function run() {
const browser = await chromium.launch({
headless: true,
Expand All @@ -37,11 +61,19 @@ async function run() {
const nodes = (await (await page.request.get(`${BASE}/api/nodes?limit=50`)).json()).nodes || [];
assert(nodes.length > 0, 'fixture has no nodes');
const pk = nodes[0].public_key;
const real = await (await page.request.get(`${BASE}/api/nodes/${pk}/analytics?days=7`)).json();
assert(Array.isArray(real.heardBy), 'analytics response has no heardBy array');
const path = '/api/nodes/' + pk + '/';
const nodeRequests = [];
page.on('request', req => {
const url = new URL(req.url());
if (url.pathname.startsWith(path)) nodeRequests.push(url.pathname.slice(path.length) + url.search);
});
let real;

await test('the Observers stat counts the heardBy rows; no SNR Trend or Observer Coverage chart', async () => {
const response = page.waitForResponse(r => new URL(r.url()).pathname === path + 'analytics');
await page.goto(`${BASE}/#/nodes/${encodeURIComponent(pk)}/analytics`, { waitUntil: 'domcontentloaded' });
real = await (await response).json();
assert(Array.isArray(real.heardBy), 'analytics response has no heardBy array');
await page.waitForSelector('#heardByCard');
assert(!(await page.$('#snrChart')), '#snrChart still on the page');
assert(!(await page.$('#observerChart')), '#observerChart still on the page');
Expand All @@ -52,13 +84,23 @@ async function run() {
assert(stat === String(real.heardBy.length), `Observers stat ${stat}, heardBy rows ${real.heardBy.length}`);
});

await test('direct SNR intervals match the unmodified analytics response', async () => {
await checkSnr(page, real.snrTrend);
if (process.env.SCREENSHOT_DIR) {
const file = require('path').join(process.env.SCREENSHOT_DIR, 'direct-snr-distribution.png');
await page.getByRole('region', { name: 'Direct SNR distribution' }).screenshot({ path: file });
}
});

const changedTrend = [-31, -25, -0.25, 0, 0, 30, null].map(snr => ({ snr }));
await test('12 observers: 10 rows, then "Show all 12" shows all', async () => {
const stub = JSON.parse(JSON.stringify(real));
stub.heardBy = Array.from({ length: 12 }, (_, i) => ({
observer_id: 'e2eobs' + i, observer_name: 'E2E observer ' + i, count: 20 - i,
medianSnr: 8 - i, p10Snr: 5 - i, p90Snr: 10 - i, recentMedianSnr: null, earlierMedianSnr: null,
}));
stub.computedStats.uniqueObservers = 12;
stub.snrTrend = changedTrend;
await page.route('**/api/nodes/*/analytics?days=30', (route) => route.fulfill({ contentType: 'application/json', body: JSON.stringify(stub) }));
await page.click('#timeRangeBtns button[data-days="30"]');
await page.waitForSelector('[data-action="heard-show-all"]');
Expand All @@ -72,6 +114,25 @@ async function run() {
assert(first === '#/observers/e2eobs0', `first row link: ${first}`);
});

await test('a saved window keeps its SNR counts and reuses the analytics request', async () => {
const saved = new URL(page.url()).hash;
assert(new URLSearchParams(saved.split('?')[1]).get('days') === '30', 'time window missing from the link');
await checkSnr(page, changedTrend);
const table = page.getByRole('table', { name: 'Direct SNR distribution' });
await table.focus();
await page.keyboard.press('Shift+Tab');
await page.keyboard.press('Tab');
assert(await table.evaluate(el => el === document.activeElement), 'keyboard can reach the interval counts');

await page.goto(BASE + '/#/home');
await page.goBack();
await page.waitForSelector('#timeRangeBtns button.active[data-days="30"]');
await checkSnr(page, changedTrend);
assert(nodeRequests.filter(r => r.startsWith('analytics?')).join(',') === 'analytics?days=7,analytics?days=30',
'only one analytics request per window');
assert(nodeRequests.every(r => /^(analytics|battery|hop_analytics)\?/.test(r)), 'unexpected per-node request');
});

await browser.close();
console.log('\nAll node analytics heard-by E2E tests passed.');
}
Expand Down
28 changes: 28 additions & 0 deletions tests/unit/test-node-analytics-heard-by.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,34 @@ t('a row without a median shows its count and no strip', () => {
assert.ok(!html.includes('na-heard-dot'));
});

t('direct SNR bins include exact five-dB boundaries, zero and both tails', () => {
const readings = [-31, -30, -29.75, -25, -20, -15, -10, -5, -0.25, 0, '0', 4.75, 5,
10, 15, 20, 25, 29.75, 30, 31, null, '', ' ', false, 'bad', Infinity, NaN];
const snrTrend = readings.map(snr => ({ snr })).concat([null, {}, { rssi: -90 }]);
const html = HB.html({ heardBy: [row(1, 4)], snrTrend }, { pubkey: PK });
assert.match(html, /20 samples in this window/, 'show the number of usable direct readings');
const rows = Array.from(html.matchAll(/<th scope="row">([^<]+)<\/th>\s*<td>([\s\S]*?)<\/td>/g),
match => [match[1], Number(match[2].replace(/<[^>]+>/g, '').trim())]);
assert.deepStrictEqual(rows, [
['Below -30', 1], ['-30 to under -25', 2], ['-25 to under -20', 1], ['-20 to under -15', 1],
['-15 to under -10', 1], ['-10 to under -5', 1], ['-5 to under 0', 2], ['0 to under 5', 3],
['5 to under 10', 1], ['10 to under 15', 1], ['15 to under 20', 1], ['20 to under 25', 1],
['25 to under 30', 2], ['30 and above', 2],
]);
});

t('direct SNR counts retained samples independently of observer totals and medians', () => {
for (const snrTrend of [undefined, null, [], [{ snr: null }, { snr: 'unknown' }]]) {
const html = HB.html({ heardBy: [row(1, 4)], snrTrend }, { pubkey: PK });
assert.match(html, /No direct SNR samples in this window/, 'explain an empty sample');
assert.ok(!html.includes('Below -30'), 'empty sample should have no bars');
}
const trend = Array.from({ length: 500 }, () => ({ snr: 0 }));
const html = HB.html({ heardBy: [row(1, 4)], snrTrend: trend }, { pubkey: PK });
assert.match(html, /500 samples in this window/);
assert.match(HB.html({ snrTrend: [{ snr: 0 }] }, { pubkey: PK }), /1 sample in this window/);
});

t('empty list explains itself and links to the node page table', () => {
const html = HB.html({ heardBy: [] }, { pubkey: PK });
assert.ok(html.includes('No observer heard this node directly in this window'));
Expand Down
Loading