Skip to content

feat(fetcher): add net_* fetcher family - #234

Merged
unhappychoice merged 3 commits into
mainfrom
feat/net-fetchers
May 14, 2026
Merged

unhappychoice merged 3 commits into
mainfrom
feat/net-fetchers

Conversation

@unhappychoice

@unhappychoice unhappychoice commented May 14, 2026 •

Copy link
Copy Markdown
Owner

Summary

New net_* fetcher family — 6 fetchers covering local network state plus a measured-bandwidth test. All Safety::Safe.

fetcher what it shows shapes
net_interfaces every interface: up/down · IP · MTU · MAC Text · TextBlock · MarkdownTextBlock · Entries · Ratio · Bars · Badge
net_ip local IPv4 / IPv6 (kind = primary/v4/v6) Text · TextBlock · MarkdownTextBlock · Entries · Badge
net_mac link-layer addresses; Badge flags universal vs randomized Text · TextBlock · MarkdownTextBlock · Entries · Badge
net_gateway default-route gateway + interface (kind = gateway/interface) Text · TextBlock · MarkdownTextBlock · Entries · Badge
net_proxy $*_PROXY env (realtime) Entries · Text · TextBlock · MarkdownTextBlock · Badge
net_speedtest measured download / upload / latency Text · TextBlock · MarkdownTextBlock · Entries · Bars · Badge

Design notes

  • Shared netdev-backed interface snapshot in net/mod.rs (new dep: netdev 0.43). get_interfaces() leaves stats unpopulated on Linux, so snapshot() calls update_stats() — otherwise byte counters read flat zero.
  • net_proxy is the one realtime fetcher (pure env reads); the four netdev fetchers and net_speedtest are cached.
  • net_speedtest hits the hardcoded speed.cloudflare.com (__down / __up) — config can't redirect it, so it stays Safe under the host-fixed rule (same as weather → Open-Meteo). The download phase is time-boxed so a slow link stays bounded within the daemon's 30s budget.
  • An instantaneous-throughput net_speed was prototyped and dropped: a single ~500ms sample frozen for the cache TTL is noise on a one-shot splash. net_speedtest measures connection capacity — the splash-appropriate "network speed".

Ticks net_interfaces / net_ip / net_mac / net_gateway / net_proxy on #62 and adds net_speedtest as a new entry. Refs #41.

Test plan

  • cargo test — 2299 passing; every fetcher's shape branches + option parsing covered
  • cargo clippy --all-targets -- -D warnings clean
  • cargo fmt --all -- --check clean
  • live net_speedtest against Cloudflare: ↓ 246 Mbps ↑ 189 Mbps
  • tty smoke test via a throwaway .splashboard/dashboard.toml exercising all 6 fetchers across shapes/options

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added comprehensive network monitoring: view active network interfaces with status, display IPv4/IPv6 addresses, check MAC addresses, identify default gateway and routing information, and detect proxy configuration.
    • Added internet speed testing to measure download and upload bandwidth.
  • Documentation

    • Updated fetcher reference documentation to reflect real-time capabilities.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 14, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@unhappychoice has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 46 minutes and 2 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 388095af-9f41-444a-bcdc-7beaf9f30759

📥 Commits

Reviewing files that changed from the base of the PR and between eda8ab3 and 54caacd.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (10)
  • AGENTS.md
  • Cargo.toml
  • src/fetcher/mod.rs
  • src/fetcher/net/gateway.rs
  • src/fetcher/net/interfaces.rs
  • src/fetcher/net/ip.rs
  • src/fetcher/net/mac.rs
  • src/fetcher/net/mod.rs
  • src/fetcher/net/proxy.rs
  • src/fetcher/net/speedtest.rs
📝 Walkthrough

Walkthrough

This PR adds six new network-aware fetchers within a unified net/ module family, wired into the built-in fetcher registry. The changes provide gateway/interface/IP/MAC information snapshots, an environment-based proxy reader, and a bandwidth speedtest utility.

Changes

Network Fetcher Family

Layer / File(s) Summary
Dependencies and registry integration
Cargo.toml, src/fetcher/mod.rs
Adds netdev = "0.43" dependency and exports the new net submodule; Registry::with_builtins iterates over net::cached_fetchers() and net::realtime_fetchers() to register them.
Net module infrastructure and utilities
src/fetcher/net/mod.rs
Defines shared NetIface and GatewayInfo data structures; implements snapshot() to normalize raw netdev interfaces, default_gateway() and gateway_ip() for routing info, and primary_interface() for selection; provides parse_options(), options_placeholder(), and cache_key() helpers used by all net fetchers.
Cached network interface fetchers
src/fetcher/net/gateway.rs, src/fetcher/net/interfaces.rs, src/fetcher/net/ip.rs, src/fetcher/net/mac.rs
Four cached fetchers snapshot interface data and render across multiple shapes: net_gateway reports default-route gateway and interface details; net_interfaces summarizes all interfaces with status/MTU/address info; net_ip exposes IPv4/IPv6 addresses with protocol/stack selection; net_mac reports MAC addresses with universal/randomized classification. All support option-driven rendering (e.g., kind, interface selectors).
Realtime proxy reader and bandwidth tester
src/fetcher/net/proxy.rs, src/fetcher/net/speedtest.rs
net_proxy is a realtime fetcher reading http_proxy/https_proxy/no_proxy environment variables and reporting proxy status (prefering HTTPS, showing direct/proxied badge). net_speedtest is an advanced async fetcher measuring download/upload bandwidth and latency by making HTTP requests to speed.cloudflare.com, with per-shape rendering of Mbps and tier-based badge status.
Documentation
AGENTS.md
Removes pomodoro from the documented list of realtime fetcher values.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • unhappychoice/splashboard#28: Earlier work on the fetcher framework and Registry::with_builtins wiring that this PR extends with net fetcher registration.
  • unhappychoice/splashboard#54: Introduced the option_schemas and sample_body API contract that the new net fetchers implement.
  • unhappychoice/splashboard#152: Similar fetcher module integration pattern, extending Registry::with_builtins to wire additional fetcher families.

Poem

🐰 A network of bunnies now hops in splashboard's sight,
Peeking at gateways, IPs, and proxy might!
From Cloudflare's speed to the MAC address bright,
The net fetchers gather all network delight. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 46.79% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(fetcher): add net_* fetcher family' directly and accurately summarizes the main change: adding a new family of network-related fetchers.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/net-fetchers

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

unhappychoice and others added 2 commits May 14, 2026 18:43
…roxy / speedtest

Six Safe-class fetchers for local network state plus a measured-bandwidth test:

- net_interfaces — per-interface state / IP / MTU / MAC (netdev-backed)
- net_ip — local IPv4 / IPv6 addresses
- net_mac — link-layer addresses, universal-vs-randomized badge
- net_gateway — default-route gateway + interface
- net_proxy — $*_PROXY env (realtime; the four netdev fetchers are cached)
- net_speedtest — real download / upload / latency test against the fixed
  speed.cloudflare.com endpoint, Safe under the host-fixed rule

Shared netdev-backed interface snapshot lives in net/mod.rs. net_speedtest
time-boxes the download phase so a slow link stays bounded within the daemon
budget. New dependency: netdev 0.43.

Refs #41, #62.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
pomodoro / focus_timer were dropped from the #62 roadmap — a one-shot splash
keeps no persistent session state, so a pomodoro timer doesn't fit the model.
Remove the stale RealtimeFetcher example reference.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@codecov

codecov Bot commented May 14, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.00608% with 171 lines in your changes missing coverage. Please review.
✅ Project coverage is 94.38%. Comparing base (1b62650) to head (54caacd).

Files with missing lines Patch % Lines
src/fetcher/net/speedtest.rs 60.99% 94 Missing ⚠️
src/fetcher/net/mod.rs 85.79% 24 Missing ⚠️
src/fetcher/net/mac.rs 90.44% 17 Missing ⚠️
src/fetcher/net/ip.rs 93.00% 14 Missing ⚠️
src/fetcher/net/gateway.rs 91.09% 13 Missing ⚠️
src/fetcher/net/proxy.rs 96.22% 6 Missing ⚠️
src/fetcher/net/interfaces.rs 98.61% 3 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #234      +/-   ##
==========================================
- Coverage   94.57%   94.38%   -0.20%     
==========================================
  Files         195      202       +7     
  Lines       50240    51556    +1316     
==========================================
+ Hits        47514    48659    +1145     
- Misses       2726     2897     +171     
Files with missing lines Coverage Δ
src/fetcher/mod.rs 99.15% <100.00%> (+0.01%) ⬆️
src/fetcher/net/interfaces.rs 98.61% <98.61%> (ø)
src/fetcher/net/proxy.rs 96.22% <96.22%> (ø)
src/fetcher/net/gateway.rs 91.09% <91.09%> (ø)
src/fetcher/net/ip.rs 93.00% <93.00%> (ø)
src/fetcher/net/mac.rs 90.44% <90.44%> (ø)
src/fetcher/net/mod.rs 85.79% <85.79%> (ø)
src/fetcher/net/speedtest.rs 60.99% <60.99%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (8)
src/fetcher/net/mac.rs (2)

84-112: ⚖️ Poor tradeoff

Consider extracting shape-specific body constructors.

body_for_shape() spans 29 lines. Extracting each shape's body construction into dedicated helpers would align with the 10-15 line guideline.

As per coding guidelines: "Write single-responsibility functions with approximately 10-15 lines maximum".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fetcher/net/mac.rs` around lines 84 - 112, The body_for_shape function is
too long and should be split into small helper constructors: create helpers like
build_text_body(ifaces, interface), build_textblock_body(ifaces),
build_markdown_textblock_body(ifaces), build_entries_body(ifaces), and
build_badge_body(ifaces, interface) and have body_for_shape simply match Shape
and call the appropriate helper (returning Option<Body> same as before); keep
helper names unique so you can locate them in the diff (e.g., build_text_body,
build_textblock_body, build_markdown_textblock_body, build_entries_body,
build_badge_body) and move the with_mac/map/collect logic into those helpers to
keep each function ~10–15 lines.

132-157: ⚖️ Poor tradeoff

Consider simplifying mac_badge() with helper functions.

This 26-line function combines interface selection, MAC extraction, and badge classification. Extracting the classification logic or using early returns would improve clarity and align with the 10-15 line guideline.

As per coding guidelines: "Write single-responsibility functions with approximately 10-15 lines maximum".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fetcher/net/mac.rs` around lines 132 - 157, mac_badge currently mixes
interface selection, MAC extraction, and classification in one long function;
split responsibilities by extracting a helper that classifies a MAC string into
a BadgeData (e.g. classify_mac(mac: &str) -> BadgeData using
is_locally_administered) and another small helper for selecting the interface if
needed (or use early returns after primary_interface/ifaces lookup), then have
mac_badge call those helpers and return early for None cases; reference
mac_badge, is_locally_administered, primary_interface, NetIface, BadgeData, and
Status when making the refactor.
src/fetcher/net/interfaces.rs (1)

52-81: ⚖️ Poor tradeoff

Consider extracting shape-specific body constructors.

body_for_shape() spans 30 lines. Extracting each shape's body construction into dedicated helpers would align with the 10-15 line guideline and improve modularity.

As per coding guidelines: "Write single-responsibility functions with approximately 10-15 lines maximum".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fetcher/net/interfaces.rs` around lines 52 - 81, body_for_shape currently
contains many shape-specific constructions in one long function; extract each
case into its own small helper (e.g. make_entries_body -> calls entries_body,
make_text_body -> builds Body::Text using headline, make_textblock_body ->
builds TextBlock using row_line, make_markdown_textblock_body -> builds the
markdown join using iface_summary, make_bars_body -> builds Bars using Bar
mapping, make_ratio_body -> wraps up_ratio, make_badge_body -> wraps
connectivity_badge) and replace each match arm in body_for_shape with a call to
the corresponding helper so body_for_shape becomes a thin dispatcher and each
helper stays within ~10–15 lines.
src/fetcher/net/mod.rs (2)

74-97: ⚖️ Poor tradeoff

Consider extracting the interface-mapping logic into a helper function.

The snapshot() function spans 24 lines and includes both iteration setup and per-interface transformation logic. Extracting the mapping closure into a separate function would improve readability and align with the 10-15 line guideline.

As per coding guidelines: "Write single-responsibility functions with approximately 10-15 lines maximum".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fetcher/net/mod.rs` around lines 74 - 97, Extract the per-interface
mapping closure in snapshot() into a small helper function (e.g., fn
map_netdev_iface(i: netdev::Interface) -> NetIface) that performs
i.update_stats(), reads fields (is_loopback(), is_up(), default, if_type.name(),
mac_addr, ipv4/ipv6 addr(), mtu, stats.rx_bytes/tx_bytes, name) and returns a
NetIface; then have snapshot() call
netdev::get_interfaces().into_iter().map(map_netdev_iface).collect() to keep
snapshot() focused and under the 10–15 line guideline.

99-118: ⚖️ Poor tradeoff

Consider breaking down default_gateway() into smaller helpers.

This 20-line function mixes iteration, conditional logic, and fallback handling. Extracting the fallback path or the IP-resolution step would improve clarity and align with the 10-15 line guideline.

As per coding guidelines: "Write single-responsibility functions with approximately 10-15 lines maximum".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fetcher/net/mod.rs` around lines 99 - 118, The default_gateway() function
mixes interface iteration, gateway IP extraction and a fallback lookup; split
responsibilities by extracting at least one helper: e.g., create a helper
resolve_from_interfaces() that iterates netdev::get_interfaces() and returns
Option<GatewayInfo> (using gateway_ip and iface.name), and a separate helper
resolve_from_fallback() that wraps netdev::get_default_gateway() -> Option<Ip>
and returns GatewayInfo with interface None; then have default_gateway() call
the interface helper and fall back to the fallback helper, keeping each function
~10-15 lines and reusing the existing gateway_ip and GatewayInfo types.
src/fetcher/net/ip.rs (2)

93-121: ⚖️ Poor tradeoff

Consider extracting shape-specific body constructors.

body_for_shape() spans 29 lines. Extracting each shape's body construction into dedicated helpers would align with the 10-15 line guideline.

As per coding guidelines: "Write single-responsibility functions with approximately 10-15 lines maximum".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fetcher/net/ip.rs` around lines 93 - 121, The body_for_shape function is
too large; extract each shape's construction into small helpers to improve
readability and single-responsibility: create functions like
body_for_text(ifaces, kind) calling text_value, body_for_text_block(ifaces)
using addressed and addr_strings, body_for_markdown_text_block(ifaces) building
the joined lines, body_for_entries(ifaces) constructing EntriesData/Entry, and
body_for_badge(ifaces) delegating to ip_badge; then refactor body_for_shape to
match Shape and call the new helpers (Text -> body_for_text, TextBlock ->
body_for_text_block, MarkdownTextBlock -> body_for_markdown_text_block, Entries
-> body_for_entries, Badge -> body_for_badge) and return None for the default
case. Ensure the helpers use the existing addressed, addr_strings, text_value,
and ip_badge helpers so behavior is unchanged.

158-177: ⚖️ Poor tradeoff

Consider simplifying ip_badge() with early returns or helper functions.

This 20-line function has nested match arms. Breaking it into smaller helpers (e.g., classify_stack()) or using early returns would improve clarity and align with the 10-15 line guideline.

As per coding guidelines: "Write single-responsibility functions with approximately 10-15 lines maximum".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fetcher/net/ip.rs` around lines 158 - 177, ip_badge is doing multiple
responsibilities in one match; refactor it to be smaller and clearer by
extracting a helper like classify_stack(primary: &NetIface) -> BadgeData or
using early returns: call primary_interface(ifaces) -> Option<NetIface>, return
the Error badge if None, then check ipv4/ipv6 presence in sequence and return
the appropriate BadgeData (Status::Ok with "dual-stack"/"IPv4 <addr>"/"IPv6
only") so the main ip_badge function is ~10-15 lines and the logic for deciding
labels is isolated (refer to ip_badge, primary_interface, NetIface, BadgeData,
and Status to locate where to change).
src/fetcher/net/gateway.rs (1)

91-118: ⚖️ Poor tradeoff

Consider extracting shape-specific body constructors.

body_for_shape() spans 28 lines with nested match arms. Extracting each shape's body construction into dedicated functions (e.g., text_body(), entries_body(), badge_body()) would align with the 10-15 line guideline and improve testability.

As per coding guidelines: "Write single-responsibility functions with approximately 10-15 lines maximum".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fetcher/net/gateway.rs` around lines 91 - 118, The body_for_shape
function has many match arms and should be split into small helpers; create
dedicated constructors like text_body(gw: &GatewayInfo, kind: GatewayKind) ->
Body, textblock_body(gw: &GatewayInfo) -> Body, markdown_textblock_body(gw:
&GatewayInfo) -> Body, entries_body(gw: &GatewayInfo) -> Body, and
badge_body(gw: &GatewayInfo) -> Body, then simplify body_for_shape to match
Shape and call these helpers (using existing utilities text_value,
gateway_field, interface_field, entry, gateway_badge); ensure each helper
returns the same Body variants and preserve the early None return for the
wildcard arm.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/fetcher/net/mod.rs`:
- Around line 74-97: The snapshot() function currently ignores errors from
i.update_stats() which then causes rx_bytes/tx_bytes to silently default to 0;
change the code to capture the Result from i.update_stats() and handle failures
explicitly: call i.update_stats() into a let res = i.update_stats() and on
Err(log::warn!/tracing::warn!) emit a warning including the interface identifier
(i.name or i.mac_addr) and the error, then proceed to build NetIface so callers
still get an entry but with logged context; alternatively, if you prefer
surfacing the error in data, add an Option<String> stats_error field to NetIface
and set it to Some(error.to_string()) when update_stats() fails and leave
rx_bytes/tx_bytes as None or 0 accordingly so consumers can detect the failure.

In `@src/fetcher/net/speedtest.rs`:
- Around line 34-42: The download loop in net_speedtest uses REQUEST_TIMEOUT and
CHUNK_BYTES such that slow links can timeout per chunk and cause an immediate
FetchError; instead, modify the download logic in net_speedtest to treat
per-request timeouts as transient: catch timeout errors from the per-chunk
fetch, do not return FetchError immediately, and continue attempting additional
chunk requests until DOWNLOAD_BUDGET elapses while accumulating bytes read to
compute a lower throughput; optionally adjust REQUEST_TIMEOUT or derive a
dynamic per-chunk timeout from CHUNK_BYTES to reduce spurious timeouts, and
ensure the final result reports a low speed rather than failing outright.
- Around line 185-191: measure_latency currently treats any HTTP response
(including 4xx/5xx) as a successful latency measurement; update measure_latency
to verify the response status before treating it as success by checking
resp.status().is_success() (or equivalent) after
client.get(&url).send().await.ok()? and only proceed to read body and return
elapsed if the status is successful; return None for non-success statuses or
errors to avoid reporting fast error responses as valid latency.

---

Nitpick comments:
In `@src/fetcher/net/gateway.rs`:
- Around line 91-118: The body_for_shape function has many match arms and should
be split into small helpers; create dedicated constructors like text_body(gw:
&GatewayInfo, kind: GatewayKind) -> Body, textblock_body(gw: &GatewayInfo) ->
Body, markdown_textblock_body(gw: &GatewayInfo) -> Body, entries_body(gw:
&GatewayInfo) -> Body, and badge_body(gw: &GatewayInfo) -> Body, then simplify
body_for_shape to match Shape and call these helpers (using existing utilities
text_value, gateway_field, interface_field, entry, gateway_badge); ensure each
helper returns the same Body variants and preserve the early None return for the
wildcard arm.

In `@src/fetcher/net/interfaces.rs`:
- Around line 52-81: body_for_shape currently contains many shape-specific
constructions in one long function; extract each case into its own small helper
(e.g. make_entries_body -> calls entries_body, make_text_body -> builds
Body::Text using headline, make_textblock_body -> builds TextBlock using
row_line, make_markdown_textblock_body -> builds the markdown join using
iface_summary, make_bars_body -> builds Bars using Bar mapping, make_ratio_body
-> wraps up_ratio, make_badge_body -> wraps connectivity_badge) and replace each
match arm in body_for_shape with a call to the corresponding helper so
body_for_shape becomes a thin dispatcher and each helper stays within ~10–15
lines.

In `@src/fetcher/net/ip.rs`:
- Around line 93-121: The body_for_shape function is too large; extract each
shape's construction into small helpers to improve readability and
single-responsibility: create functions like body_for_text(ifaces, kind) calling
text_value, body_for_text_block(ifaces) using addressed and addr_strings,
body_for_markdown_text_block(ifaces) building the joined lines,
body_for_entries(ifaces) constructing EntriesData/Entry, and
body_for_badge(ifaces) delegating to ip_badge; then refactor body_for_shape to
match Shape and call the new helpers (Text -> body_for_text, TextBlock ->
body_for_text_block, MarkdownTextBlock -> body_for_markdown_text_block, Entries
-> body_for_entries, Badge -> body_for_badge) and return None for the default
case. Ensure the helpers use the existing addressed, addr_strings, text_value,
and ip_badge helpers so behavior is unchanged.
- Around line 158-177: ip_badge is doing multiple responsibilities in one match;
refactor it to be smaller and clearer by extracting a helper like
classify_stack(primary: &NetIface) -> BadgeData or using early returns: call
primary_interface(ifaces) -> Option<NetIface>, return the Error badge if None,
then check ipv4/ipv6 presence in sequence and return the appropriate BadgeData
(Status::Ok with "dual-stack"/"IPv4 <addr>"/"IPv6 only") so the main ip_badge
function is ~10-15 lines and the logic for deciding labels is isolated (refer to
ip_badge, primary_interface, NetIface, BadgeData, and Status to locate where to
change).

In `@src/fetcher/net/mac.rs`:
- Around line 84-112: The body_for_shape function is too long and should be
split into small helper constructors: create helpers like
build_text_body(ifaces, interface), build_textblock_body(ifaces),
build_markdown_textblock_body(ifaces), build_entries_body(ifaces), and
build_badge_body(ifaces, interface) and have body_for_shape simply match Shape
and call the appropriate helper (returning Option<Body> same as before); keep
helper names unique so you can locate them in the diff (e.g., build_text_body,
build_textblock_body, build_markdown_textblock_body, build_entries_body,
build_badge_body) and move the with_mac/map/collect logic into those helpers to
keep each function ~10–15 lines.
- Around line 132-157: mac_badge currently mixes interface selection, MAC
extraction, and classification in one long function; split responsibilities by
extracting a helper that classifies a MAC string into a BadgeData (e.g.
classify_mac(mac: &str) -> BadgeData using is_locally_administered) and another
small helper for selecting the interface if needed (or use early returns after
primary_interface/ifaces lookup), then have mac_badge call those helpers and
return early for None cases; reference mac_badge, is_locally_administered,
primary_interface, NetIface, BadgeData, and Status when making the refactor.

In `@src/fetcher/net/mod.rs`:
- Around line 74-97: Extract the per-interface mapping closure in snapshot()
into a small helper function (e.g., fn map_netdev_iface(i: netdev::Interface) ->
NetIface) that performs i.update_stats(), reads fields (is_loopback(), is_up(),
default, if_type.name(), mac_addr, ipv4/ipv6 addr(), mtu,
stats.rx_bytes/tx_bytes, name) and returns a NetIface; then have snapshot() call
netdev::get_interfaces().into_iter().map(map_netdev_iface).collect() to keep
snapshot() focused and under the 10–15 line guideline.
- Around line 99-118: The default_gateway() function mixes interface iteration,
gateway IP extraction and a fallback lookup; split responsibilities by
extracting at least one helper: e.g., create a helper resolve_from_interfaces()
that iterates netdev::get_interfaces() and returns Option<GatewayInfo> (using
gateway_ip and iface.name), and a separate helper resolve_from_fallback() that
wraps netdev::get_default_gateway() -> Option<Ip> and returns GatewayInfo with
interface None; then have default_gateway() call the interface helper and fall
back to the fallback helper, keeping each function ~10-15 lines and reusing the
existing gateway_ip and GatewayInfo types.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f2d195db-1797-4081-979c-ee4d58accab6

📥 Commits

Reviewing files that changed from the base of the PR and between 1b62650 and eda8ab3.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (10)
  • AGENTS.md
  • Cargo.toml
  • src/fetcher/mod.rs
  • src/fetcher/net/gateway.rs
  • src/fetcher/net/interfaces.rs
  • src/fetcher/net/ip.rs
  • src/fetcher/net/mac.rs
  • src/fetcher/net/mod.rs
  • src/fetcher/net/proxy.rs
  • src/fetcher/net/speedtest.rs

Comment thread src/fetcher/net/mod.rs
Comment on lines +74 to +97
pub(crate) fn snapshot() -> Vec<NetIface> {
netdev::get_interfaces()
.into_iter()
.map(|mut i| {
// `get_interfaces()` leaves `stats` unpopulated on Linux — it builds interfaces with
// `stats: None` and expects an explicit refresh. Without this, the byte counters are
// always zero and `net_interfaces`' byte-count `Bars` would be flat.
let _ = i.update_stats();
NetIface {
loopback: i.is_loopback(),
up: i.is_up(),
is_default: i.default,
kind: i.if_type.name(),
mac: i.mac_addr.map(|m| m.to_string()),
ipv4: i.ipv4.iter().map(|n| n.addr()).collect(),
ipv6: i.ipv6.iter().map(|n| n.addr()).collect(),
mtu: i.mtu,
rx_bytes: i.stats.as_ref().map(|s| s.rx_bytes).unwrap_or(0),
tx_bytes: i.stats.as_ref().map(|s| s.tx_bytes).unwrap_or(0),
name: i.name,
}
})
.collect()
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Consider handling update_stats() failure explicitly.

Line 81 silently ignores update_stats() errors with let _ = i.update_stats();. When this call fails (possible on some platforms), rx_bytes and tx_bytes silently default to 0 (lines 91-92), which could mislead users into thinking interfaces have no traffic. Consider logging failures or surfacing them in the interface data.

Possible approach
-            let _ = i.update_stats();
+            if i.update_stats().is_err() {
+                tracing::debug!("failed to update stats for interface {}", i.name);
+            }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fetcher/net/mod.rs` around lines 74 - 97, The snapshot() function
currently ignores errors from i.update_stats() which then causes
rx_bytes/tx_bytes to silently default to 0; change the code to capture the
Result from i.update_stats() and handle failures explicitly: call
i.update_stats() into a let res = i.update_stats() and on
Err(log::warn!/tracing::warn!) emit a warning including the interface identifier
(i.name or i.mac_addr) and the error, then proceed to build NetIface so callers
still get an entry but with logged context; alternatively, if you prefer
surfacing the error in data, add an Option<String> stats_error field to NetIface
and set it to Some(error.to_string()) when update_stats() fails and leave
rx_bytes/tx_bytes as None or 0 accordingly so consumers can detect the failure.

Comment on lines +34 to +42
const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
/// Wall-clock cap on the download phase — chunks are pulled until this elapses.
const DOWNLOAD_BUDGET: Duration = Duration::from_secs(3);
/// Bytes per download request. Small enough that a single slow chunk overruns the budget only
/// marginally, large enough to measure a fast link without HTTP overhead dominating.
const CHUNK_BYTES: u64 = 2_000_000;
/// Single upload payload size. Modest so a typical link finishes well inside the daemon budget.
const UPLOAD_BYTES: usize = 2_000_000;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Handle slow-link downloads without hard failure

With Line 39 (CHUNK_BYTES = 2_000_000) and Line 34 (REQUEST_TIMEOUT = 5s), links below ~3.2 Mbps can time out every chunk; then Line 135 returns a hard FetchError. That makes net_speedtest fail exactly on slow connections instead of reporting a low reading.

Suggested adjustment
-const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
+const REQUEST_TIMEOUT: Duration = Duration::from_secs(12);

-const CHUNK_BYTES: u64 = 2_000_000;
+const CHUNK_BYTES: u64 = 256_000;

 async fn measure_download(client: &Client) -> Result<f64, FetchError> {
@@
-    if total == 0 {
-        return Err(FetchError::Failed(
-            "net_speedtest: download produced no data".into(),
-        ));
-    }
+    if total == 0 {
+        return Ok(0.0);
+    }
     Ok(bytes_to_mbps(total, elapsed))
 }

Also applies to: 124-140, 142-160

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fetcher/net/speedtest.rs` around lines 34 - 42, The download loop in
net_speedtest uses REQUEST_TIMEOUT and CHUNK_BYTES such that slow links can
timeout per chunk and cause an immediate FetchError; instead, modify the
download logic in net_speedtest to treat per-request timeouts as transient:
catch timeout errors from the per-chunk fetch, do not return FetchError
immediately, and continue attempting additional chunk requests until
DOWNLOAD_BUDGET elapses while accumulating bytes read to compute a lower
throughput; optionally adjust REQUEST_TIMEOUT or derive a dynamic per-chunk
timeout from CHUNK_BYTES to reduce spurious timeouts, and ensure the final
result reports a low speed rather than failing outright.

Comment on lines +185 to +191
async fn measure_latency(client: &Client) -> Option<u64> {
let url = format!("{DOWN_URL}?bytes=0");
let start = Instant::now();
let resp = client.get(&url).send().await.ok()?;
let _ = resp.bytes().await.ok()?;
Some(start.elapsed().as_millis() as u64)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Ignore non-success latency responses

Line 188 accepts any HTTP status as latency success. A fast 4xx/5xx/proxy error can be reported as valid latency.

Suggested fix
 async fn measure_latency(client: &Client) -> Option<u64> {
     let url = format!("{DOWN_URL}?bytes=0");
     let start = Instant::now();
-    let resp = client.get(&url).send().await.ok()?;
+    let resp = client.get(&url).send().await.ok()?;
+    if !resp.status().is_success() {
+        return None;
+    }
     let _ = resp.bytes().await.ok()?;
     Some(start.elapsed().as_millis() as u64)
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async fn measure_latency(client: &Client) -> Option<u64> {
let url = format!("{DOWN_URL}?bytes=0");
let start = Instant::now();
let resp = client.get(&url).send().await.ok()?;
let _ = resp.bytes().await.ok()?;
Some(start.elapsed().as_millis() as u64)
}
async fn measure_latency(client: &Client) -> Option<u64> {
let url = format!("{DOWN_URL}?bytes=0");
let start = Instant::now();
let resp = client.get(&url).send().await.ok()?;
if !resp.status().is_success() {
return None;
}
let _ = resp.bytes().await.ok()?;
Some(start.elapsed().as_millis() as u64)
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fetcher/net/speedtest.rs` around lines 185 - 191, measure_latency
currently treats any HTTP response (including 4xx/5xx) as a successful latency
measurement; update measure_latency to verify the response status before
treating it as success by checking resp.status().is_success() (or equivalent)
after client.get(&url).send().await.ok()? and only proceed to read body and
return elapsed if the status is successful; return None for non-success statuses
or errors to avoid reporting fast error responses as valid latency.

Windows env vars are case-insensitive, so `https_proxy` / `HTTPS_PROXY` are
the same variable there — the lowercase-over-uppercase precedence the test
asserts only exists on Unix. `env_either` itself stays correct on Windows
(it just reads the one variable twice).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@unhappychoice
unhappychoice merged commit 07fe9fc into main May 14, 2026
7 checks passed
@unhappychoice
unhappychoice deleted the feat/net-fetchers branch May 14, 2026 09:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant