v0.2.0 — pre-beta: per-MAC bindings, /metrics, themes, animated forge

This is the bulk pre-beta cleanup pass. Bumps the workspace to 0.2.0.
Test count is 56 -> 66 (+10), clippy is fully clean across the
workspace (was several dozen warnings).

## New features

**Per-MAC host bindings** (Tinkerbell smee pattern). New
`HostBindings` registry maps a MAC -> preferred boot target, persisted
to <work_dir>/hosts.json. The DHCP reply now embeds `?mac=${mac}` in
the boot.ipxe URL; iPXE substitutes the literal MAC client-side, so
the HTTP layer can short-circuit straight to the bound target instead
of rendering the menu. Reserved menu shortcuts (`_local`, `_gate`,
`_tools_menu`) are valid targets too. New /api/hosts CRUD + a Hosts
tab in the sidebar.

**Prometheus `/metrics`** endpoint. Tiny lock-free implementation —
just AtomicU64s and a Display impl, no `prometheus` / `metrics-rs`
dep. Counters: DHCP replies (per arch label), DHCP declined, TFTP
transfers (per status), TFTP bytes, HTTP requests (per route).
Gauges: ISO count, client count, gate count, gate-imaging, NFS active
mounts, uptime, build info. Plain text exposition format,
text/plain;version=0.0.4 content-type, no auth (all metric values are
non-sensitive counts).

**Light + dark themes**. CSS tokens on `:root` and
`:root[data-theme=light]`, swap by toggle button (top-right) or `T`
hotkey. Persisted in localStorage; pre-paint inline script avoids
dark<->light flash. Light palette designed against the Netbox Labs
reference screenshot — near-white surfaces, soft grey dividers,
accent unchanged for brand consistency. Terminal pane stays dark in
both themes (it's a console, that's the right read).

**Animated SVG logo + forge widget**. New `logo.svg` is a refined
silver/grey anvil. New `anvil-forge.svg` adds rising sparks and a
pulsing underglow via SMIL — pure SVG, no GIF, no JS animation loop.
Used:
  - in the **forge progress** widget on Dashboard + Forge Gate, paired
    with a `linear-gradient(warn -> accent)` bar with a moving sheen;
    goes idle (greyscale, no sheen) at zero imaging load
  - in the page-load `<div class=loader>` that replaces the old
    "Loading..." text

## Code cleanup pass

`cargo clippy --workspace --all-targets` is now warning-free. Spot
fixes across the tree:
  - `format!()`-into-`String` -> `std::fmt::Write::write!`
  - manual reverse comparators -> `Reverse`
  - `map_or(false, ...)` -> `is_some_and`
  - redundant closures -> method references
  - `r#"..."#` raw strings without `"` -> `r"..."`
  - `std::io::Error::new(Other, ...)` -> `Error::other`
  - `as i32` on `c.id()` -> `cast_signed()`
  - merged identical match arms

## Windows workflow validation

New integration test synthesizes an ISO9660 with the SOURCES\\BOOT.WIM
sentinel, uploads it, asserts:
  1. introspection labels it `windows_pe` with has_boot_wim=true,
  2. the boot entry is `BootKind::Wimboot` with all five canonical
     files (bootmgr, bootmgr.efi, bcd, boot.sdi, boot.wim),
  3. the rendered iPXE script chains wimboot with `initrd --name`
     entries for each file, and
  4. NO trust-store strings appear in the rendered output: bcdedit,
     testsigning, certutil, httpdisk, and test-signed are all
     explicitly forbidden as a hard guarantee.

WinPE bootstrap (startnet.cmd) picks up the Bootimus v0.1.58 lessons:
explicit `net start Workstation` before `net use` to avoid the SMB
client lazy-init race, and surfaces errors instead of blind retries.

## Docs

architecture.md gains a "Phase 5" section explaining the host-bindings
+ metrics + theming + Windows-test work, plus a refreshed "deferred
to Phase 6" list (real-hardware integration, autounattend library,
distro profile manifest, WoL trigger, syslog receiver, IPv6).
README updates the status line, the "what it does" list, and adds
the new Hosts/Terminal tab names.
This commit is contained in:
Miles Ward
2026-04-30 02:28:10 -04:00
parent a9c4f408a9
commit 49d0b00a8a
31 changed files with 1651 additions and 209 deletions
+1 -2
View File
@@ -49,9 +49,8 @@ impl ClientArch {
// ARM32 UEFI: upstream boot.ipxe.org does not publish a prebuilt
// snponly variant for this arch. We return None so the DHCP
// proxy declines rather than advertising a file we can't serve.
Self::Arm32Uefi => return None,
Self::Arm32Uefi | Self::Unknown(_) => return None,
Self::Arm64Uefi => "snponly-arm64.efi",
Self::Unknown(_) => return None,
})
}
+2 -1
View File
@@ -89,7 +89,8 @@ impl ClientRegistry {
pub fn list(&self) -> Vec<ClientSnapshot> {
let guard = self.inner.read();
let mut v: Vec<_> = guard.values().cloned().collect();
v.sort_by(|a, b| b.last_seen.cmp(&a.last_seen));
// Reverse-chronological by last-seen (most recent first).
v.sort_by_key(|c| std::cmp::Reverse(c.last_seen));
v
}
+4 -10
View File
@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
use std::net::{IpAddr, Ipv4Addr};
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
pub server: ServerConfig,
@@ -113,15 +113,9 @@ impl Default for Paths {
}
}
impl Default for Config {
fn default() -> Self {
Self {
server: ServerConfig::default(),
network: NetworkConfig::default(),
paths: Paths::default(),
}
}
}
// `Config` derives `Default` because each component supplies its own
// non-trivial defaults via `impl Default` blocks above; deriving keeps
// this in sync if a new section is added.
impl Config {
pub fn from_toml_file(path: &Path) -> crate::Result<Self> {
+1 -1
View File
@@ -246,7 +246,7 @@ mod tests {
q3.touch(&id)
});
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
q2.assign(&[g.id.clone()], "x");
q2.assign(std::slice::from_ref(&g.id), "x");
let result = fut.await.unwrap();
assert!(result.is_some());
assert_eq!(result.unwrap().assigned_target.as_deref(), Some("x"));
+235
View File
@@ -0,0 +1,235 @@
//! Per-MAC host bindings.
//!
//! Inspired by the Tinkerbell `smee` "MAC-prepended URL" pattern: an
//! operator can attach a preferred boot target (a `BootEntry::id`) to a
//! specific MAC address. When a client with that MAC arrives, the
//! top-level boot script chains straight to that target instead of
//! showing the interactive menu.
//!
//! Use cases:
//! - "This rack of Dell servers always images with Ubuntu Server 24.04"
//! - "Tom's laptop always boots from local disk"
//! - "Bench QA machines always boot Memtest until released"
//!
//! Persisted to `<work_dir>/hosts.json`. Like the SettingsStore, on-disk
//! corruption falls back to an empty registry rather than failing
//! startup — a bad hosts file should never block PXE for the network.
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use time::OffsetDateTime;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HostBinding {
/// Lowercase, colon-separated MAC (e.g. `aa:bb:cc:dd:ee:ff`). The
/// HTTP layer normalizes incoming MACs before lookup so callers
/// don't have to worry about case.
pub mac: String,
/// Preferred boot entry id (matches a `BootEntry::id` in the iso
/// store) OR one of the reserved menu names: `_local`, `_gate`,
/// `_tools_menu`. Empty string falls back to the menu.
pub target: String,
/// Optional human-readable label shown in the UI (`"Tom's laptop"`,
/// `"rack-3 spine"`). Empty if unset.
#[serde(default)]
pub label: String,
#[serde(with = "time::serde::rfc3339")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::rfc3339")]
pub updated_at: OffsetDateTime,
}
#[derive(Debug, Default)]
struct Inner {
by_mac: HashMap<String, HostBinding>,
}
/// Registry of per-MAC bindings. Cheap to clone; locks are held
/// briefly. Persistence is best-effort and mirrors `SettingsStore`'s
/// "in-memory authoritative, disk is a cache" policy.
#[derive(Debug, Clone)]
pub struct HostBindings {
path: Arc<PathBuf>,
inner: Arc<RwLock<Inner>>,
}
impl HostBindings {
/// Load from `work_dir/hosts.json`, or start empty if absent /
/// unreadable.
#[must_use]
pub fn load_or_default(work_dir: &std::path::Path) -> Self {
let path = work_dir.join("hosts.json");
let inner = match std::fs::read_to_string(&path) {
Ok(text) => match serde_json::from_str::<Vec<HostBinding>>(&text) {
Ok(items) => {
let mut by_mac = HashMap::new();
for b in items {
by_mac.insert(normalize_mac(&b.mac), b);
}
Inner { by_mac }
}
Err(e) => {
tracing::warn!(
target: "pxeforge::hosts",
"hosts.json present but unreadable ({e}); starting empty"
);
Inner::default()
}
},
Err(_) => Inner::default(),
};
Self {
path: Arc::new(path),
inner: Arc::new(RwLock::new(inner)),
}
}
/// Look up a binding by MAC. Match is case-insensitive and tolerates
/// `-` or `:` separators.
#[must_use]
pub fn lookup(&self, mac: &str) -> Option<HostBinding> {
self.inner.read().by_mac.get(&normalize_mac(mac)).cloned()
}
/// Insert or update. Returns the resulting binding (with timestamps).
pub fn upsert(&self, mac: &str, target: &str, label: &str) -> HostBinding {
let key = normalize_mac(mac);
let now = OffsetDateTime::now_utc();
let binding = {
let mut g = self.inner.write();
let entry = g.by_mac.entry(key.clone()).or_insert_with(|| HostBinding {
mac: key.clone(),
target: target.to_string(),
label: label.to_string(),
created_at: now,
updated_at: now,
});
entry.target = target.to_string();
entry.label = label.to_string();
entry.updated_at = now;
entry.clone()
};
self.persist();
binding
}
/// Remove a binding. Returns true if something was removed.
pub fn remove(&self, mac: &str) -> bool {
let key = normalize_mac(mac);
let removed = self.inner.write().by_mac.remove(&key).is_some();
if removed {
self.persist();
}
removed
}
#[must_use]
pub fn list(&self) -> Vec<HostBinding> {
let g = self.inner.read();
let mut v: Vec<_> = g.by_mac.values().cloned().collect();
v.sort_by(|a, b| a.mac.cmp(&b.mac));
v
}
#[must_use]
pub fn len(&self) -> usize {
self.inner.read().by_mac.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
fn persist(&self) {
let items: Vec<HostBinding> = self.inner.read().by_mac.values().cloned().collect();
let body = match serde_json::to_vec_pretty(&items) {
Ok(b) => b,
Err(e) => {
tracing::warn!(target: "pxeforge::hosts", "serialize hosts.json: {e}");
return;
}
};
let tmp = self.path.with_extension("json.tmp");
if let Some(parent) = self.path.parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Err(e) = std::fs::write(&tmp, body) {
tracing::warn!(target: "pxeforge::hosts", "write hosts.json tmp: {e}");
return;
}
if let Err(e) = std::fs::rename(&tmp, self.path.as_path()) {
tracing::warn!(target: "pxeforge::hosts", "rename hosts.json: {e}");
}
}
}
/// Lowercase a MAC and normalise `-` separators to `:`. We never strip
/// the separator entirely — `aabbccddeeff` formats are rejected at the
/// HTTP layer because they're ambiguous (could be a device id).
#[must_use]
pub fn normalize_mac(mac: &str) -> String {
mac.trim().to_ascii_lowercase().replace('-', ":")
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[test]
fn normalize_handles_case_and_dashes() {
assert_eq!(normalize_mac("AA:BB:CC:DD:EE:FF"), "aa:bb:cc:dd:ee:ff");
assert_eq!(normalize_mac("aa-bb-cc-dd-ee-ff"), "aa:bb:cc:dd:ee:ff");
assert_eq!(normalize_mac(" aA-Bb-CC:DD-ee:fF "), "aa:bb:cc:dd:ee:ff");
}
#[test]
fn upsert_then_lookup() {
let dir = tempdir().unwrap();
let h = HostBindings::load_or_default(dir.path());
assert!(h.is_empty());
h.upsert("AA:BB:CC:00:00:01", "ubuntu-24-04-linux", "rack-3 spine");
let found = h.lookup("aa-bb-cc-00-00-01").expect("lookup");
assert_eq!(found.target, "ubuntu-24-04-linux");
assert_eq!(found.label, "rack-3 spine");
assert_eq!(found.mac, "aa:bb:cc:00:00:01");
}
#[test]
fn upsert_replaces_existing_target() {
let dir = tempdir().unwrap();
let h = HostBindings::load_or_default(dir.path());
h.upsert("aa:bb:cc:00:00:01", "old-target", "label1");
h.upsert("aa:bb:cc:00:00:01", "new-target", "label2");
assert_eq!(h.len(), 1);
let b = h.lookup("aa:bb:cc:00:00:01").unwrap();
assert_eq!(b.target, "new-target");
assert_eq!(b.label, "label2");
}
#[test]
fn remove_works_and_reports_outcome() {
let dir = tempdir().unwrap();
let h = HostBindings::load_or_default(dir.path());
h.upsert("aa:bb:cc:00:00:01", "x", "");
assert!(h.remove("AA:BB:CC:00:00:01"));
assert!(!h.remove("aa:bb:cc:00:00:01")); // already gone
assert!(h.is_empty());
}
#[test]
fn round_trip_persists_to_disk() {
let dir = tempdir().unwrap();
let h = HostBindings::load_or_default(dir.path());
h.upsert("aa:bb:cc:00:00:01", "ubuntu-linux", "rack-3");
h.upsert("aa:bb:cc:00:00:02", "_local", "tom-laptop");
drop(h);
let h2 = HostBindings::load_or_default(dir.path());
assert_eq!(h2.len(), 2);
assert_eq!(h2.lookup("aa:bb:cc:00:00:02").unwrap().target, "_local");
}
}
+4
View File
@@ -7,7 +7,9 @@ pub mod client;
pub mod config;
pub mod error;
pub mod gate;
pub mod host_bindings;
pub mod log_bus;
pub mod metrics;
pub mod settings;
pub use arch::{ClientArch, FirmwareClass};
@@ -15,5 +17,7 @@ pub use client::{ClientEvent, ClientRegistry, ClientSnapshot};
pub use config::{Config, DhcpMode, NetworkConfig, Paths, ServerConfig};
pub use error::{Error, Result};
pub use gate::{Gate, GateQueue};
pub use host_bindings::{normalize_mac, HostBinding, HostBindings};
pub use log_bus::{LogBus, LogBusLayer, LogLine};
pub use metrics::{HttpRoute, Metrics};
pub use settings::{Settings, SettingsStore, TimeoutAction};
+283
View File
@@ -0,0 +1,283 @@
//! Tiny lock-free Prometheus-compatible metrics.
//!
//! We don't pull in `prometheus` or `metrics-rs` for this — they bring
//! their own runtime, registry, and complexity. PXEForge has a fixed,
//! tiny set of counters/gauges and the exposition format is plain text.
//! A handful of `AtomicU64`s and a `Display` impl gets us everything
//! Prometheus / Grafana / VictoriaMetrics needs to scrape:
//!
//! pxeforge_dhcp_replies_total counter (per arch label)
//! pxeforge_tftp_transfers_total counter (per status label)
//! pxeforge_tftp_bytes_total counter
//! pxeforge_http_requests_total counter (per route label)
//! pxeforge_iso_count gauge
//! pxeforge_client_count gauge
//! pxeforge_gate_count gauge
//! pxeforge_gate_imaging gauge
//! pxeforge_uptime_seconds gauge
//! pxeforge_build_info{version} gauge (always 1)
//!
//! Cheap to clone — internal state is a couple of arcs. Counters use
//! `Relaxed` ordering: we don't synchronise across counters, just need
//! per-counter monotonicity.
use std::fmt::Write as _;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
#[derive(Debug, Default)]
#[allow(clippy::struct_field_names)]
struct Inner {
// DHCP proxy
dhcp_replies_legacy: AtomicU64,
dhcp_replies_uefi: AtomicU64,
dhcp_replies_arm64: AtomicU64,
dhcp_replies_unknown: AtomicU64,
dhcp_declined: AtomicU64,
// TFTP
tftp_transfers_ok: AtomicU64,
tftp_transfers_err: AtomicU64,
tftp_bytes: AtomicU64,
// HTTP
http_boot_script: AtomicU64,
http_iso_range: AtomicU64,
http_iso_inner: AtomicU64,
http_ipxe_binary: AtomicU64,
http_api: AtomicU64,
// Gauges (set explicitly; not cumulative)
iso_count: AtomicU64,
client_count: AtomicU64,
gate_count: AtomicU64,
gate_imaging: AtomicU64,
nfs_mounts_active: AtomicU64,
}
#[derive(Debug, Clone, Default)]
pub struct Metrics {
inner: Arc<Inner>,
}
impl Metrics {
#[must_use]
pub fn new() -> Self {
Self::default()
}
// ── DHCP ───────────────────────────────────────────────────────────
pub fn record_dhcp_reply(&self, arch: &str) {
let counter = match arch {
"bios" => &self.inner.dhcp_replies_legacy,
"uefi-x64" | "uefi-ia32" => &self.inner.dhcp_replies_uefi,
"uefi-arm64" => &self.inner.dhcp_replies_arm64,
_ => &self.inner.dhcp_replies_unknown,
};
counter.fetch_add(1, Ordering::Relaxed);
}
pub fn record_dhcp_decline(&self) {
self.inner.dhcp_declined.fetch_add(1, Ordering::Relaxed);
}
// ── TFTP ───────────────────────────────────────────────────────────
pub fn record_tftp_ok(&self, bytes: u64) {
self.inner.tftp_transfers_ok.fetch_add(1, Ordering::Relaxed);
self.inner.tftp_bytes.fetch_add(bytes, Ordering::Relaxed);
}
pub fn record_tftp_err(&self) {
self.inner.tftp_transfers_err.fetch_add(1, Ordering::Relaxed);
}
// ── HTTP ───────────────────────────────────────────────────────────
pub fn record_http(&self, route: HttpRoute) {
let counter = match route {
HttpRoute::BootScript => &self.inner.http_boot_script,
HttpRoute::IsoRange => &self.inner.http_iso_range,
HttpRoute::IsoInner => &self.inner.http_iso_inner,
HttpRoute::IpxeBinary => &self.inner.http_ipxe_binary,
HttpRoute::Api => &self.inner.http_api,
};
counter.fetch_add(1, Ordering::Relaxed);
}
// ── Gauges ─────────────────────────────────────────────────────────
pub fn set_iso_count(&self, n: u64) {
self.inner.iso_count.store(n, Ordering::Relaxed);
}
pub fn set_client_count(&self, n: u64) {
self.inner.client_count.store(n, Ordering::Relaxed);
}
pub fn set_gate_counts(&self, total: u64, imaging: u64) {
self.inner.gate_count.store(total, Ordering::Relaxed);
self.inner.gate_imaging.store(imaging, Ordering::Relaxed);
}
pub fn set_nfs_active(&self, n: u64) {
self.inner.nfs_mounts_active.store(n, Ordering::Relaxed);
}
/// Render in the Prometheus text exposition format.
/// Uptime is supplied by the caller because `Metrics` doesn't own
/// the start instant; the HTTP layer does.
#[must_use]
pub fn render(&self, version: &str, uptime_secs: u64) -> String {
let mut out = String::with_capacity(2048);
let i = &self.inner;
// Helper closures.
let write_counter = |o: &mut String, name: &str, help: &str, val: u64, lbl: &str| {
let _ = writeln!(o, "# HELP {name} {help}");
let _ = writeln!(o, "# TYPE {name} counter");
if lbl.is_empty() {
let _ = writeln!(o, "{name} {val}");
} else {
let _ = writeln!(o, "{name}{{{lbl}}} {val}");
}
};
let write_gauge = |o: &mut String, name: &str, help: &str, val: u64, lbl: &str| {
let _ = writeln!(o, "# HELP {name} {help}");
let _ = writeln!(o, "# TYPE {name} gauge");
if lbl.is_empty() {
let _ = writeln!(o, "{name} {val}");
} else {
let _ = writeln!(o, "{name}{{{lbl}}} {val}");
}
};
// Counters with one HELP/TYPE per metric name and per-label rows.
let _ = writeln!(out, "# HELP pxeforge_dhcp_replies_total Number of proxyDHCP replies sent, by client architecture.");
let _ = writeln!(out, "# TYPE pxeforge_dhcp_replies_total counter");
let _ = writeln!(
out,
"pxeforge_dhcp_replies_total{{arch=\"bios\"}} {}",
i.dhcp_replies_legacy.load(Ordering::Relaxed)
);
let _ = writeln!(
out,
"pxeforge_dhcp_replies_total{{arch=\"uefi\"}} {}",
i.dhcp_replies_uefi.load(Ordering::Relaxed)
);
let _ = writeln!(
out,
"pxeforge_dhcp_replies_total{{arch=\"arm64\"}} {}",
i.dhcp_replies_arm64.load(Ordering::Relaxed)
);
let _ = writeln!(
out,
"pxeforge_dhcp_replies_total{{arch=\"unknown\"}} {}",
i.dhcp_replies_unknown.load(Ordering::Relaxed)
);
write_counter(
&mut out,
"pxeforge_dhcp_declined_total",
"DHCP requests we saw but did not reply to (mac filter, arch unsupported, etc).",
i.dhcp_declined.load(Ordering::Relaxed),
"",
);
let _ = writeln!(out, "# HELP pxeforge_tftp_transfers_total TFTP transfers, by status.");
let _ = writeln!(out, "# TYPE pxeforge_tftp_transfers_total counter");
let _ = writeln!(
out,
"pxeforge_tftp_transfers_total{{status=\"ok\"}} {}",
i.tftp_transfers_ok.load(Ordering::Relaxed)
);
let _ = writeln!(
out,
"pxeforge_tftp_transfers_total{{status=\"err\"}} {}",
i.tftp_transfers_err.load(Ordering::Relaxed)
);
write_counter(
&mut out,
"pxeforge_tftp_bytes_total",
"Total bytes successfully delivered over TFTP.",
i.tftp_bytes.load(Ordering::Relaxed),
"",
);
let _ = writeln!(out, "# HELP pxeforge_http_requests_total HTTP requests served, by route family.");
let _ = writeln!(out, "# TYPE pxeforge_http_requests_total counter");
for (label, counter) in [
("boot_script", &i.http_boot_script),
("iso_range", &i.http_iso_range),
("iso_inner", &i.http_iso_inner),
("ipxe_binary", &i.http_ipxe_binary),
("api", &i.http_api),
] {
let _ = writeln!(
out,
"pxeforge_http_requests_total{{route=\"{label}\"}} {}",
counter.load(Ordering::Relaxed)
);
}
// Gauges.
write_gauge(&mut out, "pxeforge_iso_count", "ISOs currently registered (local + NFS).", i.iso_count.load(Ordering::Relaxed), "");
write_gauge(&mut out, "pxeforge_client_count", "PXE clients seen this process lifetime.", i.client_count.load(Ordering::Relaxed), "");
write_gauge(&mut out, "pxeforge_gate_count", "Clients currently waiting at the deployment gate.", i.gate_count.load(Ordering::Relaxed), "");
write_gauge(&mut out, "pxeforge_gate_imaging", "Clients currently imaging (gate + assigned target).", i.gate_imaging.load(Ordering::Relaxed), "");
write_gauge(&mut out, "pxeforge_nfs_mounts_active", "NFS shares currently mounted.", i.nfs_mounts_active.load(Ordering::Relaxed), "");
write_gauge(&mut out, "pxeforge_uptime_seconds", "Seconds since this PXEForge instance started.", uptime_secs, "");
let _ = writeln!(out, "# HELP pxeforge_build_info Build metadata. Always 1; the version is in the label.");
let _ = writeln!(out, "# TYPE pxeforge_build_info gauge");
let _ = writeln!(out, "pxeforge_build_info{{version=\"{version}\"}} 1");
out
}
}
/// Stable label values for the HTTP route counter. Adding a new route
/// here without updating `record_http` will break compilation, which is
/// exactly the safety we want — Prometheus alerts on cardinality drift,
/// so accidental new label values matter.
#[derive(Debug, Clone, Copy)]
pub enum HttpRoute {
BootScript,
IsoRange,
IsoInner,
IpxeBinary,
Api,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn render_emits_each_metric_family_once() {
let m = Metrics::new();
m.record_dhcp_reply("uefi-x64");
m.record_dhcp_reply("bios");
m.record_tftp_ok(1024);
m.record_http(HttpRoute::Api);
m.set_iso_count(3);
let out = m.render("0.2.0", 42);
assert_eq!(out.matches("# TYPE pxeforge_dhcp_replies_total counter").count(), 1);
assert_eq!(out.matches("# TYPE pxeforge_iso_count gauge").count(), 1);
assert!(out.contains("pxeforge_dhcp_replies_total{arch=\"uefi\"} 1"));
assert!(out.contains("pxeforge_dhcp_replies_total{arch=\"bios\"} 1"));
assert!(out.contains("pxeforge_tftp_transfers_total{status=\"ok\"} 1"));
assert!(out.contains("pxeforge_tftp_bytes_total 1024"));
assert!(out.contains("pxeforge_http_requests_total{route=\"api\"} 1"));
assert!(out.contains("pxeforge_iso_count 3"));
assert!(out.contains("pxeforge_uptime_seconds 42"));
assert!(out.contains("pxeforge_build_info{version=\"0.2.0\"} 1"));
}
#[test]
fn cloned_metrics_share_state() {
let a = Metrics::new();
let b = a.clone();
a.record_dhcp_reply("bios");
b.record_dhcp_reply("bios");
let out = a.render("test", 0);
assert!(out.contains("pxeforge_dhcp_replies_total{arch=\"bios\"} 2"));
}
}