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
99 changes: 99 additions & 0 deletions lib/freshness.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/**
* When the dashboard's data was collected, and whether that still reads as
* current. Shared by the API (pages/api/overview.js, server) and the dashboard
* (pages/index.js, client) so the stamp is read and judged one way.
*
* The stamp is the lastUpdated field of data/summary.json, written by each
* collection run as an ISO 8601 UTC time. A date taken from the moment the
* page or the API answered would read as today whatever the age of the data.
*/

/* Data older than this many whole hours reads as stale. */
const FRESH_BOUND_HOURS = 30;

/* A stamp up to this far ahead of the reader's clock is clock skew and reads
* as 0 h old; further ahead it cannot be trusted and reads as unknown. */
const AHEAD_TOLERANCE_MS = 300 * 1000;

const HOUR_MS = 60 * 60 * 1000;

/* ISO 8601 UTC, e.g. 2026-11-16T06:05:47.696Z (fraction optional, 1 to 9 digits). */
const STAMP_FORM = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d{1,9})?Z$/;

/* The page's date format for a YYYY-MM-DD day: "Nov 16". */
function fmtDate(s) {
if (!s) return '';
const d = new Date(s + 'T00:00:00Z');
return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' });
}

/**
* The lastUpdated stamp of <dataDir>/summary.json when it is in ISO 8601 UTC
* form; null when the file is absent or unreadable, is not JSON, has no such
* key, or holds another form. Never throws.
*/
function readDataCollectedAt(dataDir) {
try {
// The page bundles this module too, so fs and path are loaded when this
// runs (on the server, Node 24 per package.json engines) instead of being
// required at the top, which would pull Node built-ins into the browser.
const fs = process.getBuiltinModule('node:fs');
const path = process.getBuiltinModule('node:path');
const summary = JSON.parse(fs.readFileSync(path.join(dataDir, 'summary.json'), 'utf8'));
const stamp = summary !== null && typeof summary === 'object' ? summary.lastUpdated : undefined;
return typeof stamp === 'string' && STAMP_FORM.test(stamp) ? stamp : null;
} catch {
return null;
}
}

/* Milliseconds since the epoch for a stamp in STAMP_FORM, else null. Parsed by
* hand so every browser reads it alike (engines differ on fractions longer
* than 3 digits) and a calendar-impossible value such as 2026-02-30T00:00:00Z
* is null instead of rolling over into March. */
function parseStamp(stamp) {
if (typeof stamp !== 'string') return null;
const m = STAMP_FORM.exec(stamp);
if (!m) return null;
const [y, mo, d, h, mi, s] = m.slice(1, 7).map(Number);
const ms = m[7] ? Number(m[7].slice(1, 4).padEnd(3, '0')) : 0;
const t = Date.UTC(y, mo - 1, d, h, mi, s, ms);
const back = new Date(t);
if (back.getUTCFullYear() !== y || back.getUTCMonth() !== mo - 1 || back.getUTCDate() !== d
|| back.getUTCHours() !== h || back.getUTCMinutes() !== mi || back.getUTCSeconds() !== s) {
return null;
}
return t;
}

/**
* { state, ageHours } for data collected at `dataCollectedAt`, read at `nowMs`.
* 'unknown' (ageHours null) when there is no parsable stamp or it is more than
* 300 s ahead of nowMs. Otherwise ageHours is the whole hours since collection
* (0 when the stamp is up to 300 s ahead), and the state is 'stale' past
* FRESH_BOUND_HOURS, else 'fresh'.
*/
function dataFreshness(dataCollectedAt, nowMs) {
const t = parseStamp(dataCollectedAt);
if (t === null || !Number.isFinite(nowMs) || t - nowMs > AHEAD_TOLERANCE_MS) {
return { state: 'unknown', ageHours: null };
}
const ageHours = Math.max(0, Math.floor((nowMs - t) / HOUR_MS));
return { state: ageHours > FRESH_BOUND_HOURS ? 'stale' : 'fresh', ageHours };
}

/**
* The dashboard's text for data collected at `dataCollectedAt`, read at `nowMs`:
* fresh Data collected Nov 16, 06:05 UTC
* stale Data is 97 h old (collected Nov 4, 06:05 UTC)
* unknown Data date unknown
*/
function dataDateLabel(dataCollectedAt, nowMs) {
const { state, ageHours } = dataFreshness(dataCollectedAt, nowMs);
if (state === 'unknown') return 'Data date unknown';
const iso = new Date(parseStamp(dataCollectedAt)).toISOString();
const collected = `${fmtDate(iso.slice(0, 10))}, ${iso.slice(11, 16)} UTC`;
return state === 'stale' ? `Data is ${ageHours} h old (collected ${collected})` : `Data collected ${collected}`;
}

module.exports = { FRESH_BOUND_HOURS, fmtDate, readDataCollectedAt, dataFreshness, dataDateLabel };
14 changes: 11 additions & 3 deletions pages/api/overview.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,31 @@
const Database = require('better-sqlite3');
const path = require('path');
const { computeOverview } = require('../../lib/overview');
const { readDataCollectedAt } = require('../../lib/freshness');

/**
* Overview API: Returns combined GitHub + npm metrics suitable for
* investor presentations, dashboards, and growth tracking. All computation
* lives in lib/overview.js.
* lives in lib/overview.js; dataCollectedAt, the time the data was collected,
* is read from data/summary.json by lib/freshness.js.
*/
export default async function handler(req, res) {
// Cache response on Vercel edge for 5 minutes
res.setHeader('Cache-Control', 's-maxage=300');
const dbPath = path.join(process.cwd(), 'data', 'analytics.db');
const dataDir = path.join(process.cwd(), 'data');
const dbPath = path.join(dataDir, 'analytics.db');
const db = new Database(dbPath, { readonly: true });

// Custom date range support
const { start, end } = req.query;

try {
res.status(200).json(computeOverview(db, { start, end }));
res.status(200).json({
...computeOverview(db, { start, end }),
// When the data was collected (null when summary.json has no readable
// stamp). lastUpdated stays the moment this answer was computed.
dataCollectedAt: readDataCollectedAt(dataDir),
});
} catch (error) {
console.error('Error fetching overview:', error);
res.status(500).json({ error: 'Failed to fetch overview' });
Expand Down
19 changes: 11 additions & 8 deletions pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ import { SERIES } from '../lib/series';
// A first-party telemetry count under ten, zero included, is withheld: the API
// serves it as null and it reads "fewer than 10" here, never 0.
import { floorCount, formatTelemetryCount, topMeasuredVersion, withWithheldNote, WITHHELD_LABEL } from '../lib/telemetry-withheld';
// The sidebar date is when the data was collected (the API's dataCollectedAt),
// never when the page or the API answered: past 30 hours it reads as stale and
// with no readable stamp as unknown. fmtDate is the page's one date format.
import { fmtDate, dataFreshness, dataDateLabel } from '../lib/freshness';

/* ============================================================
Source identity — one place defines color + icon per source
Expand Down Expand Up @@ -75,13 +79,8 @@ const tt = {
const BREAKDOWN_COLORS = ['#6e9bff', '#2dd4bf', '#f5b53c', '#ff7a7a', '#a78bfa', '#4cb8f5', '#ffce4d', '#f472b6', '#34d399', '#fb923c'];

/* ============================================================
Formatting helpers
Formatting helpers (fmtDate is imported from lib/freshness)
============================================================ */
function fmtDate(s) {
if (!s) return '';
const d = new Date(s + 'T00:00:00Z');
return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' });
}
function fmtNum(n) {
if (n == null) return '0';
if (Math.abs(n) >= 1e6) return (n / 1e6).toFixed(1) + 'M';
Expand Down Expand Up @@ -388,6 +387,10 @@ export default function Dashboard() {
chrome: overview?.totals?.chrome?.extensions,
};
const meta = SOURCES[tab];
// The sidebar's data date, on the reader's clock: settled once the overview
// has answered (a failed answer reads as unknown, never as fresh).
const nowMs = Date.now();
const dataDate = (overview || !ovLoading) ? dataFreshness(overview?.dataCollectedAt, nowMs) : null;

return (
<>
Expand Down Expand Up @@ -418,8 +421,8 @@ export default function Dashboard() {
);
})}
</nav>
<div className="sidebar-foot">
<span className="dot">●</span> {overview?.lastUpdated ? `Updated ${fmtDate(overview.lastUpdated.split('T')[0])}` : 'Loading…'}
<div className={`sidebar-foot${dataDate && dataDate.state !== 'fresh' ? ' data-warn' : ''}`}>
<span className={dataDate ? 'dot' : undefined}>●</span> {dataDate ? dataDateLabel(overview?.dataCollectedAt, nowMs) : 'Loading…'}
</div>
</aside>

Expand Down
4 changes: 4 additions & 0 deletions styles/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,10 @@ a { color: inherit; }
font-size: 0.66rem; color: var(--ink-4); line-height: 1.6;
}
.sidebar-foot .dot { color: var(--up); }
/* Data past the freshness bound, or with no readable date: the line and its
dot read as a warning (the words say so as well). */
.sidebar-foot.data-warn,
.sidebar-foot.data-warn .dot { color: #f59e0b; }

/* ---------- Topbar ---------- */
.topbar {
Expand Down
136 changes: 136 additions & 0 deletions test/freshness.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { mkdirSync, mkdtempSync, rmSync, writeFileSync } = require('node:fs');
const { join } = require('node:path');
const { tmpdir } = require('node:os');

/*
* The dashboard's date is the time its data was collected (the lastUpdated
* stamp of data/summary.json), never the moment the page or the API answered.
* Past 30 hours it reads as stale; with no readable stamp it reads as unknown,
* never as fresh.
*
* The module is loaded inside each test so that every cell fails on its own
* while lib/freshness.js does not exist.
*/
const freshness = () => require('../lib/freshness');

const MINUTE = 60 * 1000;
const HOUR = 60 * MINUTE;
const STAMP = '2026-11-16T06:05:47.696Z';
const STAMP_MS = Date.UTC(2026, 10, 16, 6, 5, 47, 696);
const UNKNOWN = { state: 'unknown', ageHours: null };

/* A temporary data directory, removed after the test. `summary` is the raw
* text of summary.json; undefined writes no file. */
function dataDir(t, summary) {
const dir = mkdtempSync(join(tmpdir(), 'gat-freshness-'));
t.after(() => rmSync(dir, { recursive: true, force: true }));
if (summary !== undefined) writeFileSync(join(dir, 'summary.json'), summary);
return dir;
}

/* ---------- readDataCollectedAt ---------- */

test('readDataCollectedAt returns the lastUpdated stamp of summary.json', (t) => {
const dir = dataDir(t, JSON.stringify({ lastUpdated: STAMP, repos: [] }, null, 2));
assert.equal(freshness().readDataCollectedAt(dir), STAMP);
});

test('readDataCollectedAt is null when summary.json is missing', (t) => {
const dir = dataDir(t, undefined);
assert.equal(freshness().readDataCollectedAt(dir), null);
});

test('readDataCollectedAt is null when summary.json is not valid JSON', (t) => {
const dir = dataDir(t, `{"lastUpdated": "${STAMP}",`);
assert.equal(freshness().readDataCollectedAt(dir), null);
});

test('readDataCollectedAt is null when summary.json has no lastUpdated', (t) => {
const dir = dataDir(t, JSON.stringify({ repos: [], totals: {} }));
assert.equal(freshness().readDataCollectedAt(dir), null);
});

test('readDataCollectedAt is null for a stamp with a non-UTC offset', (t) => {
const dir = dataDir(t, JSON.stringify({ lastUpdated: '2026-11-16T08:05:47.696+02:00' }));
assert.equal(freshness().readDataCollectedAt(dir), null);
});

test('readDataCollectedAt is null, without throwing, when summary.json cannot be read as a file', (t) => {
const dir = dataDir(t, undefined);
mkdirSync(join(dir, 'summary.json'));
assert.equal(freshness().readDataCollectedAt(dir), null);
});

test('readDataCollectedAt is null, without throwing, when summary.json holds JSON null', (t) => {
const dir = dataDir(t, 'null');
assert.equal(freshness().readDataCollectedAt(dir), null);
});

/* ---------- dataFreshness ---------- */

test('the freshness bound is 30 hours', () => {
assert.equal(freshness().FRESH_BOUND_HOURS, 30);
});

test('dataFreshness: data collected at this moment is fresh, 0 h', () => {
assert.deepEqual(freshness().dataFreshness(STAMP, STAMP_MS), { state: 'fresh', ageHours: 0 });
});

test('dataFreshness: 29 h 59 min old is fresh, 29 h', () => {
assert.deepEqual(freshness().dataFreshness(STAMP, STAMP_MS + 29 * HOUR + 59 * MINUTE), { state: 'fresh', ageHours: 29 });
});

test('dataFreshness: 30 h 59 min old is still fresh, 30 h', () => {
assert.deepEqual(freshness().dataFreshness(STAMP, STAMP_MS + 30 * HOUR + 59 * MINUTE), { state: 'fresh', ageHours: 30 });
});

test('dataFreshness: 31 h 0 min old is stale, 31 h', () => {
assert.deepEqual(freshness().dataFreshness(STAMP, STAMP_MS + 31 * HOUR), { state: 'stale', ageHours: 31 });
});

test('dataFreshness: a stamp 299 s ahead of the clock is fresh, 0 h', () => {
assert.deepEqual(freshness().dataFreshness(STAMP, STAMP_MS - 299 * 1000), { state: 'fresh', ageHours: 0 });
});

test('dataFreshness: a stamp 301 s ahead of the clock is unknown', () => {
assert.deepEqual(freshness().dataFreshness(STAMP, STAMP_MS - 301 * 1000), UNKNOWN);
});

test('dataFreshness: no stamp is unknown', () => {
assert.deepEqual(freshness().dataFreshness(null, STAMP_MS), UNKNOWN);
});

test('dataFreshness: an unparsable stamp is unknown', () => {
assert.deepEqual(freshness().dataFreshness('garbage', STAMP_MS), UNKNOWN);
});

/* ---------- dataDateLabel ---------- */

test('dataDateLabel: fresh data reads when it was collected', () => {
// Read at 20:45:30Z over data collected at 06:05:47Z the same day.
const now = Date.UTC(2026, 10, 16, 20, 45, 30, 393);
assert.equal(freshness().dataDateLabel(STAMP, now), 'Data collected Nov 16, 06:05 UTC');
});

test('dataDateLabel: stale data reads its age in hours', () => {
// A day like 2026-11-08: data collected on 2026-11-04 (the hour is illustrative), read at 07:30Z.
const now = Date.UTC(2026, 10, 8, 7, 30, 0, 0);
assert.equal(freshness().dataDateLabel('2026-11-04T06:05:47.696Z', now), 'Data is 97 h old (collected Nov 4, 06:05 UTC)');
});

test('dataDateLabel: data with no readable stamp reads as unknown', () => {
assert.equal(freshness().dataDateLabel(null, STAMP_MS), 'Data date unknown');
// An answer without the field at all reads the same way.
assert.equal(freshness().dataDateLabel(undefined, STAMP_MS), 'Data date unknown');
});

/* ---------- fmtDate (the page's date format, shared with the label) ---------- */

test('fmtDate keeps the page date format', () => {
assert.equal(freshness().fmtDate('2026-11-16'), 'Nov 16');
assert.equal(freshness().fmtDate('2026-11-04'), 'Nov 4');
assert.equal(freshness().fmtDate(''), '');
assert.equal(freshness().fmtDate(null), '');
});
Loading