Repository navigation
refactor(fetcher)!: split system into system_{info,monitor}_* family - #227
Conversation
Restructures the system fetcher family around a fixed 3-segment naming
pattern `system_{info|monitor}_{subject}` so siblings sort together and
the role (static identifier vs live measurement) is visible at the
fetcher name itself instead of via opaque `kind` options.
Renames:
- `system_cpu` -> `system_monitor_cpu`
- `system_memory` -> `system_monitor_memory`
- `system_uptime` -> `system_monitor_uptime`
- `system_load` -> `system_monitor_load`
- `system_processes` -> `system_monitor_processes`
- `system_disk_usage` -> `system_monitor_disk`
- `system_battery` -> `system_monitor_battery`
Split: `system` (Text+kind identity + Entries rollup) is replaced by two
focused siblings:
- `system_info_host` — Text+kind for terminal / os / os_version /
hostname / shell / arch (the original 6 identity kinds)
- `system_monitor_host` — Entries / TextBlock rollup of os / host /
uptime / load / cpu% / memory%
New `system_info_*` siblings absorb #225's 25 `system kind` extensions
(each prefix dropped because the family carries the subject):
- `system_info_cpu` — kind = model / cores / frequency / vendor
- `system_info_memory` — kind = total / swap_total
- `system_info_kernel` — kind = name / version
- `system_info_machine` — DMI host, kind = model / vendor / serial / chassis
- `system_info_board` — DMI motherboard, kind = vendor / model
- `system_info_bios` — DMI firmware, kind = vendor / version / date
- `system_info_locale` — single Text (no kind)
- `system_info_timezone` — single Text (no kind)
- `system_info_env` — kind = editor / visual / pager
- `system_info_desktop` — kind = de / wm / init
Note: "host" and "machine" trade off vs the original `#62` roadmap.
Under the new scheme, `system_info_host` is OS-side identity (terminal /
shell / arch) and `system_info_machine` is DMI hardware (vendor /
model / serial / chassis). The roadmap entry that called the DMI
cluster `system_host` is now covered by `system_info_machine`.
Templates / examples / runtime tests / xtask snapshots updated to the
new names. The `SystemKind` enum in `src/fetcher/system.rs` reverts to
its pre-#225 six-variant shape, scoped to `SystemInfoHost`.
BREAKING CHANGE: every existing `fetcher = "system*"` reference in a
user's dashboard needs renaming. The new names follow a stable pattern
`system_{info|monitor}_{subject}` so future additions slot in without
further churn.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughSplits system fetchers into system_info_* (static identity) and system_monitor_* (live metrics); adds many new fetcher modules, shared helpers, a registry, tests, templates/snapshot updates, docs and render text edits, and removes the top-level system_dmi export. ChangesSystem Fetcher Architecture Refactor
Estimated code review effort 🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
🚥 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 docstrings
🧪 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 |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #227 +/- ##
==========================================
- Coverage 95.16% 94.67% -0.50%
==========================================
Files 161 181 +20
Lines 48131 48518 +387
==========================================
+ Hits 45805 45932 +127
- Misses 2326 2586 +260
🚀 New features to boost your workflow:
|
Splits `src/fetcher/system.rs` (~2900 lines) into a directory module with
one file per fetcher. The omnibus file held 19 fetchers plus shared
helpers, which makes navigation hard and pushes well past the project's
~100-line-per-file guideline.
Layout:
src/fetcher/system/
mod.rs — shared helpers (cached caches, formatters,
env detection, payload constructors) + registration
entry points + test scaffolding
dmi.rs — DMI / SMBIOS reads (was system_dmi.rs)
info_host.rs — system_info_host (terminal / os / hostname / ...)
info_cpu.rs — system_info_cpu (model / cores / freq / vendor)
info_memory.rs — system_info_memory (total / swap_total)
info_kernel.rs — system_info_kernel (name / version)
info_machine.rs — system_info_machine (DMI host bundle)
info_board.rs — system_info_board (DMI motherboard)
info_bios.rs — system_info_bios (DMI firmware)
info_locale.rs — system_info_locale (single Text)
info_timezone.rs — system_info_timezone (single Text)
info_env.rs — system_info_env (editor / visual / pager)
info_desktop.rs — system_info_desktop (de / wm / init)
monitor_host.rs — system_monitor_host (Entries rollup)
monitor_cpu.rs — system_monitor_cpu (usage)
monitor_memory.rs — system_monitor_memory (usage)
monitor_uptime.rs — system_monitor_uptime
monitor_load.rs — system_monitor_load
monitor_processes.rs— system_monitor_processes
monitor_disk.rs — system_monitor_disk (cached fetcher)
monitor_battery.rs — system_monitor_battery (+ battery helpers)
Each per-fetcher file owns its own `Options` / `Kind` enum / `OPTION_SCHEMAS`
constant; shared helpers (`cached_cpu_info`, `format_*`, `detect_*`,
`parse_options`, `payload`, `entry`, etc.) live in `mod.rs` and are
accessed via `super::*` from submodules. Internal helpers used by the
test module in `mod.rs` are exposed as `pub(crate)` where needed.
`pub use` re-exports every `SystemMonitor*` / `SystemInfo*` struct so
external callers and the registration list see flat names.
Naming preserved from the previous commit on this branch: still
`system_{info|monitor}_{subject}` for every fetcher.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 7
🤖 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/system/mod.rs`:
- Around line 1155-1161: The ignored live test live_system_text_all_kinds() is
still invoked by a non-ignored test
(system_text_all_kinds_helper_runs_in_regular_suite), reintroducing
host-dependent behavior into the regular test suite; fix this by preventing the
helper from running in regular runs—either mark
system_text_all_kinds_helper_runs_in_regular_suite with #[ignore], make the
helper private/only callable from the ignored test, or remove the helper
entirely so live_system_text_all_kinds() is the sole invoker and remains
isolated; update references to the helper
(system_text_all_kinds_helper_runs_in_regular_suite and
live_system_text_all_kinds) accordingly.
In `@src/fetcher/system/monitor_battery.rs`:
- Around line 164-167: The read_snapshot function currently calls
self.manager.lock().expect(...), which will panic if the mutex is poisoned;
change that to handle the PoisonError and return None instead of panicking. In
read_snapshot, replace the expect-based lock with a match or if-let that does:
on Ok(guard) continue, on Err(_) immediately return None; then continue using
the guard (the same manager variable) as before when calling manager.as_ref()
and manager.batteries().
In `@src/fetcher/system/monitor_cpu.rs`:
- Line 55: The current code uses self.state.lock().expect("cpu state mutex
poisoned") which will panic on a poisoned Mutex; change it to recover from
poison by matching the Result and using PoisonError::into_inner() on Err to
obtain the inner guard instead of panicking (e.g. let mut sys = match
self.state.lock() { Ok(g) => g, Err(e) => { /* log a warning about poisoned
mutex */ e.into_inner() } }; ), so the fetcher continues running even if the
mutex was poisoned.
In `@src/fetcher/system/monitor_disk.rs`:
- Around line 48-61: The fallback for the Shape::Ratio path currently returns a
Body::Text payload when primary_disk(&disks) is None, which breaks consumers
expecting Body::Ratio; update the unwrap_or_else branch in the primary_disk
mapping to return payload(Body::Ratio(...)) with an appropriate empty or zero
RatioData (e.g., value 0.0 and label like Some("no disks") or None and
denominator None) instead of payload(Body::Text(...)); modify the code around
primary_disk(&disks).map(...).unwrap_or_else(...) so Shape::Ratio always yields
a Body::Ratio, referencing primary_disk, payload, Body::Ratio, RatioData and
disk_label as needed.
In `@src/fetcher/system/monitor_host.rs`:
- Line 77: The current code calls self.state.lock().expect(...), which will
panic on a poisoned mutex; replace this with proper PoisonError handling in the
realtime path by matching on self.state.lock() and either recovering the guard
via poison.into_inner() or returning a degraded/empty payload (or Err) instead
of aborting. Concretely, update the code that currently uses let mut sys =
self.state.lock().expect("system state mutex poisoned") to use match
self.state.lock() { Ok(g) => g, Err(poison) => { let g = poison.into_inner(); /*
optionally log warning about poisoned lock and return degraded payload or
continue with recovered g */ } } and ensure the surrounding function (the
realtime fetcher) returns a safe degraded result or logs the error rather than
panicking; reference the self.state mutex and the realtime fetcher function
where this lock is used.
In `@src/fetcher/system/monitor_memory.rs`:
- Line 60: The code currently calls self.state.lock().expect("memory state mutex
poisoned") which will panic on a poisoned mutex; change this to handle poisoning
gracefully by matching the lock result (e.g., match self.state.lock()) and on
Err(poisonErr) either log a warning (using your module's logger) and return
early from the sampling call or recover with poisonErr.into_inner() if it's safe
to continue; replace the expect call with that match/if-let flow so the sampler
degrades instead of crashing and keep the bound variable name (sys) used
downstream.
In `@src/fetcher/system/monitor_processes.rs`:
- Around line 67-69: The fetch loop currently panics on a poisoned mutex by
calling self.state.lock().expect(...); change this to handle PoisonError and
recover the inner guard via into_inner() so the process data is still read;
specifically replace the expect usage with a match (or map_err) that on Ok
returns the guard and on Err(poison) calls poison.into_inner() to get the mutex
data, then continue to call sys.refresh_processes and top_processes as before;
apply the same fix to the other system monitor fetchers (monitor_memory.rs,
monitor_host.rs, monitor_cpu.rs, monitor_battery.rs) wherever
self.state.lock().expect is used to ensure recovery instead of panicking.
🪄 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: 00ce4e3a-4429-4cb2-b188-fb0884ddf00f
📒 Files selected for processing (22)
src/fetcher/mod.rssrc/fetcher/system/dmi.rssrc/fetcher/system/info_bios.rssrc/fetcher/system/info_board.rssrc/fetcher/system/info_cpu.rssrc/fetcher/system/info_desktop.rssrc/fetcher/system/info_env.rssrc/fetcher/system/info_host.rssrc/fetcher/system/info_kernel.rssrc/fetcher/system/info_locale.rssrc/fetcher/system/info_machine.rssrc/fetcher/system/info_memory.rssrc/fetcher/system/info_timezone.rssrc/fetcher/system/mod.rssrc/fetcher/system/monitor_battery.rssrc/fetcher/system/monitor_cpu.rssrc/fetcher/system/monitor_disk.rssrc/fetcher/system/monitor_host.rssrc/fetcher/system/monitor_load.rssrc/fetcher/system/monitor_memory.rssrc/fetcher/system/monitor_processes.rssrc/fetcher/system/monitor_uptime.rs
💤 Files with no reviewable changes (1)
- src/fetcher/mod.rs
✅ Files skipped from review due to trivial changes (1)
- src/fetcher/system/info_host.rs
…review
Distributes fetcher-specific tests from the monolithic `system/mod.rs` test
block into `#[cfg(test)] mod tests` blocks colocated with each fetcher,
matching AGENTS.md's "tests live next to the code" rule. Cross-cutting
tests (registration list, shape/sample contract sweep, helper formatters,
env detection) stay in `mod.rs`.
- New `system/test_helpers.rs` (cfg-gated) shares `ctx_text`,
`ctx_with_shape`, `EnvGuard`, and `detect_terminal_with` across all
per-fetcher test modules. Submodules import via
`super::super::test_helpers::*`.
- Per-fetcher test placement:
- `monitor_cpu::tests` — load defaults / text shape (2 tests)
- `monitor_memory::tests` — ratio default / entries / text formatting (3 tests)
- `monitor_uptime::tests` — text emission (1 test)
- `monitor_load::tests` — text default / entries shape (2 tests)
- `monitor_processes::tests` — count cap / textblock formatting (2 tests)
- `monitor_disk::tests` — sample body / fetch defaults / bars (3 tests)
- `monitor_host::tests` — rollup row count / textblock format (2 tests)
- `monitor_battery::tests` — 14 tests covering text format, badge status,
state mapping, AC fallbacks, panic-free coverage; uses
`pub(crate)`-elevated internals (`BatterySnapshot`, `BatteryState`,
`format_battery_text`, etc.) which are now reachable only from
within `system_*` test modules.
- `info_host::tests` — terminal kind default / arch / placeholder
on unknown kind (3 tests)
Address CodeRabbit review on #227:
- Drop `system_text_all_kinds_helper_runs_in_regular_suite`: it called
the `#[ignore]`-d `live_system_text_all_kinds` from a regular test,
defeating the ignore boundary and reintroducing host-dependent
behaviour into `cargo test`.
- `SystemMonitorBattery::read_snapshot` no longer panics on a poisoned
manager mutex. `lock().unwrap_or_else(|e| e.into_inner())` matches
the recovery pattern used elsewhere in the codebase and keeps battery
reads working after any prior panic while holding the mutex.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
♻️ Duplicate comments (1)
src/fetcher/system/monitor_memory.rs (1)
60-60:⚠️ Potential issue | 🟠 Major | ⚡ Quick winAvoid hard panic on poisoned memory-state mutex (Line 60).
expect(...)turns a recoverable poisoned lock into a hard failure on the fetch path. Recovering withinto_inner()keeps the monitor path resilient.Suggested fix
- let mut sys = self.state.lock().expect("memory state mutex poisoned"); + let mut sys = self + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner());🤖 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/system/monitor_memory.rs` at line 60, The code currently panics on a poisoned mutex via self.state.lock().expect(...); change this to recover from a poisoned lock by matching the Result from self.state.lock() (or using unwrap_or_else/unwrap_or) and calling into_inner() on the PoisonError to obtain the inner guard, so the monitor remains resilient; update the lock acquisition at the site referencing self.state.lock() to handle Err(poison) -> poison.into_inner() and continue using the guard (e.g., bind to mut sys) instead of calling expect().
🤖 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.
Duplicate comments:
In `@src/fetcher/system/monitor_memory.rs`:
- Line 60: The code currently panics on a poisoned mutex via
self.state.lock().expect(...); change this to recover from a poisoned lock by
matching the Result from self.state.lock() (or using unwrap_or_else/unwrap_or)
and calling into_inner() on the PoisonError to obtain the inner guard, so the
monitor remains resilient; update the lock acquisition at the site referencing
self.state.lock() to handle Err(poison) -> poison.into_inner() and continue
using the guard (e.g., bind to mut sys) instead of calling expect().
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 3b5d7eb1-3302-48e4-87e6-05d933981a3e
📒 Files selected for processing (11)
src/fetcher/system/info_host.rssrc/fetcher/system/mod.rssrc/fetcher/system/monitor_battery.rssrc/fetcher/system/monitor_cpu.rssrc/fetcher/system/monitor_disk.rssrc/fetcher/system/monitor_host.rssrc/fetcher/system/monitor_load.rssrc/fetcher/system/monitor_memory.rssrc/fetcher/system/monitor_processes.rssrc/fetcher/system/monitor_uptime.rssrc/fetcher/system/test_helpers.rs
🚧 Files skipped from review as they are similar to previous changes (7)
- src/fetcher/system/monitor_host.rs
- src/fetcher/system/monitor_load.rs
- src/fetcher/system/monitor_processes.rs
- src/fetcher/system/info_host.rs
- src/fetcher/system/monitor_disk.rs
- src/fetcher/system/monitor_cpu.rs
- src/fetcher/system/monitor_battery.rs
Sweep up stale references to the pre-rename `system` / `system_cpu` / `system_memory` / `system_disk_usage` fetcher names that survived in hand-written docs and inline doc comments. The auto-generated `docs-site/src/content/docs/reference/` tree is gitignored and regenerates from source on the next `cargo xtask`, so it's left out of the commit. - `src/fetcher/mod.rs`: shape-mismatch placeholder doc example - `src/render/gauge_battery.rs`: `tone = "drain"` description - `docs-site/src/content/docs/guides/concepts/shape.md`: Ratio fetcher list - `docs-site/src/content/docs/guides/concepts/renderer.md`: animated_postfx example widget - `docs-site/src/content/docs/guides/concepts/widget.md`: Realtime widget ASCII diagram Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Apply CodeRabbit's poison-mutex feedback consistently across the new
`system_monitor_*` family and tidy a `monitor_disk` shape-fallback path:
- `monitor_cpu` / `monitor_memory` / `monitor_host` / `monitor_processes`:
replace `state.lock().expect("... mutex poisoned")` with
`unwrap_or_else(|e| e.into_inner())` so a prior panic in any other
fetcher path doesn't cascade into a hard crash on the next frame.
Matches the recovery pattern already used by `monitor_battery`.
- `monitor_disk`: when no disks are visible, the `Shape::Ratio` (and
default) branch now returns a `Body::Ratio { value: 0.0, label: "no
disks" }` payload instead of falling through to `Body::Text`. Keeps
the body type consistent with the requested shape so shape-specific
renderers don't crash on the empty-disk edge case.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/fetcher/system/monitor_host.rs (1)
76-95: ⚡ Quick winSplit
computeinto smaller single-purpose helpers.
computecurrently refreshes state, builds rows, and renders shape output in one function. Extracting row collection/rendering keeps it within the project’s function-size and single-responsibility target.Refactor sketch
impl RealtimeFetcher for SystemMonitorHost { @@ fn compute(&self, ctx: &FetchContext) -> Payload { let mut sys = self.state.lock().unwrap_or_else(|e| e.into_inner()); sys.refresh_cpu_usage(); sys.refresh_memory(); - let rows = [ + let rows = [ ("os", self.os.clone()), ("host", self.host.clone()), ("uptime", format_uptime(System::uptime())), ("load", format!("{:.2}", System::load_average().one)), ("cpu", format!("{:.0}%", sys.global_cpu_usage())), ("memory", format!("{:.0}%", memory_ratio(&sys) * 100.0)), ]; - match ctx.shape.unwrap_or(Shape::Entries) { - Shape::TextBlock => payload(Body::TextBlock(TextBlockData { - lines: rows.iter().map(|(k, v)| format!("{k}: {v}")).collect(), - })), - _ => payload(Body::Entries(EntriesData { - items: rows.iter().map(|(k, v)| entry(k, v)).collect(), - })), - } + render_rows(ctx.shape.unwrap_or(Shape::Entries), &rows) } } + +fn render_rows(shape: Shape, rows: &[(&str, String)]) -> Payload { + match shape { + Shape::TextBlock => payload(Body::TextBlock(TextBlockData { + lines: rows.iter().map(|(k, v)| format!("{k}: {v}")).collect(), + })), + _ => payload(Body::Entries(EntriesData { + items: rows.iter().map(|(k, v)| entry(k, v)).collect(), + })), + } +}As per coding guidelines, "Keep functions small with single responsibility, aiming for ~10–15 lines per function".
🤖 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/system/monitor_host.rs` around lines 76 - 95, The compute method in monitor_host.rs is doing three responsibilities (state refresh, building rows, rendering by Shape); split it into small helpers: move the row construction into a new fn build_rows(&self, sys: &System) -> Vec<(String,String)> or build_rows(&self) -> Vec<(String,String)> and create two render helpers like render_textblock(rows: &[(String,String)]) -> Payload and render_entries(rows: &[(String,String)]) -> Payload; keep compute minimal by acquiring and refreshing sys, calling build_rows, then selecting between render_textblock and render_entries based on ctx.shape (using Shape::Entries default) and returning that Payload. Reference compute, build_rows, render_textblock, render_entries, rows, FetchContext, Payload, and Shape in your changes.
🤖 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.
Nitpick comments:
In `@src/fetcher/system/monitor_host.rs`:
- Around line 76-95: The compute method in monitor_host.rs is doing three
responsibilities (state refresh, building rows, rendering by Shape); split it
into small helpers: move the row construction into a new fn build_rows(&self,
sys: &System) -> Vec<(String,String)> or build_rows(&self) ->
Vec<(String,String)> and create two render helpers like render_textblock(rows:
&[(String,String)]) -> Payload and render_entries(rows: &[(String,String)]) ->
Payload; keep compute minimal by acquiring and refreshing sys, calling
build_rows, then selecting between render_textblock and render_entries based on
ctx.shape (using Shape::Entries default) and returning that Payload. Reference
compute, build_rows, render_textblock, render_entries, rows, FetchContext,
Payload, and Shape in your changes.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 7c58ae1d-5cbd-49b7-8e29-838f53a49234
📒 Files selected for processing (5)
src/fetcher/system/monitor_cpu.rssrc/fetcher/system/monitor_disk.rssrc/fetcher/system/monitor_host.rssrc/fetcher/system/monitor_memory.rssrc/fetcher/system/monitor_processes.rs
🚧 Files skipped from review as they are similar to previous changes (4)
- src/fetcher/system/monitor_memory.rs
- src/fetcher/system/monitor_processes.rs
- src/fetcher/system/monitor_cpu.rs
- src/fetcher/system/monitor_disk.rs
Summary
Restructures the system fetcher family around a fixed 3-segment naming pattern
system_{info|monitor}_{subject}so siblings sort together and the role (static identifier vs live measurement) is visible at the fetcher name itself, not buried in opaque `kind` options.Renames (BREAKING)
Split
`system` mixed static identity (Text+kind for terminal / os / hostname / ...) with a dynamic Entries rollup (uptime / load / cpu% / memory%). Replaced by two focused siblings:
New `system_info_*` siblings
Absorb #225's 25 `system kind` extensions, prefix-stripped since the family already carries the subject:
Notes:
Templates / examples / runtime / xtask
Test plan
BREAKING CHANGE
Every existing `fetcher = "system*"` reference in a user's dashboard needs renaming. The new names follow a stable pattern `system_{info|monitor}_{subject}` so future additions slot in without further churn.
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Refactor
Documentation