Repository navigation
feat(ops): surface fetch errors in UI and log file (closes #95) - #103
Conversation
Resolves #95. Fetch failures used to be silent: `runtime.rs:555` discarded both `FetchError::Failed` and deadline timeouts via `.ok()?.ok()?`, so a failing widget just stayed blank until TTL expired. - Wire `tracing` + `tracing-appender` (daily rotation, keep 3 files) under `$HOME/.splashboard/logs/`. `SPLASHBOARD_LOG=debug|info|error` toggles verbosity; defaults to `error` so the log only fills when something actually breaks. - Runtime `fetch_all` now lifts `Err(FetchError)` → `⚠ <msg>` placeholder and `Elapsed` → `⏱ timed out` placeholder, persisting both to the cache with a 30s error TTL (`ERROR_CACHE_TTL_SECS`) so the next render sees the warning instead of stale success data. - `CacheEntry` gains `kind: CacheEntryKind { Ok, Err, Timeout }` so diagnostics can tell success from failure without sniffing the body. Missing on legacy cache files deserializes back to `Ok` via `#[serde(default)]`. - Convert every cached fetcher's `Ok(placeholder(...))` bail-out to `return Err(FetchError::Failed(...))`, collapsing ~4 lines per call site to a `?`-propagating one-liner. Per-fetcher `placeholder()` helpers are gone (common.rs, weather.rs, avatar.rs, repo.rs). Realtime fetchers (clock/*, system.rs) keep their inline placeholders since their trait signature is infallible by design. Out of scope (deliberate): variant B (`last_ok` + `last_err` cache compositor), panic-hook capture, remote telemetry, the `splashboard logs` subcommand, and the docs-site "Debugging" page. All tracked in #95 as follow-ups. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
📝 WalkthroughWalkthroughThis PR implements comprehensive error handling and logging infrastructure for fetch failures. It adds tracing-based logging with file persistence, introduces a Changes
Sequence Diagram(s)sequenceDiagram
actor CLI as CLI / Daemon
participant RT as Runtime<br/>(fetch_all)
participant Cache as Cache
participant Logger as Logger
participant Fetcher as Fetcher
Note over CLI,Fetcher: Old Flow (Silent Failures)
CLI->>RT: Request fetch
RT->>Fetcher: Call fetch()
Fetcher-->>RT: Err(FetchError)
RT->>RT: .ok()? drops error silently
RT-->>CLI: None (blank widget)
Note over CLI,Fetcher: New Flow (Explicit Error Handling)
CLI->>RT: Request fetch
RT->>Fetcher: Call fetch()
alt Success
Fetcher-->>RT: Ok(Payload)
RT->>Cache: Store with kind=Ok, ttl=default
else Fetch Failed
Fetcher-->>RT: Err(FetchError)
RT->>Logger: Log error event
RT->>RT: Generate error_placeholder()
RT->>Cache: Store with kind=Err, ttl=ERROR_CACHE_TTL
else Timeout
Fetcher-->>RT: Timeout elapsed
RT->>Logger: Log timeout event
RT->>RT: Generate timeout_placeholder()
RT->>Cache: Store with kind=Timeout, ttl=ERROR_CACHE_TTL
end
RT->>Cache: Read payload
Cache-->>RT: CacheEntry {kind, payload}
RT-->>CLI: Render with visible ⚠ placeholder
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 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 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 #103 +/- ##
==========================================
+ Coverage 76.71% 76.73% +0.02%
==========================================
Files 86 92 +6
Lines 14303 15352 +1049
==========================================
+ Hits 10973 11781 +808
- Misses 3330 3571 +241
🚀 New features to boost your workflow:
|
…lift - `github/client.rs`: mention both the placeholder and the log line now flow from the REST error message, not just the placeholder. - `github/contributors_monthly.rs`: the 202-stats-warming path returns `Err` now; call that out explicitly so the module doc-comment tracks the new control flow. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/runtime.rs (1)
526-610:⚠️ Potential issue | 🟡 MinorError TTL can exceed a widget's configured
refresh_interval.
ERROR_CACHE_TTL_SECS = 30is applied unconditionally on theErr/Timeoutarms, butttlon theOkarm comes fromw.refresh_interval.unwrap_or(DEFAULT_REFRESH_SECS). For a widget configured with a sub-30s refresh (e.g.refresh_interval = 5), a transient blip will pin the widget on the⚠placeholder for up to 30s — longer than the user's own refresh cadence — becauseshould_refreshreads the error entry as "fresh".The docstring's rationale ("Set well below the 60s default refresh so the next tick retries") only holds when
refresh_interval >= 30. Consider clamping to the user's interval so the error TTL never exceeds what a successful fetch would have used:🔧 Proposed clamp
- let ttl = w.refresh_interval.unwrap_or(DEFAULT_REFRESH_SECS); + let ok_ttl = w.refresh_interval.unwrap_or(DEFAULT_REFRESH_SECS); + let err_ttl = ok_ttl.min(ERROR_CACHE_TTL_SECS); let fetcher_name = fetcher.name().to_string(); set.spawn(async move { let _lock = lock; match tokio::time::timeout(deadline, fetcher.fetch(&ctx)).await { - Ok(Ok(payload)) => (id, cache_key, ttl, CacheEntryKind::Ok, payload), + Ok(Ok(payload)) => (id, cache_key, ok_ttl, CacheEntryKind::Ok, payload), Ok(Err(e)) => { … - (id, cache_key, ERROR_CACHE_TTL_SECS, CacheEntryKind::Err, …) + (id, cache_key, err_ttl, CacheEntryKind::Err, …) } Err(_) => { … - (id, cache_key, ERROR_CACHE_TTL_SECS, CacheEntryKind::Timeout, …) + (id, cache_key, err_ttl, CacheEntryKind::Timeout, …) } } });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/runtime.rs` around lines 526 - 610, In fetch_all the error/timeout branches use the constant ERROR_CACHE_TTL_SECS unconditionally which can exceed a widget's configured refresh_interval; change those branches to clamp the error TTL to the widget's configured ttl (computed as w.refresh_interval.unwrap_or(DEFAULT_REFRESH_SECS)) by computing let ttl = w.refresh_interval.unwrap_or(DEFAULT_REFRESH_SECS) earlier (already present) and use something like let err_ttl = std::cmp::min(ERROR_CACHE_TTL_SECS, ttl) then replace ERROR_CACHE_TTL_SECS in the CacheEntryKind::Err and CacheEntryKind::Timeout returns with that err_ttl so errors/timeouts never produce a cache TTL longer than the widget's normal refresh interval.
🧹 Nitpick comments (5)
src/main.rs (1)
120-124: Minor: init order means clap parse errors bypass the log sink.
logging::init()runs afterCli::parse(), so argument-parsing failures are printed by clap to stderr but not captured in$HOME/.splashboard/logs/splashboard.log. That's arguably fine (clap's diagnostics are already user-facing), just flagging since the PR advertises "every fetch failure + startup event" landing in the log file. If the intent is the log file is authoritative for post-mortems, consider swapping the order:🔧 Optional swap
- let cli = Cli::parse(); - logging::init(); + logging::init(); + let cli = Cli::parse();🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/main.rs` around lines 120 - 124, Move the logging initialization before argument parsing so clap parse errors are captured by the app logger: in the async fn main() (the main function), call logging::init() before invoking Cli::parse() (the Cli::parse() call) so startup/parse diagnostics are routed into the log sink rather than only to stderr.src/fetcher/github/contributors_monthly.rs (1)
94-106: Optional: collapseStatsOutcomenow thatComputingis always re-raised asErr.With this change, the
Computingvariant is constructed infetch_statsonly to be immediately converted toFetchError::Failedhere. You can fold the mapping intofetch_statsand drop the intermediate enum — the caller then just uses?and the stats list. No behavior change; just fewer moving parts.♻️ Sketch
- match fetch_stats(&slug).await? { - StatsOutcome::Computing => Err(FetchError::Failed( - "github: stats warming up (refresh in a minute)".into(), - )), - StatsOutcome::Ready(stats) => { - let rows = top_contributors(&stats, days, limit); - Ok(payload(render_body( - &rows, - ctx.shape.unwrap_or(Shape::Bars), - ))) - } - } + let stats = fetch_stats(&slug).await?; + let rows = top_contributors(&stats, days, limit); + Ok(payload(render_body(&rows, ctx.shape.unwrap_or(Shape::Bars))))And in
fetch_stats, returnErr(FetchError::Failed("github: stats warming up (refresh in a minute)".into()))for the 202 branch, dropping theStatsOutcomeenum entirely.As per coding guidelines: "Keep functions small with single responsibility (~10–15 lines)" — this also trims
fetchslightly.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/fetcher/github/contributors_monthly.rs` around lines 94 - 106, The match on StatsOutcome in the fetch function can be removed by changing fetch_stats to return Result<Stats, FetchError> directly: update fetch_stats to convert the 202/Computing branch into Err(FetchError::Failed("github: stats warming up (refresh in a minute)".into())), drop the StatsOutcome enum, and have callers (the function containing match) simply use let stats = fetch_stats(&slug).await?; then call top_contributors(&stats, days, limit) and continue returning the payload; ensure all other call sites of fetch_stats are updated to expect a Result<Stats, FetchError>.src/logging.rs (2)
36-62: Minor: concurrentinit()calls can waste a background worker.Two threads racing into
init()can both pass theGUARD.get().is_some()check and each construct an appender +tracing_appender::non_blocking(...)worker thread. The loser'stry_init()andGUARD.set()both fail, and itsguardis dropped locally — so its background worker is torn down immediately. Functionally safe, but it spawns and drops a writer thread for nothing.Not worth blocking on, but
GUARD.get_or_init(...)(building the appender + installing subscriber inside the closure and returning the guard) would collapse the race into a single critical section. Leaving as optional since the current fall-through path is the common case and already correct.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/logging.rs` around lines 36 - 62, Concurrent calls to init() can race and each create a tracing_appender::non_blocking writer thread that is immediately dropped by the loser; fix by collapsing init into a single critical section via GUARD.get_or_init (or equivalent) so only one thread builds the appender, calls tracing_appender::non_blocking(appender), installs the subscriber via subscriber.try_init(), and sets/returns the guard; move the build_appender, non_blocking call, subscriber construction/try_init, and GUARD.set() logic inside the GUARD.get_or_init closure and return the guard so races no longer spawn redundant background workers (refer to init(), GUARD, build_appender, tracing_appender::non_blocking, subscriber.try_init(), and GUARD.set()).
64-72: Change&PathBufto&Pathto align with clippy'sptr_arglint.The parameter type
&PathBufforces callers to own the allocation unnecessarily;&Pathaccepts both&PathBufand&PathviaAsRef<Path>. TheBuilder::buildmethod in tracing-appender 0.2 already accepts this pattern. Currently, the test callsite (line 84) works around this with.to_path_buf(), which becomes unnecessary after the fix.🔧 Proposed fix
-fn build_appender(dir: &PathBuf) -> Option<tracing_appender::rolling::RollingFileAppender> { +fn build_appender(dir: &Path) -> Option<tracing_appender::rolling::RollingFileAppender> { Builder::new() .rotation(Rotation::DAILY) .filename_prefix(LOG_FILENAME_PREFIX) .filename_suffix(LOG_FILENAME_SUFFIX) .max_log_files(MAX_LOG_FILES) .build(dir) .ok() }Update callsites:
Line 46: Already passes
&PathBufdirectly, which will work as&Path.Line 84: Remove unnecessary allocation:
-let appender = build_appender(&dir.path().to_path_buf()).expect("appender builds"); +let appender = build_appender(dir.path()).expect("appender builds");🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/logging.rs` around lines 64 - 72, Change the build_appender signature to accept a borrowed Path instead of a PathBuf to satisfy clippy's ptr_arg: update fn build_appender(dir: &PathBuf) -> ... to use &Path (i.e., dir: &Path), adjust internal uses accordingly (Builder::build accepts &Path), and update all callsites (notably the test that currently uses .to_path_buf()) to pass a &Path or &PathBuf directly without allocating a new PathBuf.src/fetcher/mod.rs (1)
149-174: LGTM — placeholder helpers mirrorshape_mismatch_placeholder.Two-line structure (
⚠/⏱+ log-dir pointer) is consistent with the existing trust/shape-mismatch placeholders and keeps the runtime callers trivial.One small consideration:
error_placeholderinterpolates the rawmsgwithout truncation or newline scrubbing. AFetchError::Failedwhose message contains a newline or runs long will break the "one-line reason" contract from issue#95and may render awkwardly in narrow slots. Consider sanitizing (first line only, width cap) here so every caller gets the invariant for free.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/fetcher/mod.rs` around lines 149 - 174, In error_placeholder, sanitize the incoming msg so the first line-only / width-capped invariant is always preserved: strip newlines and take only the first line of msg, trim whitespace, and truncate to a reasonable width (e.g. 80 chars) adding an ellipsis if truncated before inserting into TextBlockData::lines; keep the rest of the Payload shape (icon/status/format and the "see $HOME/.splashboard/logs" second line) unchanged so callers of error_placeholder get a single concise reason string every time.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/fetcher/github/contributors_monthly.rs`:
- Around line 89-97: In the fetch function's StatsOutcome::Computing match arm
(in src/fetcher/github/contributors_monthly.rs) change the hardcoded "github:
stats warming up (refresh in a minute)" message used in the FetchError::Failed
return so it doesn't promise "in a minute"; either reference the actual retry
TTL constant (e.g., ERROR_CACHE_TTL_SECS) to interpolate the real wait time or
use a neutral phrase like "github: stats warming up (try again later)" so the
message aligns with the runtime error-cache TTL and fetcher refresh behavior.
---
Outside diff comments:
In `@src/runtime.rs`:
- Around line 526-610: In fetch_all the error/timeout branches use the constant
ERROR_CACHE_TTL_SECS unconditionally which can exceed a widget's configured
refresh_interval; change those branches to clamp the error TTL to the widget's
configured ttl (computed as w.refresh_interval.unwrap_or(DEFAULT_REFRESH_SECS))
by computing let ttl = w.refresh_interval.unwrap_or(DEFAULT_REFRESH_SECS)
earlier (already present) and use something like let err_ttl =
std::cmp::min(ERROR_CACHE_TTL_SECS, ttl) then replace ERROR_CACHE_TTL_SECS in
the CacheEntryKind::Err and CacheEntryKind::Timeout returns with that err_ttl so
errors/timeouts never produce a cache TTL longer than the widget's normal
refresh interval.
---
Nitpick comments:
In `@src/fetcher/github/contributors_monthly.rs`:
- Around line 94-106: The match on StatsOutcome in the fetch function can be
removed by changing fetch_stats to return Result<Stats, FetchError> directly:
update fetch_stats to convert the 202/Computing branch into
Err(FetchError::Failed("github: stats warming up (refresh in a
minute)".into())), drop the StatsOutcome enum, and have callers (the function
containing match) simply use let stats = fetch_stats(&slug).await?; then call
top_contributors(&stats, days, limit) and continue returning the payload; ensure
all other call sites of fetch_stats are updated to expect a Result<Stats,
FetchError>.
In `@src/fetcher/mod.rs`:
- Around line 149-174: In error_placeholder, sanitize the incoming msg so the
first line-only / width-capped invariant is always preserved: strip newlines and
take only the first line of msg, trim whitespace, and truncate to a reasonable
width (e.g. 80 chars) adding an ellipsis if truncated before inserting into
TextBlockData::lines; keep the rest of the Payload shape (icon/status/format and
the "see $HOME/.splashboard/logs" second line) unchanged so callers of
error_placeholder get a single concise reason string every time.
In `@src/logging.rs`:
- Around line 36-62: Concurrent calls to init() can race and each create a
tracing_appender::non_blocking writer thread that is immediately dropped by the
loser; fix by collapsing init into a single critical section via
GUARD.get_or_init (or equivalent) so only one thread builds the appender, calls
tracing_appender::non_blocking(appender), installs the subscriber via
subscriber.try_init(), and sets/returns the guard; move the build_appender,
non_blocking call, subscriber construction/try_init, and GUARD.set() logic
inside the GUARD.get_or_init closure and return the guard so races no longer
spawn redundant background workers (refer to init(), GUARD, build_appender,
tracing_appender::non_blocking, subscriber.try_init(), and GUARD.set()).
- Around line 64-72: Change the build_appender signature to accept a borrowed
Path instead of a PathBuf to satisfy clippy's ptr_arg: update fn
build_appender(dir: &PathBuf) -> ... to use &Path (i.e., dir: &Path), adjust
internal uses accordingly (Builder::build accepts &Path), and update all
callsites (notably the test that currently uses .to_path_buf()) to pass a &Path
or &PathBuf directly without allocating a new PathBuf.
In `@src/main.rs`:
- Around line 120-124: Move the logging initialization before argument parsing
so clap parse errors are captured by the app logger: in the async fn main() (the
main function), call logging::init() before invoking Cli::parse() (the
Cli::parse() call) so startup/parse diagnostics are routed into the log sink
rather than only to stderr.
🪄 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: accbaf4c-9056-405a-9498-a01fd2ba6c9c
⛔ Files ignored due to path filters (1)
Cargo.lockis excluded by!**/*.lock
📒 Files selected for processing (28)
Cargo.tomlsrc/cache.rssrc/fetcher/github/action_history.rssrc/fetcher/github/action_status.rssrc/fetcher/github/assigned_issues.rssrc/fetcher/github/avatar.rssrc/fetcher/github/client.rssrc/fetcher/github/common.rssrc/fetcher/github/contributions.rssrc/fetcher/github/contributors_monthly.rssrc/fetcher/github/good_first_issues.rssrc/fetcher/github/languages.rssrc/fetcher/github/my_prs.rssrc/fetcher/github/notifications.rssrc/fetcher/github/recent_releases.rssrc/fetcher/github/repo.rssrc/fetcher/github/repo_issues.rssrc/fetcher/github/repo_prs.rssrc/fetcher/github/repo_stars.rssrc/fetcher/github/review_requests.rssrc/fetcher/github/user.rssrc/fetcher/mod.rssrc/fetcher/weather.rssrc/lib.rssrc/logging.rssrc/main.rssrc/paths.rssrc/runtime.rs
💤 Files with no reviewable changes (1)
- src/fetcher/github/common.rs
| async fn fetch(&self, ctx: &FetchContext) -> Result<Payload, FetchError> { | ||
| let opts: Options = match parse_options(ctx.options.as_ref()) { | ||
| Ok(o) => o, | ||
| Err(msg) => return Ok(placeholder(&msg)), | ||
| }; | ||
| let slug = match resolve_repo(opts.repo.as_deref()) { | ||
| Ok(s) => s, | ||
| Err(e) => return Ok(placeholder(&e.to_string())), | ||
| }; | ||
| let opts: Options = parse_options(ctx.options.as_ref()).map_err(FetchError::Failed)?; | ||
| let slug = resolve_repo(opts.repo.as_deref())?; | ||
| let limit = opts.limit.unwrap_or(DEFAULT_LIMIT).clamp(1, 30) as usize; | ||
| let days = opts.days.unwrap_or(30).clamp(7, 365) as i64; | ||
| match fetch_stats(&slug).await? { | ||
| StatsOutcome::Computing => Ok(placeholder( | ||
| "github: stats warming up (refresh in a minute)", | ||
| StatsOutcome::Computing => Err(FetchError::Failed( | ||
| "github: stats warming up (refresh in a minute)".into(), | ||
| )), |
There was a problem hiding this comment.
Minor: warming-up text will be cached for the full error TTL.
With the runtime's ~30 s ERROR_CACHE_TTL_SECS, a 202 "stats warming up" response will show the ⚠ github: stats warming up (refresh in a minute) placeholder for ~30 s before the next attempt. The message suggests "refresh in a minute" but the actual retry cadence is governed by the error TTL and the fetcher's refresh interval — worth aligning the copy (or the TTL) so users aren't misled. No correctness issue.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/fetcher/github/contributors_monthly.rs` around lines 89 - 97, In the
fetch function's StatsOutcome::Computing match arm (in
src/fetcher/github/contributors_monthly.rs) change the hardcoded "github: stats
warming up (refresh in a minute)" message used in the FetchError::Failed return
so it doesn't promise "in a minute"; either reference the actual retry TTL
constant (e.g., ERROR_CACHE_TTL_SECS) to interpolate the real wait time or use a
neutral phrase like "github: stats warming up (try again later)" so the message
aligns with the runtime error-cache TTL and fetcher refresh behavior.
Summary
Resolves #95. Fetch failures used to be silent —
runtime.rs's.ok()?.ok()?dropped bothFetchError::Failedand deadline timeouts on the floor, so a failing widget stayed blank until its TTL rolled over and nothing was logged anywhere.fetch_allnow turnsErr(FetchError)into a⚠ <msg>placeholder andtokio::time::Elapsedinto a⏱ timed outplaceholder. Both pathstracing::error!/tracing::warn!the failure and write the outcome to the cache with a 30s error TTL (ERROR_CACHE_TTL_SECS), so the next render sees the warning instead of stale success data.tracingwiring:tracing-subscriber+tracing-appender(daily rotation, keep 3 files) under$HOME/.splashboard/logs/.SPLASHBOARD_LOG=debug|info|errortoggles verbosity; defaults toerrorso the log only fills when something actually breaks.CacheEntry.kind: newCacheEntryKind { Ok, Err, Timeout }.#[serde(default)]keeps back-compat — legacy cache files without the field deserialize asOk.Ok(placeholder(...))bail-out becomesreturn Err(FetchError::Failed(...)). Per-fetcherplaceholder()helpers ingithub/common.rs,weather.rs,github/avatar.rs, andgithub/repo.rsare gone, replaced by the onefetcher::error_placeholder+timeout_placeholderpair. Realtime fetchers (clock/*,system.rs) keep their inline placeholders — their trait signature is infallible by design.Out of scope (deliberate, tracked in #95 as follow-ups): variant B (
last_ok+last_errcache + renderer-side compositor), panic-hook capture, remote telemetry, thesplashboard logssubcommand, and the docs-site "Debugging" cookbook page.Test plan
cargo test— 492 unit + 12 bin tests passcargo clippy --all-targets -- -D warningscargo fmt --all -- --checkCacheEntryKindlegacy deserialize, runtime liftsErr→ placeholder +CacheEntryKind::Errcache write, runtime lifts timeout → placeholder +CacheEntryKind::Timeoutcache write, log appender writes a file🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes