Repository navigation
feat(node): add decdn node peers over loopback JSON-RPC admin surface (#247) - #260
Conversation
There was a problem hiding this comment.
Pull request overview
Adds a loopback-only admin HTTP surface to the node runtime and a new operator CLI (decdn node peers) that queries /v1/peers to inspect the gossip peer table, along with supporting config/ADR updates.
Changes:
- Introduces
GET /v1/peerson a loopback-bound admin HTTP server, wired into runtime startup/shutdown. - Adds
decdn node peersCLI (table or JSON output, optional region filter) that queries the admin surface. - Extends config with
observability.admin_port(default9191,0disables) and rejects collisions withmetrics_port.
Reviewed changes
Copilot reviewed 21 out of 22 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/node/tests/config_validate.rs | Updates resolved-config test fixture to include admin_port. |
| crates/node/tests/admin_peers.rs | New integration tests covering /v1/peers, 404/405 behavior, sorting, and shutdown behavior. |
| crates/node/src/runtime/mod.rs | Binds/spawns admin server, logs admin port, and integrates admin shutdown into runtime sequence. |
| crates/node/src/main.rs | Adds dispatch for new Command::Node. |
| crates/node/src/lib.rs | Exposes new admin module from the library crate. |
| crates/node/src/config/types.rs | Adds observability.admin_port to file-deserializable config types. |
| crates/node/src/config/resolved.rs | Adds resolved admin_port: Option<u16> to runtime config. |
| crates/node/src/config/mod.rs | Adds default admin port, resolves/validates admin port (including collision check), and adds unit tests. |
| crates/node/src/commands/node.rs | Implements decdn node peers HTTP client + output formatting and filtering. |
| crates/node/src/commands/mod.rs | Exposes node commands module and prints admin_port in config validation summary; updates default config template. |
| crates/node/src/cli/run.rs | Adds --admin-port / DECDN_ADMIN_PORT CLI/env support. |
| crates/node/src/cli/node.rs | Defines decdn node CLI args and peers subcommand flags. |
| crates/node/src/cli/mod.rs | Wires new node subcommand into top-level CLI. |
| crates/node/src/admin.rs | New hyper-based admin server implementation with /v1/peers. |
| crates/node/Cargo.toml | Adds serde_json and reqwest dependencies for CLI/admin JSON handling. |
| crates/gossip/src/peer_table.rs | Derives Serialize/Deserialize on PeerEntry. |
| crates/gossip/Cargo.toml | Adds serde dependency (derive) to support PeerEntry serde derives. |
| adr/architecture.md | Adds ADR 025 to the architecture index. |
| adr/025-local-admin-http.md | New ADR describing the local admin HTTP surface and CLI. |
| Cargo.toml | Adds workspace serde_json dependency. |
| Cargo.lock | Locks new dependency additions (serde_json, reqwest, serde in gossip). |
| CLAUDE.md | Bumps “next ADR number” note to 026. |
💡 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 implements ADR 025, introducing a loopback-only HTTP admin surface for deCDN nodes. It adds a /v1/peers endpoint to expose the gossip peer table and a new decdn node peers CLI command. The feedback suggests using the existing const-hex crate for hex encoding, optimizing concurrency by moving sorting logic outside of the peer table read lock, and ensuring the CLI correctly utilizes the provided configuration path for URL resolution.
Addresses PR #260 review feedback: - `decdn node peers --config <path>` now reads observability.admin_port from the TOML (expanded tildes handled); explicit admin_port = 0 is a hard error so the CLI doesn't silently probe the default instead. - Sort the peers response after dropping the peer-table read lock so announce writers aren't blocked on the sort's CPU time. - ObservabilityConfig.admin_port doc, runtime "admin disabled" log line, and ADR 025 all now match the actual resolution: missing = default 9191, explicit 0 = disabled. - Push back on the const_hex suggestion: it's only a transitive dep via alloy, not a direct one. The 15-line custom hex_encode is zero new dependencies and already covered by tests. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Addresses the 14 important items from the comprehensive review:
Shared DTO (was dup'd server↔client):
- Move PeerView/PeersResponse to admin.rs as pub(crate), import from
commands/node.rs so the two sides can't drift.
- Tighten PeerView doc — "stays stable" claim was false because
LoadHint is still a transitive protocol type.
Runtime shutdown ordering:
- Fire metrics_stop_tx/admin_stop_tx before awaiting router.shutdown()
so HTTP listeners don't keep accepting while router drain blocks.
CLI URL resolution:
- Drop manual std::env::var("DECDN_ADMIN_URL") — clap's env= attribute
already folds it into args.admin_url; the manual branch was dead.
- Explicit --config pointing at a missing file now errors (mirrors
decdn run); only the default-path fall-through silently uses the
built-in default.
- Re-export DEFAULT_ADMIN_PORT from config module so commands/node.rs
doesn't duplicate the literal.
CLI errors:
- Split reqwest connect / timeout / other into distinct operator
messages so ECONNREFUSED vs lock-stall vs TLS-weirdness are
distinguishable at a glance.
Docs & logs:
- PeersArgs::config now correctly states the global -c isn't plumbed
into node subcommands.
- --admin-port help no longer pretends to have a clap default.
- "admin disabled" log no longer pins the source to TOML.
- Drop the stale "regardless of server's whitespace" comment — server
uses compact JSON.
Tests:
- render_json round-trips filter output (covers the --json + --region
branch).
- cli_peers_surfaces_non_2xx covers the !is_success bail! via a real
404 from the admin server.
- single_peer_serializes_with_hex_node_id now seeds first_seen=100 and
last_seen=300 so a field-swap regression is catchable.
- filter_by_region_is_case_insensitive now asserts exact surviving
node_ids, not just length + the filter predicate reapplied.
- port_from_config_file_missing_explicit_errors covers the new
explicit-path error path.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
/gemini review |
Introduces a loopback-only admin HTTP surface (ADR 025) on observability.admin_port (default 9191), with GET /v1/peers as its first route. Adds the decdn node subcommand group whose first child, decdn node peers, fetches the gossip peer table from a running node and prints it as a human table (with --json and --region filters). The admin transport is designed for future operational routes (drain #244, health, config reload) so they can land without redesigning the transport. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
CI clippy (Rust 1.95) caught two lints the local 1.93 toolchain missed: replace `sort_by(|a, b| b.cmp(&a))` with `sort_by_key(|v| Reverse(v))` in the admin peers handler, and fold `.map(..).unwrap_or(..)` on Result into `.map_or(..)` in the wall-clock helper. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Addresses PR #260 review feedback: - `decdn node peers --config <path>` now reads observability.admin_port from the TOML (expanded tildes handled); explicit admin_port = 0 is a hard error so the CLI doesn't silently probe the default instead. - Sort the peers response after dropping the peer-table read lock so announce writers aren't blocked on the sort's CPU time. - ObservabilityConfig.admin_port doc, runtime "admin disabled" log line, and ADR 025 all now match the actual resolution: missing = default 9191, explicit 0 = disabled. - Push back on the const_hex suggestion: it's only a transitive dep via alloy, not a direct one. The 15-line custom hex_encode is zero new dependencies and already covered by tests. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Addresses the 14 important items from the comprehensive review:
Shared DTO (was dup'd server↔client):
- Move PeerView/PeersResponse to admin.rs as pub(crate), import from
commands/node.rs so the two sides can't drift.
- Tighten PeerView doc — "stays stable" claim was false because
LoadHint is still a transitive protocol type.
Runtime shutdown ordering:
- Fire metrics_stop_tx/admin_stop_tx before awaiting router.shutdown()
so HTTP listeners don't keep accepting while router drain blocks.
CLI URL resolution:
- Drop manual std::env::var("DECDN_ADMIN_URL") — clap's env= attribute
already folds it into args.admin_url; the manual branch was dead.
- Explicit --config pointing at a missing file now errors (mirrors
decdn run); only the default-path fall-through silently uses the
built-in default.
- Re-export DEFAULT_ADMIN_PORT from config module so commands/node.rs
doesn't duplicate the literal.
CLI errors:
- Split reqwest connect / timeout / other into distinct operator
messages so ECONNREFUSED vs lock-stall vs TLS-weirdness are
distinguishable at a glance.
Docs & logs:
- PeersArgs::config now correctly states the global -c isn't plumbed
into node subcommands.
- --admin-port help no longer pretends to have a clap default.
- "admin disabled" log no longer pins the source to TOML.
- Drop the stale "regardless of server's whitespace" comment — server
uses compact JSON.
Tests:
- render_json round-trips filter output (covers the --json + --region
branch).
- cli_peers_surfaces_non_2xx covers the !is_success bail! via a real
404 from the admin server.
- single_peer_serializes_with_hex_node_id now seeds first_seen=100 and
last_seen=300 so a field-swap regression is catchable.
- filter_by_region_is_case_insensitive now asserts exact surviving
node_ids, not just length + the filter predicate reapplied.
- port_from_config_file_missing_explicit_errors covers the new
explicit-path error path.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Operator-visible fixes:
- Forward the global `decdn --config` flag into `node_dispatch` so
`decdn --config foo.toml node peers` actually uses `foo.toml`
(previously silently ignored — the subcommand-level `--config`
was the only path plumbed).
- Reject `--timeout-ms 0` at entry: `Duration::ZERO` has implementation-
defined semantics in reqwest.
- Surface `PermissionDenied` distinctly from other IO errors so
operators see "permission denied; check file mode and ownership"
rather than the generic "failed to read config file".
Code-quality fixes:
- Replace `explicit: bool` with `ConfigPathSource { Explicit, Default }`
so callers can't swap polarity.
- Collapse redundant tilde expansion in `port_from_config_file`;
callers are now contract-bound to hand in already-expanded paths.
- `render_json` returns `anyhow::Result<String>` instead of leaking
`serde_json::Error`.
- `print_peers_table` → `write_peers_table(&mut impl io::Write, ...)`
so the table formatter is testable.
Docs/logs:
- ADR 025's CLI-shape section now matches the implemented precedence
(flag > config > default), including the global-`--config` fallback.
- Fix rotted `PeersResponse` doc; the borrowed variant it described
was deleted in 123c10b.
- Bump the "stop channel closed before shutdown" breadcrumbs from
`debug!` to `warn!` — they signal the HTTP server already exited
on its own, which is worth surfacing at default log level.
- Tighten the "admin disabled" log to `observability.admin_port = 0`.
Tests (+3 net, 175/175):
- `port_from_config_file_reads_admin_port_explicit_path` — covers
the (Explicit, valid file) → Some(port) case that round-1 missed.
- `write_peers_table_empty_emits_sentinel` and
`write_peers_table_renders_header_and_row` — cover the human-output
branch now that the formatter takes `impl io::Write`.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Replaces the hand-rolled hyper `GET /v1/peers` loopback admin server with a jsonrpsee 0.26 server dispatching `admin_v1_peersList` over JSON-RPC 2.0. The `#[rpc(server, client, namespace = "admin_v1")]` trait becomes the single source of truth for both the server impl and the client bindings used by `decdn node peers` and the integration tests — no more paired hand-written HTTP handler / reqwest parser that could drift field-for-field. - ADR 025 amended: versioned method namespace (`admin_v1_...`), JSON-RPC wire format, rationale for the move, hand-rolled hyper and OpenRPC-generation crates listed in alternatives-considered. - Workspace: add `jsonrpsee = 0.26` with server + http-client + macros features. Drop `reqwest` from `crates/node` (still used by `crates/cache` for origin pull-through). - `crates/node/src/admin.rs` rewritten around the trait. `AdminState`, `PeerView`, `PeersResponse`, `bind`, `serve` signatures preserved so `runtime/mod.rs` needs no edits. Concurrency via `ServerConfig::max_connections(16)`, shutdown via `ServerHandle::stop()` + `stopped()` keyed off the existing `oneshot` channel. - `crates/node/src/commands/node.rs` uses `HttpClientBuilder` plus the generated `AdminRpcClient::peers_list`. `classify_client_error` walks the source chain for `io::ErrorKind::ConnectionRefused` so the "is the node running?" hint still fires on `ECONNREFUSED`. - `tests/admin_peers.rs` reduced to 5 wire tests — round-trip empty and seeded, unknown method returns `-32601`, CLI surfaces `ECONNREFUSED`, shutdown closes listener. Per-peer shape assertions (hex, sort, field mapping) moved into admin.rs unit tests where they belong. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request implements ADR 025, introducing a loopback-only JSON-RPC 2.0 admin surface for the deCDN node. It adds a new decdn node CLI subcommand group, starting with decdn node peers to list the gossip peer table. The implementation uses jsonrpsee for both the server and client bindings. Configuration for the admin port is added to the observability section, defaulting to 9191. Feedback suggests optimizing the admin RPC handler to minimize lock contention by moving data conversion outside the read guard and refining the configuration parsing logic in the CLI to be less brittle.
9ce4b20 to
5ff502c
Compare
Two gemini-code-assist suggestions on PR #260: - admin.rs: PeerView assembly held the read lock across hex_encode and String::clone. Replace the in-lock map with a two-pass: copy a small RawPeer (raw [u8;32], cloned region, scalar fields) under the lock, then run hex_encode + final PeerView::from_raw outside. Lock-hold drops to per-entry data extraction; sort and (downstream) JSON encoding remain outside as before. - commands/node.rs: peers resolved its admin URL by parsing the full FileConfig just to read observability.admin_port, so a typo'd unrelated section (e.g. malformed [payments]) would block listing peers. Swap in a private partial deserializer (AdminPortConfig + AdminPortObservability) — serde-toml ignores unknown fields, so any other valid TOML round-trips through with no effect, and only a real parse error or a wrong type for admin_port itself surfaces. Adds a test that locks the property in. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Resolves Cargo.lock conflicts from main's dependency churn (rand 0.9 → 0.10 in #263, webpki-root-certs 1.0.6 unification). Took main's lockfile and let `cargo build` reconcile the new admin-only deps (jsonrpsee, serde_json) so versions stay pinned consistently with what the rest of the workspace now uses. Cargo.toml auto-merged: kept this branch's `serde_json` and `jsonrpsee` additions, picked up main's `rand = "0.10"` bump. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
# Conflicts: # crates/node/src/config/mod.rs # crates/node/src/runtime/mod.rs
…layout Follow-up to the main→#260 merge. Before this, there were two overlapping collision checks: `resolve_observability` rejected admin_port == metrics_port internally, and `validate_port_layout` (added by #267) rejected bind_port == metrics_port externally. Plus bind_port == admin_port was not checked at all — a gap the two-place split hid. Move the admin/metrics check into `validate_port_layout` so all three collision rules live together, add the missing bind/admin rule, and make `resolve_observability` non-fallible again (the only error it produced was the collision that now lives elsewhere). Well-known-port warnings extend to admin_port too; port 0 (OS-assigned ephemeral) and admin disabled (`None`) skip the relevant checks as before. Tests: drop the now-obsolete `resolve_observability_rejects_admin_eq_metrics`, add `validate_port_layout_rejects_admin_eq_metrics` (same behavior, moved), add `validate_port_layout_rejects_bind_equal_admin` (new coverage), and `validate_port_layout_skips_admin_when_disabled` pinning the None-skips-admin-rules contract. Drop `?` on the three resolve_ observability callers that no longer return Result. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Cargo doc with `-D warnings` failed CI on #260 with `unresolved link to 'AdminRpc'`. Root cause: jsonrpsee's `#[rpc(server, client, ...)]` macro consumes the annotated trait and emits a `AdminRpcServer` / `AdminRpcClient` pair, so the original `AdminRpc` name is not a linkable rustdoc item — only a conceptual one. Replace the `[\`AdminRpc\`]` intra-doc link with bare backticks and add a sentence naming the generated pair so a future reader knows where to look. No behavior change; doc-only.
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request implements a local admin HTTP surface using JSON-RPC 2.0, as specified in the newly introduced ADR 025. The changes include a new admin module in the node crate to handle RPC requests, a decdn node CLI subcommand group for operator-local actions like listing gossip peers, and integration into the node runtime for managed startup and graceful shutdown. Configuration for the admin port is now supported, including validation logic to prevent port collisions with metrics or network services. Feedback identifies opportunities to improve maintainability by using existing library functions for hex encoding and to optimize performance in CLI string formatting.
- `admin.rs`: drop the 15-line custom `hex_encode` helper and its test in favor of `alloy::primitives::hex::encode`. `alloy` is already a direct dep of `crates/node` (used in `config/mod.rs` for `alloy::primitives::Address`), and `alloy::primitives::hex` re-exports `const-hex`'s optimized encoder. Net: fewer lines, no new dependencies, and the remaining `single_peer_serializes_with_hex_node_id` test plus the integration-test lowercase-hex/length assertions still cover the wire contract. - `commands/node.rs`: collapse `short_node_id`'s two iterations of `hex` (once for `take(12)`, once for `chars().count()`) into a single borrowed-iterator pass — `take` then peek via `next()`. Output is unchanged for any `&str`; the prior redundant count was an O(n) walk of the full string for a yes/no question.
- `cli/node.rs`: `PeersArgs::config` doc claimed the top-level `decdn --config` was not plumbed through. It is — `main.rs:24` passes it to `node_dispatch`, which falls back to it when the subcommand's own `--config` is unset. Fix the comment to match both the code and ADR 025's resolution order. - `crates/gossip/src/peer_table.rs` + `Cargo.toml`: drop `Serialize, Deserialize` derives on `PeerEntry` and the corresponding `serde` workspace dep. The admin surface has always wired its own `PeerView` DTO (see `admin.rs`) so that internal `PeerEntry` fields don't leak onto the wire; no caller actually serdes a `PeerEntry`, so the derives were dead and the dep was speculative. YAGNI — revive if a caller ever needs it. - `tests/admin_peers.rs`: pin the `--timeout-ms > 0` guard in `commands::peers`. The guard fires before the jsonrpsee client is built (jsonrpsee reads `Duration::ZERO` as "never time out" rather than "sub-millisecond deadline"); a regression that dropped the `ensure!` would silently let operator scripts hang. - `commands/node.rs`: collapse `truncate`'s two `chars()` walks (`.take(max).collect()` + `.chars().count() > max`) into a single `by_ref() + next().is_some()` pass, matching the shape already adopted by `short_node_id`. Output is unchanged for any `&str`. Drops the six-line single-pass rationale comment from `short_node_id` now that the pattern is used twice in the file and is self-evident. - `adr/025-local-admin-http.md`: flip status `Draft` → `Accepted` on merge.
|
/gemini review |
|
Warning Gemini is experiencing higher than usual traffic and was unable to create the review. Please try again in a few hours by commenting |
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request implements ADR 025, introducing a loopback-only JSON-RPC 2.0 admin surface for deCDN nodes. It adds the decdn node CLI subcommand group, starting with a peers command to list the current gossip peer table. The implementation leverages jsonrpsee for the RPC layer, integrates the server into the node runtime with graceful shutdown support, and includes configuration validation to prevent port collisions between the admin, metrics, and network services. Comprehensive integration tests and documentation updates are also included. I have no feedback to provide.
admin_v1_health method returning node_id + uptime over the loopback admin surface (ADR 025)
#243
Summary
observability.admin_port(default9191, explicit0disables), withGET /v1/peersas its first route.decdn nodesubcommand group withdecdn node peers, which prints the running node's gossip peer table as a human table (default) or JSON (--json), with a--regionclient-side filter.oneshot-driven shutdown sequence alongside the metrics server; HTTP listeners are signaled to stop beforerouter.shutdown().awaitso they don't keep accepting during a stalled router drain.admin_port == metrics_portis rejected at config resolution.Closes #247. The admin transport is designed so future operational routes (drain #244, health, config reload) land here without redesigning the transport.
What's in the change
crates/node/src/admin.rs— hyper admin server (service_fn, semaphore-bounded, oneshot shutdown),{peers: [...]}sorted bylast_seen_usdescending, 404 on unknown path / 405 on wrong method. Owns the canonicalPeerView/PeersResponseDTOs; the CLI imports them to avoid server↔client drift.crates/node/src/cli/node.rs+crates/node/src/commands/node.rs—decdn node peersCLI. Admin-URL resolution precedence is--admin-url(incl.DECDN_ADMIN_URLvia clap'senv=) → config fileobservability.admin_port→ built-in default9191. Explicit--config <missing>errors; explicitadmin_port = 0errors. reqwest errors are split into ECONNREFUSED / timeout / other so the operator message points at the right fix.crates/node/src/config/{types,resolved,mod}.rs— newobservability.admin_port: Option<u16>; missing defaults to9191, explicit0disables; env varDECDN_ADMIN_PORT;admin_port == metrics_portrejected at startup.crates/gossip/src/peer_table.rs— derivesSerialize, DeserializeonPeerEntry(wire format is still routed through a DTO inadmin.rsso internal counters can accrete without leaking).adr/025-local-admin-http.md+adr/architecture.mdindex entry.CLAUDE.mdADR counter bumped to 026.crates/node/tests/admin_peers.rs+ per-module unit tests — empty / seeded-and-sorted / non-2xx via a real 404 / method-not-allowed / shutdown teardown, plus the explicit-missing-config and JSON-round-trip-through-filter paths.Review feedback addressed
8c743cb: clippy 1.95 lints (unnecessary_sort_by,map_unwrap_or).933dae8: wired--configinto peers URL resolution; reconciled doc/ADR/log drift on the0-disables / missing-defaults semantics.123c10b: review-agent punch list — de-dup'd DTOs, shutdown-order reshuffle, removed deadstd::env::varbranch (clap foldsDECDN_ADMIN_URLintoargs.admin_url), split reqwest connect/timeout errors, correctedPeersArgs::configdoc on global-cplumbing, strengthened test assertions (distinctfirst_seen/last_seen; exact survivingnode_ids instead of tautological predicate re-application).Test plan
cargo fmt -- --checkcargo clippy --workspace --all-targets -- -D warnings(reproduces CI's clippy 1.95)cargo nextest run— 172 tests, all pass (baseline was 143; +29 new tests)cargo deny checkpre-commit run --all-filesdecdn node --help,decdn node peers --help, connection-refused surfaces ECONNREFUSED cause and exits1.decdn node peerslists a discovered peer with monotoniclast_seen_us, and the admin port becomes unreachable after SIGTERM.🤖 Generated with Claude Code