feat(frontend): post collected samples to /api/v1/reports (closes #53)
check / check (push) Successful in 13s
check / check (push) Successful in 13s
A Reporter class beside AppState POSTs a JSON report to the same-origin
/api/v1/reports every reportInterval (default 60s, a new CONFIG value).
buildReport is a pure function of host state: it emits each host's
unreported, non-paused samples ({t, latency, error}) plus a random
per-browser clientId from localStorage, geo null, and an ISO 8601 UTC
timestamp. A per-host high-water mark keyed on sample time makes every
report a delta and only advances on a delivered POST, so a failed send
re-sends next interval, bounded by the existing history window. Failure
is quiet: one debug-log line per outage, one on recovery, no alert, no
tight retry loop, never blocking probing. While paused nothing is sent.
vite.config.js proxies /api to 127.0.0.1:8080 so yarn dev exercises the
real path against a local netwatch-server. Backend and schema unchanged.
Model: opus-4-8
This commit is contained in:
+120
@@ -7,9 +7,11 @@ import "./styles.css";
|
||||
// graphMaxLatency — values above it pin to the top of the chart but still
|
||||
// display their real value in the latency figure. The history buffer holds
|
||||
// maxHistoryPoints samples (historyDuration / updateInterval).
|
||||
// reportInterval is how often collected samples are POSTed to the backend.
|
||||
const CONFIG = {
|
||||
updateInterval: 3000,
|
||||
maxHistoryPoints: 100,
|
||||
reportInterval: 60000,
|
||||
get historyDuration() {
|
||||
return (this.maxHistoryPoints * this.updateInterval) / 1000;
|
||||
},
|
||||
@@ -346,6 +348,121 @@ class AppState {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Reporting ---------------------------------------------------------------
|
||||
|
||||
// A random id identifying this browser across reports. Generated once and
|
||||
// kept in localStorage; if storage is unavailable (e.g. private mode) a
|
||||
// fresh id is used for this session only.
|
||||
function getClientId() {
|
||||
const key = "netwatch-client-id";
|
||||
try {
|
||||
let id = localStorage.getItem(key);
|
||||
if (!id) {
|
||||
id = crypto.randomUUID();
|
||||
localStorage.setItem(key, id);
|
||||
}
|
||||
return id;
|
||||
} catch {
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
}
|
||||
|
||||
// Build the delta report body the backend decodes, plus the new per-host
|
||||
// high-water marks. Pure function of the passed state: `hosts` is an array
|
||||
// of { name, url, status, history }, `since` maps a host url to the Unix-ms
|
||||
// timestamp of the last sample already reported for it, and `now` is a Date.
|
||||
// Only non-paused samples newer than the mark are included. Returns null
|
||||
// when no host has an unreported sample.
|
||||
function buildReport(hosts, clientId, now, since) {
|
||||
const reportHosts = [];
|
||||
const marks = new Map();
|
||||
for (const host of hosts) {
|
||||
const mark = since.get(host.url) ?? 0;
|
||||
const samples = [];
|
||||
let high = mark;
|
||||
for (const p of host.history) {
|
||||
if (p.paused) continue;
|
||||
if (p.timestamp <= mark) continue;
|
||||
samples.push({
|
||||
t: p.timestamp,
|
||||
latency: p.latency,
|
||||
error: p.error ?? null,
|
||||
});
|
||||
if (p.timestamp > high) high = p.timestamp;
|
||||
}
|
||||
if (samples.length === 0) continue;
|
||||
reportHosts.push({
|
||||
name: host.name,
|
||||
url: host.url,
|
||||
status: host.status,
|
||||
history: samples,
|
||||
});
|
||||
marks.set(host.url, high);
|
||||
}
|
||||
if (reportHosts.length === 0) return null;
|
||||
return {
|
||||
body: {
|
||||
clientId,
|
||||
geo: null,
|
||||
hosts: reportHosts,
|
||||
timestamp: now.toISOString(),
|
||||
},
|
||||
marks,
|
||||
};
|
||||
}
|
||||
|
||||
// Periodically POSTs unreported samples to the same-origin backend. Holds
|
||||
// the per-host high-water marks so each report is a delta; marks only
|
||||
// advance on a delivered report, so a failed POST simply re-sends those
|
||||
// samples next interval (bounded by the history window — whatever has since
|
||||
// fallen out is dropped). Failure is quiet: one debug line per outage, one
|
||||
// on recovery, never an alert, never a tight retry loop.
|
||||
class Reporter {
|
||||
constructor(state, clientId, intervalMs) {
|
||||
this.state = state;
|
||||
this.clientId = clientId;
|
||||
this.intervalMs = intervalMs;
|
||||
this.marks = new Map();
|
||||
this.failing = false;
|
||||
this.timerId = null;
|
||||
}
|
||||
|
||||
start() {
|
||||
if (this.timerId) return;
|
||||
this.timerId = setInterval(() => this.flush(), this.intervalMs);
|
||||
}
|
||||
|
||||
async flush() {
|
||||
if (this.state.paused) return;
|
||||
const report = buildReport(
|
||||
this.state.allHosts,
|
||||
this.clientId,
|
||||
new Date(),
|
||||
this.marks,
|
||||
);
|
||||
if (!report) return;
|
||||
try {
|
||||
const resp = await fetch("/api/v1/reports", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "omit",
|
||||
body: JSON.stringify(report.body),
|
||||
});
|
||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
||||
for (const [url, t] of report.marks) this.marks.set(url, t);
|
||||
if (this.failing) {
|
||||
log.debug("Report delivery recovered");
|
||||
this.failing = false;
|
||||
}
|
||||
} catch (err) {
|
||||
if (!this.failing) {
|
||||
log.debug(`Report delivery failed: ${err.message}`);
|
||||
this.failing = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Latency Measurement -----------------------------------------------------
|
||||
|
||||
async function measureLatency(url) {
|
||||
@@ -1162,6 +1279,9 @@ async function init() {
|
||||
buildUI(state);
|
||||
log.info("UI built, starting tick loop");
|
||||
|
||||
const reporter = new Reporter(state, getClientId(), CONFIG.reportInterval);
|
||||
reporter.start();
|
||||
|
||||
document
|
||||
.getElementById("pause-btn")
|
||||
.addEventListener("click", () => togglePause(state));
|
||||
|
||||
Reference in New Issue
Block a user