Repository navigation
feat(fetcher): add net_* fetcher family - #234
Conversation
|
Warning Rate limit exceeded
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 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 configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (10)
📝 WalkthroughWalkthroughThis PR adds six new network-aware fetchers within a unified ChangesNetwork Fetcher Family
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
…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]>
eda8ab3 to
450af03
Compare
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ 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
🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (8)
src/fetcher/net/mac.rs (2)
84-112: ⚖️ Poor tradeoffConsider 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 tradeoffConsider 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 tradeoffConsider 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 tradeoffConsider 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 tradeoffConsider 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 tradeoffConsider 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 tradeoffConsider 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 tradeoffConsider 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
⛔ Files ignored due to path filters (1)
Cargo.lockis excluded by!**/*.lock
📒 Files selected for processing (10)
AGENTS.mdCargo.tomlsrc/fetcher/mod.rssrc/fetcher/net/gateway.rssrc/fetcher/net/interfaces.rssrc/fetcher/net/ip.rssrc/fetcher/net/mac.rssrc/fetcher/net/mod.rssrc/fetcher/net/proxy.rssrc/fetcher/net/speedtest.rs
| 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() | ||
| } |
There was a problem hiding this comment.
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.
| 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; | ||
|
|
There was a problem hiding this comment.
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.
| 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) | ||
| } |
There was a problem hiding this comment.
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.
| 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]>
Summary
New
net_*fetcher family — 6 fetchers covering local network state plus a measured-bandwidth test. AllSafety::Safe.net_interfacesnet_ipkind= primary/v4/v6)net_macnet_gatewaykind= gateway/interface)net_proxy$*_PROXYenv (realtime)net_speedtestDesign notes
netdev-backed interface snapshot innet/mod.rs(new dep:netdev0.43).get_interfaces()leavesstatsunpopulated on Linux, sosnapshot()callsupdate_stats()— otherwise byte counters read flat zero.net_proxyis the one realtime fetcher (pure env reads); the fournetdevfetchers andnet_speedtestare cached.net_speedtesthits the hardcodedspeed.cloudflare.com(__down/__up) — config can't redirect it, so it staysSafeunder the host-fixed rule (same asweather→ Open-Meteo). The download phase is time-boxed so a slow link stays bounded within the daemon's 30s budget.net_speedwas prototyped and dropped: a single ~500ms sample frozen for the cache TTL is noise on a one-shot splash.net_speedtestmeasures connection capacity — the splash-appropriate "network speed".Ticks
net_interfaces/net_ip/net_mac/net_gateway/net_proxyon #62 and addsnet_speedtestas a new entry. Refs #41.Test plan
cargo test— 2299 passing; every fetcher's shape branches + option parsing coveredcargo clippy --all-targets -- -D warningscleancargo fmt --all -- --checkcleannet_speedtestagainst Cloudflare:↓ 246 Mbps ↑ 189 Mbps.splashboard/dashboard.tomlexercising all 6 fetchers across shapes/options🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Documentation