Repository navigation
feat(cli): add decdn node top live metrics view (#275) - #485
Conversation
Coverage reportTotal: 88.58% (was 87.90%, ▲ +0.68%) — 12675/14309 lines
History
|
There was a problem hiding this comment.
Pull request overview
Adds a new user-facing CLI subcommand, decdn node top, which scrapes the running daemon’s /metrics endpoint and renders a live “top”-style view (or single-shot JSON) to improve operator visibility without requiring Prometheus/Grafana.
Changes:
- Introduces
decdn node topCLI args + dispatch wiring, including config-based metrics URL resolution with operator-friendly missing-file semantics. - Implements the
node topscraper/parser/renderer with unit tests and in-module e2e tests against a real metrics server. - Exposes
DEFAULT_METRICS_PORTfrom common config so the CLI can share the daemon’s canonical default.
Reviewed changes
Copilot reviewed 8 out of 9 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/common/src/config/mod.rs | Makes DEFAULT_METRICS_PORT public for CLI reuse. |
| crates/common/src/cli/node.rs | Adds NodeCommand::Top and defines TopArgs. |
| crates/common/src/cli/mod.rs | Re-exports TopArgs. |
| crates/common/src/cli/common.rs | Introduces shared ConfigPathSource enum for config resolution semantics. |
| crates/cli/src/commands/node.rs | Wires node top into the node command dispatcher and reuses shared ConfigPathSource. |
| crates/cli/src/commands/node_top.rs | Implements metrics scraping/parsing, live table rendering, JSON mode, and tests/e2e coverage. |
| crates/cli/src/commands/mod.rs | Exposes the new node_top module. |
| crates/cli/Cargo.toml | Adds reqwest dependency for HTTP scraping. |
| Cargo.lock | Locks new dependency graph including reqwest. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Code Review
This pull request introduces the decdn node top command, which provides a live view of node activity by scraping the daemon's /metrics HTTP endpoint. The implementation includes a new node_top module with logic for parsing OpenMetrics data, calculating per-second deltas, and rendering both a live terminal table and JSON snapshots. Additionally, ConfigPathSource was moved to a common CLI module to unify configuration path handling across subcommands. I have no feedback to provide as the existing review comment was purely explanatory and did not identify any issues or required improvements.
…275) Two findings from PR review on #485: 1. format!("{url_base}/metrics") broke for operator-supplied URLs with a trailing slash ("http://h:9090/" → "//metrics") or that already pointed at /metrics ("http://h:9090/metrics" → "/metrics/metrics"). Both produce 404s on most servers. Add append_metrics_path() that strips a trailing slash and avoids double-appending the suffix; covers the four URL shapes (bare/trailing-slash/already-complete/both) plus path-prefixed bases for reverse-proxy setups. New unit test locks in the normalisation. 2. fetch_metrics_surfaces_non_2xx_as_error claimed in its comment to ".unwrap() the JoinError so a panic in the spawned write loop surfaces with the real cause" but actually had `let _ = ...`. The comment lied — fix the code to match (and the e2e test above): timeout → ?, then JoinError → ?. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…t dep (#275) Bundles the clap variant + dispatch wiring as one commit because the exhaustiveness check on `node_dispatch` couples them: a half-landed variant breaks the workspace clippy gate that runs in pre-commit. - `NodeCommand::Top(TopArgs)` with `--metrics-url` / `--config` / `--interval-ms` / `--json` / `--timeout-ms`, mirroring the existing `Peers` arg shape so operators get the same resolution semantics. - `crates/cli/src/commands/node_top.rs` is a stub that bails — later tasks fill in the parser, snapshot, renderer, and fetch loop. - `DEFAULT_METRICS_PORT` is promoted to `pub` so the resolver can fall back to the same port the daemon binds on without duplicating 9090. - `reqwest` enters `crates/cli`'s runtime deps; the daemon already uses the workspace pin (rustls + no default features). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Tiny line-based parser scoped to the label-free `decdn_*` series the daemon registers. Skips `# HELP`/`# TYPE`/`# EOF` directives and labelled lines silently — the latter so a future label addition on the metrics surface degrades to "unknown values" rather than panics. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Snapshot reads selected `decdn_*` fields out of the parsed metric map with saturating-to-zero handling for missing or NaN values. Older daemons missing some metric must not panic — they should render zero and let the operator see the gap. SnapshotDelta::between divides counter differences by an elapsed Duration, returning all-zero on zero elapsed (Instant::now()-prev_at can be sub-tick on a fast loop and would otherwise produce NaN/inf). hit_rate returns None on 0/0 so the renderer can show n/a vs. 0.0%. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
write_top_table renders to any impl Write, mirroring the existing write_peers_table pattern so unit tests can compare exact output without HTTP. Header line carries uptime / rpc status / active counters; the body is a fixed-column METRIC | VALUE | /sec table with per-second deltas computed against the previous snapshot. format_bytes uses strict binary units (KiB/MiB/...) so the displayed value matches the raw counter when divided by the obvious power of two. format_rate_bytes guards against negative/non-finite input that SnapshotDelta could in theory produce on a counter wraparound. format_uptime collapses seconds → s/m/h/d notation for the header. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
render_json_snapshot is hand-rolled rather than serde-derived so the public output schema (field names + ordering + null `hit_rate` on empty cache) is decoupled from the internal Snapshot field order. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
resolve_metrics_url mirrors resolve_admin_url's flag → env → config file → default precedence so the operator's experience for `node top` matches `node peers`. Host is hard-coded to 127.0.0.1 because the daemon's metrics_bind can be 0.0.0.0/:: which a client should never dial; the operator overrides with --metrics-url for a non-loopback endpoint. Partial deserialization of `[observability]` only — a typo elsewhere in the config must not cost the operator the ability to point top at the daemon. metrics_port = 0 is treated as the explicit operator opt-out (no metrics server) and produces an actionable error. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The plain-text mode runs a tokio::time::interval at --interval-ms, clears the screen + redraws between ticks, and computes per-second deltas against the previous snapshot. Ctrl-C exits cleanly via tokio::signal::ctrl_c selected against the ticker, leaving the terminal in a usable state. Scrape errors print to stderr and the loop continues — operators need stickiness across daemon restarts; a transient ECONNREFUSED shouldn't require re-running `decdn node top`. JSON mode is single- shot: one fetch, pretty JSON to stdout, exit. Removes the now-redundant dead_code allows on items wired into the loop. format_uptime + Snapshot + SnapshotDelta + write_top_table are all part of the live path now. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ver (#275) Spawns decdn_node::metrics::serve on an ephemeral loopback port, bumps a couple of counters via the engine-side handles, scrapes via reqwest, and asserts that the parser + Snapshot pipeline reflects the bumps. Also drives the high-level `run` in JSON mode end-to-end to smoke-test resolver → fetch → render → exit doesn't panic against a real daemon endpoint. Promotes parse_openmetrics and Snapshot::from_metrics to pub so the integration test (a separate crate from the lib) can exercise them directly. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
) The previous loop swallowed every fetch error and re-printed it every tick forever, even for permanent classes (malformed URL, unsupported scheme, persistent 4xx). And `let _ = stdout.write_all/flush(...)` silently dropped output failures while the next call's `?` would have surfaced them — leaving the door open for a half-rendered table on a transient stdout hiccup. - Add MAX_CONSECUTIVE_SCRAPE_FAILURES = 30: after 30 failed ticks in a row (≈30s at the default 1Hz refresh) the loop gives up with the last error wrapped. A successful scrape resets the counter, so a real flap during a daemon restart still recovers. - Fast-fail on `reqwest::Error::is_builder()` (URL parse, unsupported scheme): the URL is fixed for the process lifetime, so retrying buys nothing. Walk the anyhow source chain via `.chain()` because fetch_metrics wraps the reqwest error with `with_context`. - Replace `let _ =` on the two stdout writes with `?`-propagated context. A clear-screen failure now bails the loop instead of letting the next render produce a corrupted display against an inconsistent terminal state. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…275) Promoting parse_openmetrics, Snapshot, and Snapshot::from_metrics to `pub` was an API exposure paid for one black-box test that no production caller needs. Move the test into a `#[cfg(test)]` module inside node_top.rs so the assertions can use `pub(crate)` items directly, and revert the three promotions. Drive-bys made possible by the move: - The spawned server task now captures `serve`'s Result; the test unwraps the JoinError outside the timeout so a panic or encoder error surfaces as a real failure with the actual cause, rather than the previous "got 0, expected 1" downstream confusion. - New `fetch_metrics_surfaces_non_2xx_as_error` covers the 503 arm in fetch_metrics' status check — locks in the bail so a future refactor that stopped checking status fails here rather than silently feeding HTML to the parser. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…#275) Two type-design tightenings flagged by review: 1. ConfigPathSource was duplicated verbatim across node.rs and node_top.rs (same shape, same docstring spirit). Hoist to `decdn_common::cli::common` next to expand_tilde and default_config_path — both call sites already import from there. 2. SnapshotDelta fields all ended in `_per_sec`, which is just the unit, redundant with the type name, and triggered a `clippy::struct_field_names` allow. Rename to `hits` / `misses` / `bytes`; drop the allow. The unit is implicit in the type name (compare `Duration::as_secs_f64()` — the unit is in the method, the field would just be `secs` or similar). Drive-by: SnapshotDelta::between's wraparound comment used to point only at "daemon restart" — extend to cover URL re-pointing and counter resets, which were equally valid causes the comment narrowed. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…275) Six new tests + small comment/cleanup churn flagged in review: Test additions: - per_second_delta_saturates_on_counter_regression — locks in the saturating_sub behaviour at SnapshotDelta::between for the daemon-restart / URL-re-pointing case. A regression to plain `-` would silently produce a huge spike on the next tick. - format_uptime_crosses_unit_boundaries — covers 60s/3600s/86400s cross-unit transitions and the in-band cases. write_top_table exercises only the m+s shape via substring; cross-units need direct asserts. - port_from_config_file_{missing_default_returns_none, missing_explicit_errors, errors_on_invalid_toml, ignores_unrelated_field_errors} — bring metrics-side parity with the 7-test admin_port suite in node.rs. Drive-bys: - hit_rate now uses saturating_add for u64 symmetry. - Tighten three docstrings: parser doc no longer claims to distinguish HELP/TYPE/UNIT/EOF (it skips all `#` lines), Snapshot saturation comment now covers the upper-bound clamp too, and SnapshotDelta wraparound rationale extends beyond "daemon restart" to URL re-pointing / counter resets. - Trim two narrative comments at run() and render_json_snapshot. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
CI clippy (rust-toolchain@stable → 1.95) flagged 4 call sites of `Duration::from_millis(1000)` under `clippy::duration_suboptimal_units`, a lint added in 1.95. My local toolchain (1.93) didn't ship the lint, so pre-commit ran clean despite the bug. Mechanically replace with `Duration::from_secs(1)` — same value, satisfies the lint. No semantic change. Verified by running `cargo +1.95.0 clippy --workspace --all-targets -- -D warnings` locally before pushing this time. Process gap (lints from a newer toolchain than the local pre-commit's won't be caught) tracked separately. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…275) Two findings from PR review on #485: 1. format!("{url_base}/metrics") broke for operator-supplied URLs with a trailing slash ("http://h:9090/" → "//metrics") or that already pointed at /metrics ("http://h:9090/metrics" → "/metrics/metrics"). Both produce 404s on most servers. Add append_metrics_path() that strips a trailing slash and avoids double-appending the suffix; covers the four URL shapes (bare/trailing-slash/already-complete/both) plus path-prefixed bases for reverse-proxy setups. New unit test locks in the normalisation. 2. fetch_metrics_surfaces_non_2xx_as_error claimed in its comment to ".unwrap() the JoinError so a panic in the spawned write loop surfaces with the real cause" but actually had `let _ = ...`. The comment lied — fix the code to match (and the e2e test above): timeout → ?, then JoinError → ?. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…275) Two findings from round-2 review: 1. append_metrics_path mishandled query strings and fragments. `http://h:9090?token=foo` produced `http://h:9090?token=foo/metrics` — `/metrics` spliced inside the query value, 404 on every sane server. Fix: split off `?` / `#` before doing the trim/append, reattach after. New test covers query, fragment, query-then- fragment, and the previously-broken combinations. 2. resolve_metrics_url_falls_back_to_default_port_when_no_config read `~/.decdn/node.toml` if it existed, making the test non-hermetic on developer machines that have a real config. Replace with port_from_config_file_returns_none_when_path_is_none which locks the load-bearing helper-layer invariant directly (`Ok(None)` regardless of source). The DEFAULT_METRICS_PORT fallback is still implicitly covered: resolve_metrics_url's `port?.unwrap_or(DEFAULT_METRICS_PORT)` is one line, and the constant's identity is locked by the resolve_metrics_url_reads_observability_metrics_port_from_file positive path. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…nup (#275) Round-2 review follow-ups bundled because they all touch the same classifier surface: - fetch_metrics now tags 4xx (except 408 Request Timeout / 429 Too Many Requests) with PERMANENT_STATUS_TAG via anyhow context. A daemon that's reachable but returns 404 on the metrics path is not transient; previously it would loop for 30s before bailing. - is_permanent_url_error → is_permanent_scrape_error (broader name matches the new 4xx coverage; reqwest::Error::is_builder() never was URL-only — it also fires for unsupported schemes / missing host). Walks the chain for the sentinel string in addition to the reqwest error class. - Add `// per second` field-level comments on SnapshotDelta so rate-vs-cumulative is unambiguous at use sites where the type isn't visible (`format_rate_bytes(d.bytes)`). - Tighten resolve_metrics_url_zero_port_errors to require the exact "disables the metrics server" wording — the previous `||` let a regression that drops the operator-actionable phrasing pass. - Comment-drift fixes flagged in round 2: * SnapshotDelta::between wraparound comment dropped the spurious "--metrics-url re-pointed at a different node" item — that can't fire because the URL is fixed for the process lifetime. * MAX_CONSECUTIVE_SCRAPE_FAILURES doc qualified — "≈30s on fast-fail; up to ≈150s if scrapes time out at the default --timeout-ms 5000." * format_uptime_crosses_unit_boundaries comment said "four" cross-unit boundaries; there are three (60/3600/86400). * fetch_metrics_surfaces_non_2xx_as_error assertion was a boolean OR over two substrings that always co-occur in StatusCode's Display. Tighten to the single substring. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Round-2 review identified three test gaps: - is_permanent_scrape_error has zero direct coverage. The classifier is the only thing standing between a misconfigured --metrics-url and an indefinite retry loop, so a refactor that breaks the predicate (e.g. is_builder() → is_request(), or dropping the sentinel-string match) would silently lose the fail-fast contract. New `mod classifier_tests` with 4 cases: builder error → permanent, connection refused → transient, sentinel tag → permanent, bare anyhow → transient. Builds the reqwest errors via real Client::send() so the chain shape matches production rather than a hand-constructed mock. - MAX_CONSECUTIVE_SCRAPE_FAILURES has zero direct coverage. The cap is operator-visible and could silently regress to u32::MAX. `loop_budget_tests::run_bails_after_consecutive_failures_cap` binds-then-drops a listener (hermetic ECONNREFUSED), points `run` at it with a 1ms interval and 100ms timeout, and asserts the bail message contains "30 times in a row". Runs in under a second. - port_from_config_file_reads_metrics_port_explicit_path closes the parity gap with the admin-side suite. Without it, a regression that broadened the explicit-source error arm to swallow successes would still pass CI because all other tests use Default source. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Round-2 review: ConfigPathSource was `pub` in
`decdn_common::cli::common` but not in the `pub use common::{…}`
line at `cli/mod.rs:18`, leaving the import path exposed as
`decdn_common::cli::common::ConfigPathSource` while sibling types
(LogFormat, default_config_path, etc.) are exported as
`decdn_common::cli::ConfigPathSource`.
Add to the re-export and update both call sites
(`crates/cli/src/commands/node{,_top}.rs`) to import from the
cleaner path.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
42703b4 to
874f431
Compare
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces the "decdn node top" command, which provides a live dashboard of node activity by scraping the daemon's /metrics endpoint. The implementation includes an OpenMetrics parser, logic for calculating per-second performance deltas (hits, misses, and bytes served), and support for both a terminal-based live view and single-shot JSON output. The changes also involve refactoring configuration path handling and making the default metrics port public. I have no feedback to provide.
* feat(node): wire ADR 005 QUIC transport defaults (#328) Apply ADR 005 §Connection lifecycle / §Concurrent stream limits at the iroh endpoint: 30s max idle timeout, 10s keep-alive PING interval, and a 100-stream bidirectional cap (sized for `cdn/client/v1`, the largest ALPN). `QuicTransportConfig` is per-endpoint, not per-ALPN, so probe's tighter 1-stream bound stays enforced inside the handler — documented inline. Add a constant-guard unit test for the three values plus a behavioral loopback test that uses a 300ms idle window to verify the wiring without slowing the suite. Defers per-ALPN QUIC caps for `cdn/client/v1` and `cdn/dht/v1` until those handlers exist, and config-driven tunability until #485 merges. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fixup: address PR #491 review - Tighten QUIC_MAX_IDLE_TIMEOUT doc to call out the keep-alive interaction: 10s PINGs refresh the 30s timer, so the QUIC idle reaper is a defense-in-depth floor for silent paths; the "30s after last stream and no unacked vouchers" rule is application-layer and lives in the cdn/client/v1 handler (not yet implemented). - Propagate the accept_task join result in idle_timeout_closes_quiet_connection so a server-side panic or error fails the test deterministically, matching the probe_roundtrip pattern. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Summary
decdn node topto the user CLI: polls the daemon's loopback/metricsHTTP endpoint every--interval-ms(default 1000) and renders a refreshing fixed-column table covering active streams, cache hit rate, and cache bytes returned.--jsonis single-shot for scripted use.reqwest::Error::is_builder()so a malformed--metrics-urldoesn't loop forever.decdn_dispatch_in_flight(≈ active streams),decdn_cache_hits_total/decdn_cache_misses_total,decdn_cache_bytes_returned_total(the proxy for "bytes served" — the network-egress counter is gated on Implement cdn/client/v1 paid delivery protocol (StreamRequest, StreamResponse, ChunkData, vouchers) #317; column is labelled to avoid confusion), plus uptime/active_connections/rpc_healthy for context.resolve_admin_url's flag → env → config → default precedence, withmetrics_port = 0as the explicit operator opt-out and the partial-deserializer pattern so unrelated typos don't breaknode top.Test plan
cargo clippy --workspace --all-targets -- -D warningscleancargo fmt -- --checkcleanpre-commit run --all-filescleandecdn_node::metrics::serveon an ephemeral loopback port and asserts snapshot fields against bytes the encoder producedErr(locks in thefetch_metricsstatus check)--metrics-urlexits immediately with `permanent error: --metrics-url is malformed or uses an unsupported scheme` instead of loopingCloses #275.
🤖 Generated with Claude Code